Completed
Push — master ( 4836a5...d78a4d )
by Morris
25:06 queued 07:35
created
lib/private/AppConfig.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@
 block discarded – undo
160 160
 	 *
161 161
 	 * @param string $app app
162 162
 	 * @param string $key key
163
-	 * @param string|float|int $value value
163
+	 * @param string $value value
164 164
 	 * @return bool True if the value was inserted or updated, false if the value was the same
165 165
 	 */
166 166
 	public function setValue($app, $key, $value) {
Please login to merge, or discard this patch.
Indentation   +280 added lines, -280 removed lines patch added patch discarded remove patch
@@ -41,288 +41,288 @@
 block discarded – undo
41 41
  */
42 42
 class AppConfig implements IAppConfig {
43 43
 
44
-	/** @var array[] */
45
-	protected $sensitiveValues = [
46
-		'spreed' => [
47
-			'turn_server_secret',
48
-		],
49
-		'user_ldap' => [
50
-			'ldap_agent_password',
51
-		],
52
-	];
53
-
54
-	/** @var \OCP\IDBConnection */
55
-	protected $conn;
56
-
57
-	/** @var array[] */
58
-	private $cache = [];
59
-
60
-	/** @var bool */
61
-	private $configLoaded = false;
62
-
63
-	/**
64
-	 * @param IDBConnection $conn
65
-	 */
66
-	public function __construct(IDBConnection $conn) {
67
-		$this->conn = $conn;
68
-		$this->configLoaded = false;
69
-	}
70
-
71
-	/**
72
-	 * @param string $app
73
-	 * @return array
74
-	 */
75
-	private function getAppValues($app) {
76
-		$this->loadConfigValues();
77
-
78
-		if (isset($this->cache[$app])) {
79
-			return $this->cache[$app];
80
-		}
81
-
82
-		return [];
83
-	}
84
-
85
-	/**
86
-	 * Get all apps using the config
87
-	 *
88
-	 * @return array an array of app ids
89
-	 *
90
-	 * This function returns a list of all apps that have at least one
91
-	 * entry in the appconfig table.
92
-	 */
93
-	public function getApps() {
94
-		$this->loadConfigValues();
95
-
96
-		return $this->getSortedKeys($this->cache);
97
-	}
98
-
99
-	/**
100
-	 * Get the available keys for an app
101
-	 *
102
-	 * @param string $app the app we are looking for
103
-	 * @return array an array of key names
104
-	 *
105
-	 * This function gets all keys of an app. Please note that the values are
106
-	 * not returned.
107
-	 */
108
-	public function getKeys($app) {
109
-		$this->loadConfigValues();
110
-
111
-		if (isset($this->cache[$app])) {
112
-			return $this->getSortedKeys($this->cache[$app]);
113
-		}
114
-
115
-		return [];
116
-	}
117
-
118
-	public function getSortedKeys($data) {
119
-		$keys = array_keys($data);
120
-		sort($keys);
121
-		return $keys;
122
-	}
123
-
124
-	/**
125
-	 * Gets the config value
126
-	 *
127
-	 * @param string $app app
128
-	 * @param string $key key
129
-	 * @param string $default = null, default value if the key does not exist
130
-	 * @return string the value or $default
131
-	 *
132
-	 * This function gets a value from the appconfig table. If the key does
133
-	 * not exist the default value will be returned
134
-	 */
135
-	public function getValue($app, $key, $default = null) {
136
-		$this->loadConfigValues();
137
-
138
-		if ($this->hasKey($app, $key)) {
139
-			return $this->cache[$app][$key];
140
-		}
141
-
142
-		return $default;
143
-	}
144
-
145
-	/**
146
-	 * check if a key is set in the appconfig
147
-	 *
148
-	 * @param string $app
149
-	 * @param string $key
150
-	 * @return bool
151
-	 */
152
-	public function hasKey($app, $key) {
153
-		$this->loadConfigValues();
154
-
155
-		return isset($this->cache[$app][$key]);
156
-	}
157
-
158
-	/**
159
-	 * Sets a value. If the key did not exist before it will be created.
160
-	 *
161
-	 * @param string $app app
162
-	 * @param string $key key
163
-	 * @param string|float|int $value value
164
-	 * @return bool True if the value was inserted or updated, false if the value was the same
165
-	 */
166
-	public function setValue($app, $key, $value) {
167
-		if (!$this->hasKey($app, $key)) {
168
-			$inserted = (bool) $this->conn->insertIfNotExist('*PREFIX*appconfig', [
169
-				'appid' => $app,
170
-				'configkey' => $key,
171
-				'configvalue' => $value,
172
-			], [
173
-				'appid',
174
-				'configkey',
175
-			]);
176
-
177
-			if ($inserted) {
178
-				if (!isset($this->cache[$app])) {
179
-					$this->cache[$app] = [];
180
-				}
181
-
182
-				$this->cache[$app][$key] = $value;
183
-				return true;
184
-			}
185
-		}
186
-
187
-		$sql = $this->conn->getQueryBuilder();
188
-		$sql->update('appconfig')
189
-			->set('configvalue', $sql->createParameter('configvalue'))
190
-			->where($sql->expr()->eq('appid', $sql->createParameter('app')))
191
-			->andWhere($sql->expr()->eq('configkey', $sql->createParameter('configkey')))
192
-			->setParameter('configvalue', $value)
193
-			->setParameter('app', $app)
194
-			->setParameter('configkey', $key);
195
-
196
-		/*
44
+    /** @var array[] */
45
+    protected $sensitiveValues = [
46
+        'spreed' => [
47
+            'turn_server_secret',
48
+        ],
49
+        'user_ldap' => [
50
+            'ldap_agent_password',
51
+        ],
52
+    ];
53
+
54
+    /** @var \OCP\IDBConnection */
55
+    protected $conn;
56
+
57
+    /** @var array[] */
58
+    private $cache = [];
59
+
60
+    /** @var bool */
61
+    private $configLoaded = false;
62
+
63
+    /**
64
+     * @param IDBConnection $conn
65
+     */
66
+    public function __construct(IDBConnection $conn) {
67
+        $this->conn = $conn;
68
+        $this->configLoaded = false;
69
+    }
70
+
71
+    /**
72
+     * @param string $app
73
+     * @return array
74
+     */
75
+    private function getAppValues($app) {
76
+        $this->loadConfigValues();
77
+
78
+        if (isset($this->cache[$app])) {
79
+            return $this->cache[$app];
80
+        }
81
+
82
+        return [];
83
+    }
84
+
85
+    /**
86
+     * Get all apps using the config
87
+     *
88
+     * @return array an array of app ids
89
+     *
90
+     * This function returns a list of all apps that have at least one
91
+     * entry in the appconfig table.
92
+     */
93
+    public function getApps() {
94
+        $this->loadConfigValues();
95
+
96
+        return $this->getSortedKeys($this->cache);
97
+    }
98
+
99
+    /**
100
+     * Get the available keys for an app
101
+     *
102
+     * @param string $app the app we are looking for
103
+     * @return array an array of key names
104
+     *
105
+     * This function gets all keys of an app. Please note that the values are
106
+     * not returned.
107
+     */
108
+    public function getKeys($app) {
109
+        $this->loadConfigValues();
110
+
111
+        if (isset($this->cache[$app])) {
112
+            return $this->getSortedKeys($this->cache[$app]);
113
+        }
114
+
115
+        return [];
116
+    }
117
+
118
+    public function getSortedKeys($data) {
119
+        $keys = array_keys($data);
120
+        sort($keys);
121
+        return $keys;
122
+    }
123
+
124
+    /**
125
+     * Gets the config value
126
+     *
127
+     * @param string $app app
128
+     * @param string $key key
129
+     * @param string $default = null, default value if the key does not exist
130
+     * @return string the value or $default
131
+     *
132
+     * This function gets a value from the appconfig table. If the key does
133
+     * not exist the default value will be returned
134
+     */
135
+    public function getValue($app, $key, $default = null) {
136
+        $this->loadConfigValues();
137
+
138
+        if ($this->hasKey($app, $key)) {
139
+            return $this->cache[$app][$key];
140
+        }
141
+
142
+        return $default;
143
+    }
144
+
145
+    /**
146
+     * check if a key is set in the appconfig
147
+     *
148
+     * @param string $app
149
+     * @param string $key
150
+     * @return bool
151
+     */
152
+    public function hasKey($app, $key) {
153
+        $this->loadConfigValues();
154
+
155
+        return isset($this->cache[$app][$key]);
156
+    }
157
+
158
+    /**
159
+     * Sets a value. If the key did not exist before it will be created.
160
+     *
161
+     * @param string $app app
162
+     * @param string $key key
163
+     * @param string|float|int $value value
164
+     * @return bool True if the value was inserted or updated, false if the value was the same
165
+     */
166
+    public function setValue($app, $key, $value) {
167
+        if (!$this->hasKey($app, $key)) {
168
+            $inserted = (bool) $this->conn->insertIfNotExist('*PREFIX*appconfig', [
169
+                'appid' => $app,
170
+                'configkey' => $key,
171
+                'configvalue' => $value,
172
+            ], [
173
+                'appid',
174
+                'configkey',
175
+            ]);
176
+
177
+            if ($inserted) {
178
+                if (!isset($this->cache[$app])) {
179
+                    $this->cache[$app] = [];
180
+                }
181
+
182
+                $this->cache[$app][$key] = $value;
183
+                return true;
184
+            }
185
+        }
186
+
187
+        $sql = $this->conn->getQueryBuilder();
188
+        $sql->update('appconfig')
189
+            ->set('configvalue', $sql->createParameter('configvalue'))
190
+            ->where($sql->expr()->eq('appid', $sql->createParameter('app')))
191
+            ->andWhere($sql->expr()->eq('configkey', $sql->createParameter('configkey')))
192
+            ->setParameter('configvalue', $value)
193
+            ->setParameter('app', $app)
194
+            ->setParameter('configkey', $key);
195
+
196
+        /*
197 197
 		 * Only limit to the existing value for non-Oracle DBs:
198 198
 		 * http://docs.oracle.com/cd/E11882_01/server.112/e26088/conditions002.htm#i1033286
199 199
 		 * > Large objects (LOBs) are not supported in comparison conditions.
200 200
 		 */
201
-		if (!($this->conn instanceof OracleConnection)) {
202
-			// Only update the value when it is not the same
203
-			$sql->andWhere($sql->expr()->neq('configvalue', $sql->createParameter('configvalue')))
204
-				->setParameter('configvalue', $value);
205
-		}
206
-
207
-		$changedRow = (bool) $sql->execute();
208
-
209
-		$this->cache[$app][$key] = $value;
210
-
211
-		return $changedRow;
212
-	}
213
-
214
-	/**
215
-	 * Deletes a key
216
-	 *
217
-	 * @param string $app app
218
-	 * @param string $key key
219
-	 * @return boolean
220
-	 */
221
-	public function deleteKey($app, $key) {
222
-		$this->loadConfigValues();
223
-
224
-		$sql = $this->conn->getQueryBuilder();
225
-		$sql->delete('appconfig')
226
-			->where($sql->expr()->eq('appid', $sql->createParameter('app')))
227
-			->andWhere($sql->expr()->eq('configkey', $sql->createParameter('configkey')))
228
-			->setParameter('app', $app)
229
-			->setParameter('configkey', $key);
230
-		$sql->execute();
231
-
232
-		unset($this->cache[$app][$key]);
233
-		return false;
234
-	}
235
-
236
-	/**
237
-	 * Remove app from appconfig
238
-	 *
239
-	 * @param string $app app
240
-	 * @return boolean
241
-	 *
242
-	 * Removes all keys in appconfig belonging to the app.
243
-	 */
244
-	public function deleteApp($app) {
245
-		$this->loadConfigValues();
246
-
247
-		$sql = $this->conn->getQueryBuilder();
248
-		$sql->delete('appconfig')
249
-			->where($sql->expr()->eq('appid', $sql->createParameter('app')))
250
-			->setParameter('app', $app);
251
-		$sql->execute();
252
-
253
-		unset($this->cache[$app]);
254
-		return false;
255
-	}
256
-
257
-	/**
258
-	 * get multiple values, either the app or key can be used as wildcard by setting it to false
259
-	 *
260
-	 * @param string|false $app
261
-	 * @param string|false $key
262
-	 * @return array|false
263
-	 */
264
-	public function getValues($app, $key) {
265
-		if (($app !== false) === ($key !== false)) {
266
-			return false;
267
-		}
268
-
269
-		if ($key === false) {
270
-			return $this->getAppValues($app);
271
-		} else {
272
-			$appIds = $this->getApps();
273
-			$values = array_map(function($appId) use ($key) {
274
-				return isset($this->cache[$appId][$key]) ? $this->cache[$appId][$key] : null;
275
-			}, $appIds);
276
-			$result = array_combine($appIds, $values);
277
-
278
-			return array_filter($result);
279
-		}
280
-	}
281
-
282
-	/**
283
-	 * get all values of the app or and filters out sensitive data
284
-	 *
285
-	 * @param string $app
286
-	 * @return array
287
-	 */
288
-	public function getFilteredValues($app) {
289
-		$values = $this->getValues($app, false);
290
-
291
-		foreach ($this->sensitiveValues[$app] as $sensitiveKey) {
292
-			if (isset($values[$sensitiveKey])) {
293
-				$values[$sensitiveKey] = IConfig::SENSITIVE_VALUE;
294
-			}
295
-		}
296
-
297
-		return $values;
298
-	}
299
-
300
-	/**
301
-	 * Load all the app config values
302
-	 */
303
-	protected function loadConfigValues() {
304
-		if ($this->configLoaded) {
305
-			return;
306
-		}
307
-
308
-		$this->cache = [];
309
-
310
-		$sql = $this->conn->getQueryBuilder();
311
-		$sql->select('*')
312
-			->from('appconfig');
313
-		$result = $sql->execute();
314
-
315
-		// we are going to store the result in memory anyway
316
-		$rows = $result->fetchAll();
317
-		foreach ($rows as $row) {
318
-			if (!isset($this->cache[$row['appid']])) {
319
-				$this->cache[$row['appid']] = [];
320
-			}
321
-
322
-			$this->cache[$row['appid']][$row['configkey']] = $row['configvalue'];
323
-		}
324
-		$result->closeCursor();
325
-
326
-		$this->configLoaded = true;
327
-	}
201
+        if (!($this->conn instanceof OracleConnection)) {
202
+            // Only update the value when it is not the same
203
+            $sql->andWhere($sql->expr()->neq('configvalue', $sql->createParameter('configvalue')))
204
+                ->setParameter('configvalue', $value);
205
+        }
206
+
207
+        $changedRow = (bool) $sql->execute();
208
+
209
+        $this->cache[$app][$key] = $value;
210
+
211
+        return $changedRow;
212
+    }
213
+
214
+    /**
215
+     * Deletes a key
216
+     *
217
+     * @param string $app app
218
+     * @param string $key key
219
+     * @return boolean
220
+     */
221
+    public function deleteKey($app, $key) {
222
+        $this->loadConfigValues();
223
+
224
+        $sql = $this->conn->getQueryBuilder();
225
+        $sql->delete('appconfig')
226
+            ->where($sql->expr()->eq('appid', $sql->createParameter('app')))
227
+            ->andWhere($sql->expr()->eq('configkey', $sql->createParameter('configkey')))
228
+            ->setParameter('app', $app)
229
+            ->setParameter('configkey', $key);
230
+        $sql->execute();
231
+
232
+        unset($this->cache[$app][$key]);
233
+        return false;
234
+    }
235
+
236
+    /**
237
+     * Remove app from appconfig
238
+     *
239
+     * @param string $app app
240
+     * @return boolean
241
+     *
242
+     * Removes all keys in appconfig belonging to the app.
243
+     */
244
+    public function deleteApp($app) {
245
+        $this->loadConfigValues();
246
+
247
+        $sql = $this->conn->getQueryBuilder();
248
+        $sql->delete('appconfig')
249
+            ->where($sql->expr()->eq('appid', $sql->createParameter('app')))
250
+            ->setParameter('app', $app);
251
+        $sql->execute();
252
+
253
+        unset($this->cache[$app]);
254
+        return false;
255
+    }
256
+
257
+    /**
258
+     * get multiple values, either the app or key can be used as wildcard by setting it to false
259
+     *
260
+     * @param string|false $app
261
+     * @param string|false $key
262
+     * @return array|false
263
+     */
264
+    public function getValues($app, $key) {
265
+        if (($app !== false) === ($key !== false)) {
266
+            return false;
267
+        }
268
+
269
+        if ($key === false) {
270
+            return $this->getAppValues($app);
271
+        } else {
272
+            $appIds = $this->getApps();
273
+            $values = array_map(function($appId) use ($key) {
274
+                return isset($this->cache[$appId][$key]) ? $this->cache[$appId][$key] : null;
275
+            }, $appIds);
276
+            $result = array_combine($appIds, $values);
277
+
278
+            return array_filter($result);
279
+        }
280
+    }
281
+
282
+    /**
283
+     * get all values of the app or and filters out sensitive data
284
+     *
285
+     * @param string $app
286
+     * @return array
287
+     */
288
+    public function getFilteredValues($app) {
289
+        $values = $this->getValues($app, false);
290
+
291
+        foreach ($this->sensitiveValues[$app] as $sensitiveKey) {
292
+            if (isset($values[$sensitiveKey])) {
293
+                $values[$sensitiveKey] = IConfig::SENSITIVE_VALUE;
294
+            }
295
+        }
296
+
297
+        return $values;
298
+    }
299
+
300
+    /**
301
+     * Load all the app config values
302
+     */
303
+    protected function loadConfigValues() {
304
+        if ($this->configLoaded) {
305
+            return;
306
+        }
307
+
308
+        $this->cache = [];
309
+
310
+        $sql = $this->conn->getQueryBuilder();
311
+        $sql->select('*')
312
+            ->from('appconfig');
313
+        $result = $sql->execute();
314
+
315
+        // we are going to store the result in memory anyway
316
+        $rows = $result->fetchAll();
317
+        foreach ($rows as $row) {
318
+            if (!isset($this->cache[$row['appid']])) {
319
+                $this->cache[$row['appid']] = [];
320
+            }
321
+
322
+            $this->cache[$row['appid']][$row['configkey']] = $row['configvalue'];
323
+        }
324
+        $result->closeCursor();
325
+
326
+        $this->configLoaded = true;
327
+    }
328 328
 }
Please login to merge, or discard this patch.
settings/ajax/setquota.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -35,9 +35,9 @@  discard block
 block discarded – undo
35 35
 
36 36
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
37 37
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
38
-	$l = \OC::$server->getL10N('core');
39
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
40
-	exit();
38
+    $l = \OC::$server->getL10N('core');
39
+    OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
40
+    exit();
41 41
 }
42 42
 
43 43
 $username = isset($_POST["username"]) ? (string)$_POST["username"] : '';
@@ -46,32 +46,32 @@  discard block
 block discarded – undo
46 46
 $currentUserObject = \OC::$server->getUserSession()->getUser();
47 47
 $targetUserObject = \OC::$server->getUserManager()->get($username);
48 48
 if($targetUserObject !== null && $currentUserObject !== null) {
49
-	$isUserAccessible = \OC::$server->getGroupManager()->getSubAdmin()->isUserAccessible($currentUserObject, $targetUserObject);
49
+    $isUserAccessible = \OC::$server->getGroupManager()->getSubAdmin()->isUserAccessible($currentUserObject, $targetUserObject);
50 50
 }
51 51
 
52 52
 if(($username === '' && !OC_User::isAdminUser(OC_User::getUser()))
53
-	|| (!OC_User::isAdminUser(OC_User::getUser())
54
-		&& !$isUserAccessible)) {
55
-	$l = \OC::$server->getL10N('core');
56
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
57
-	exit();
53
+    || (!OC_User::isAdminUser(OC_User::getUser())
54
+        && !$isUserAccessible)) {
55
+    $l = \OC::$server->getL10N('core');
56
+    OC_JSON::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
57
+    exit();
58 58
 }
59 59
 
60 60
 //make sure the quota is in the expected format
61 61
 $quota= (string)$_POST["quota"];
62 62
 if($quota !== 'none' and $quota !== 'default') {
63
-	$quota= OC_Helper::computerFileSize($quota);
64
-	$quota=OC_Helper::humanFileSize($quota);
63
+    $quota= OC_Helper::computerFileSize($quota);
64
+    $quota=OC_Helper::humanFileSize($quota);
65 65
 }
66 66
 
67 67
 // Return Success story
68 68
 if($username) {
69
-	$targetUserObject->setQuota($quota);
69
+    $targetUserObject->setQuota($quota);
70 70
 }else{//set the default quota when no username is specified
71
-	if($quota === 'default') {//'default' as default quota makes no sense
72
-		$quota='none';
73
-	}
74
-	\OC::$server->getConfig()->setAppValue('files', 'default_quota', $quota);
71
+    if($quota === 'default') {//'default' as default quota makes no sense
72
+        $quota='none';
73
+    }
74
+    \OC::$server->getConfig()->setAppValue('files', 'default_quota', $quota);
75 75
 }
76 76
 OC_JSON::success(array("data" => array( "username" => $username , 'quota' => $quota)));
77 77
 
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -36,42 +36,42 @@
 block discarded – undo
36 36
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
37 37
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
38 38
 	$l = \OC::$server->getL10N('core');
39
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
39
+	OC_JSON::error(array('data' => array('message' => $l->t('Password confirmation is required'))));
40 40
 	exit();
41 41
 }
42 42
 
43
-$username = isset($_POST["username"]) ? (string)$_POST["username"] : '';
43
+$username = isset($_POST["username"]) ? (string) $_POST["username"] : '';
44 44
 
45 45
 $isUserAccessible = false;
46 46
 $currentUserObject = \OC::$server->getUserSession()->getUser();
47 47
 $targetUserObject = \OC::$server->getUserManager()->get($username);
48
-if($targetUserObject !== null && $currentUserObject !== null) {
48
+if ($targetUserObject !== null && $currentUserObject !== null) {
49 49
 	$isUserAccessible = \OC::$server->getGroupManager()->getSubAdmin()->isUserAccessible($currentUserObject, $targetUserObject);
50 50
 }
51 51
 
52
-if(($username === '' && !OC_User::isAdminUser(OC_User::getUser()))
52
+if (($username === '' && !OC_User::isAdminUser(OC_User::getUser()))
53 53
 	|| (!OC_User::isAdminUser(OC_User::getUser())
54 54
 		&& !$isUserAccessible)) {
55 55
 	$l = \OC::$server->getL10N('core');
56
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
56
+	OC_JSON::error(array('data' => array('message' => $l->t('Authentication error'))));
57 57
 	exit();
58 58
 }
59 59
 
60 60
 //make sure the quota is in the expected format
61
-$quota= (string)$_POST["quota"];
62
-if($quota !== 'none' and $quota !== 'default') {
63
-	$quota= OC_Helper::computerFileSize($quota);
64
-	$quota=OC_Helper::humanFileSize($quota);
61
+$quota = (string) $_POST["quota"];
62
+if ($quota !== 'none' and $quota !== 'default') {
63
+	$quota = OC_Helper::computerFileSize($quota);
64
+	$quota = OC_Helper::humanFileSize($quota);
65 65
 }
66 66
 
67 67
 // Return Success story
68
-if($username) {
68
+if ($username) {
69 69
 	$targetUserObject->setQuota($quota);
70
-}else{//set the default quota when no username is specified
71
-	if($quota === 'default') {//'default' as default quota makes no sense
72
-		$quota='none';
70
+} else {//set the default quota when no username is specified
71
+	if ($quota === 'default') {//'default' as default quota makes no sense
72
+		$quota = 'none';
73 73
 	}
74 74
 	\OC::$server->getConfig()->setAppValue('files', 'default_quota', $quota);
75 75
 }
76
-OC_JSON::success(array("data" => array( "username" => $username , 'quota' => $quota)));
76
+OC_JSON::success(array("data" => array("username" => $username, 'quota' => $quota)));
77 77
 
Please login to merge, or discard this patch.
lib/public/IAppConfig.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -31,41 +31,41 @@
 block discarded – undo
31 31
  * @since 7.0.0
32 32
  */
33 33
 interface IAppConfig {
34
-	/**
35
-	 * check if a key is set in the appconfig
36
-	 * @param string $app
37
-	 * @param string $key
38
-	 * @return bool
39
-	 * @since 7.0.0
40
-	 */
41
-	public function hasKey($app, $key);
34
+    /**
35
+     * check if a key is set in the appconfig
36
+     * @param string $app
37
+     * @param string $key
38
+     * @return bool
39
+     * @since 7.0.0
40
+     */
41
+    public function hasKey($app, $key);
42 42
 
43
-	/**
44
-	 * get multiply values, either the app or key can be used as wildcard by setting it to false
45
-	 *
46
-	 * @param string|false $key
47
-	 * @param string|false $app
48
-	 * @return array|false
49
-	 * @since 7.0.0
50
-	 */
51
-	public function getValues($app, $key);
43
+    /**
44
+     * get multiply values, either the app or key can be used as wildcard by setting it to false
45
+     *
46
+     * @param string|false $key
47
+     * @param string|false $app
48
+     * @return array|false
49
+     * @since 7.0.0
50
+     */
51
+    public function getValues($app, $key);
52 52
 
53
-	/**
54
-	 * get all values of the app or and filters out sensitive data
55
-	 *
56
-	 * @param string $app
57
-	 * @return array
58
-	 * @since 12.0.0
59
-	 */
60
-	public function getFilteredValues($app);
53
+    /**
54
+     * get all values of the app or and filters out sensitive data
55
+     *
56
+     * @param string $app
57
+     * @return array
58
+     * @since 12.0.0
59
+     */
60
+    public function getFilteredValues($app);
61 61
 
62
-	/**
63
-	 * Get all apps using the config
64
-	 * @return array an array of app ids
65
-	 *
66
-	 * This function returns a list of all apps that have at least one
67
-	 * entry in the appconfig table.
68
-	 * @since 7.0.0
69
-	 */
70
-	public function getApps();
62
+    /**
63
+     * Get all apps using the config
64
+     * @return array an array of app ids
65
+     *
66
+     * This function returns a list of all apps that have at least one
67
+     * entry in the appconfig table.
68
+     * @since 7.0.0
69
+     */
70
+    public function getApps();
71 71
 }
Please login to merge, or discard this patch.
lib/private/Installer.php 2 patches
Indentation   +562 added lines, -562 removed lines patch added patch discarded remove patch
@@ -57,566 +57,566 @@
 block discarded – undo
57 57
  * This class provides the functionality needed to install, update and remove apps
58 58
  */
59 59
 class Installer {
60
-	/** @var AppFetcher */
61
-	private $appFetcher;
62
-	/** @var IClientService */
63
-	private $clientService;
64
-	/** @var ITempManager */
65
-	private $tempManager;
66
-	/** @var ILogger */
67
-	private $logger;
68
-	/** @var IConfig */
69
-	private $config;
70
-	/** @var array - for caching the result of app fetcher */
71
-	private $apps = null;
72
-	/** @var bool|null - for caching the result of the ready status */
73
-	private $isInstanceReadyForUpdates = null;
74
-
75
-	/**
76
-	 * @param AppFetcher $appFetcher
77
-	 * @param IClientService $clientService
78
-	 * @param ITempManager $tempManager
79
-	 * @param ILogger $logger
80
-	 * @param IConfig $config
81
-	 */
82
-	public function __construct(AppFetcher $appFetcher,
83
-								IClientService $clientService,
84
-								ITempManager $tempManager,
85
-								ILogger $logger,
86
-								IConfig $config) {
87
-		$this->appFetcher = $appFetcher;
88
-		$this->clientService = $clientService;
89
-		$this->tempManager = $tempManager;
90
-		$this->logger = $logger;
91
-		$this->config = $config;
92
-	}
93
-
94
-	/**
95
-	 * Installs an app that is located in one of the app folders already
96
-	 *
97
-	 * @param string $appId App to install
98
-	 * @throws \Exception
99
-	 * @return string app ID
100
-	 */
101
-	public function installApp($appId) {
102
-		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
104
-			throw new \Exception('App not found in any app directory');
105
-		}
106
-
107
-		$basedir = $app['path'].'/'.$appId;
108
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
-
110
-		$l = \OC::$server->getL10N('core');
111
-
112
-		if(!is_array($info)) {
113
-			throw new \Exception(
114
-				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
-					[$info['name']]
116
-				)
117
-			);
118
-		}
119
-
120
-		$version = \OCP\Util::getVersion();
121
-		if (!\OC_App::isAppCompatible($version, $info)) {
122
-			throw new \Exception(
123
-				// TODO $l
124
-				$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
-					[$info['name']]
126
-				)
127
-			);
128
-		}
129
-
130
-		// check for required dependencies
131
-		\OC_App::checkAppDependencies($this->config, $l, $info);
132
-		\OC_App::registerAutoloading($appId, $basedir);
133
-
134
-		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
136
-			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
-			} else {
139
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
-			}
141
-		} else {
142
-			$ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
-			$ms->migrate();
144
-		}
145
-
146
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-		if(isset($info['settings']) && is_array($info['settings'])) {
148
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
149
-		}
150
-
151
-		//run appinfo/install.php
152
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
153
-			self::includeAppScript($basedir . '/appinfo/install.php');
154
-		}
155
-
156
-		$appData = OC_App::getAppInfo($appId);
157
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
158
-
159
-		//set the installed version
160
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
161
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162
-
163
-		//set remote/public handlers
164
-		foreach($info['remote'] as $name=>$path) {
165
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166
-		}
167
-		foreach($info['public'] as $name=>$path) {
168
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169
-		}
170
-
171
-		OC_App::setAppTypes($info['id']);
172
-
173
-		return $info['id'];
174
-	}
175
-
176
-	/**
177
-	 * @brief checks whether or not an app is installed
178
-	 * @param string $app app
179
-	 * @returns bool
180
-	 *
181
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
182
-	 */
183
-	public static function isInstalled( $app ) {
184
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185
-	}
186
-
187
-	/**
188
-	 * Updates the specified app from the appstore
189
-	 *
190
-	 * @param string $appId
191
-	 * @return bool
192
-	 */
193
-	public function updateAppstoreApp($appId) {
194
-		if($this->isUpdateAvailable($appId)) {
195
-			try {
196
-				$this->downloadApp($appId);
197
-			} catch (\Exception $e) {
198
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
199
-				return false;
200
-			}
201
-			return OC_App::updateApp($appId);
202
-		}
203
-
204
-		return false;
205
-	}
206
-
207
-	/**
208
-	 * Downloads an app and puts it into the app directory
209
-	 *
210
-	 * @param string $appId
211
-	 *
212
-	 * @throws \Exception If the installation was not successful
213
-	 */
214
-	public function downloadApp($appId) {
215
-		$appId = strtolower($appId);
216
-
217
-		$apps = $this->appFetcher->get();
218
-		foreach($apps as $app) {
219
-			if($app['id'] === $appId) {
220
-				// Load the certificate
221
-				$certificate = new X509();
222
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
223
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
224
-
225
-				// Verify if the certificate has been revoked
226
-				$crl = new X509();
227
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
-				if($crl->validateSignature() !== true) {
230
-					throw new \Exception('Could not validate CRL signature');
231
-				}
232
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
233
-				$revoked = $crl->getRevoked($csn);
234
-				if ($revoked !== false) {
235
-					throw new \Exception(
236
-						sprintf(
237
-							'Certificate "%s" has been revoked',
238
-							$csn
239
-						)
240
-					);
241
-				}
242
-
243
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
-				if($certificate->validateSignature() !== true) {
245
-					throw new \Exception(
246
-						sprintf(
247
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
248
-							$appId
249
-						)
250
-					);
251
-				}
252
-
253
-				// Verify if the certificate is issued for the requested app id
254
-				$certInfo = openssl_x509_parse($app['certificate']);
255
-				if(!isset($certInfo['subject']['CN'])) {
256
-					throw new \Exception(
257
-						sprintf(
258
-							'App with id %s has a cert with no CN',
259
-							$appId
260
-						)
261
-					);
262
-				}
263
-				if($certInfo['subject']['CN'] !== $appId) {
264
-					throw new \Exception(
265
-						sprintf(
266
-							'App with id %s has a cert issued to %s',
267
-							$appId,
268
-							$certInfo['subject']['CN']
269
-						)
270
-					);
271
-				}
272
-
273
-				// Download the release
274
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
275
-				$client = $this->clientService->newClient();
276
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
277
-
278
-				// Check if the signature actually matches the downloaded content
279
-				$certificate = openssl_get_publickey($app['certificate']);
280
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281
-				openssl_free_key($certificate);
282
-
283
-				if($verified === true) {
284
-					// Seems to match, let's proceed
285
-					$extractDir = $this->tempManager->getTemporaryFolder();
286
-					$archive = new TAR($tempFile);
287
-
288
-					if($archive) {
289
-						if (!$archive->extract($extractDir)) {
290
-							throw new \Exception(
291
-								sprintf(
292
-									'Could not extract app %s',
293
-									$appId
294
-								)
295
-							);
296
-						}
297
-						$allFiles = scandir($extractDir);
298
-						$folders = array_diff($allFiles, ['.', '..']);
299
-						$folders = array_values($folders);
300
-
301
-						if(count($folders) > 1) {
302
-							throw new \Exception(
303
-								sprintf(
304
-									'Extracted app %s has more than 1 folder',
305
-									$appId
306
-								)
307
-							);
308
-						}
309
-
310
-						// Check if appinfo/info.xml has the same app ID as well
311
-						$loadEntities = libxml_disable_entity_loader(false);
312
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
313
-						libxml_disable_entity_loader($loadEntities);
314
-						if((string)$xml->id !== $appId) {
315
-							throw new \Exception(
316
-								sprintf(
317
-									'App for id %s has a wrong app ID in info.xml: %s',
318
-									$appId,
319
-									(string)$xml->id
320
-								)
321
-							);
322
-						}
323
-
324
-						// Check if the version is lower than before
325
-						$currentVersion = OC_App::getAppVersion($appId);
326
-						$newVersion = (string)$xml->version;
327
-						if(version_compare($currentVersion, $newVersion) === 1) {
328
-							throw new \Exception(
329
-								sprintf(
330
-									'App for id %s has version %s and tried to update to lower version %s',
331
-									$appId,
332
-									$currentVersion,
333
-									$newVersion
334
-								)
335
-							);
336
-						}
337
-
338
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
339
-						// Remove old app with the ID if existent
340
-						OC_Helper::rmdirr($baseDir);
341
-						// Move to app folder
342
-						if(@mkdir($baseDir)) {
343
-							$extractDir .= '/' . $folders[0];
344
-							OC_Helper::copyr($extractDir, $baseDir);
345
-						}
346
-						OC_Helper::copyr($extractDir, $baseDir);
347
-						OC_Helper::rmdirr($extractDir);
348
-						return;
349
-					} else {
350
-						throw new \Exception(
351
-							sprintf(
352
-								'Could not extract app with ID %s to %s',
353
-								$appId,
354
-								$extractDir
355
-							)
356
-						);
357
-					}
358
-				} else {
359
-					// Signature does not match
360
-					throw new \Exception(
361
-						sprintf(
362
-							'App with id %s has invalid signature',
363
-							$appId
364
-						)
365
-					);
366
-				}
367
-			}
368
-		}
369
-
370
-		throw new \Exception(
371
-			sprintf(
372
-				'Could not download app %s',
373
-				$appId
374
-			)
375
-		);
376
-	}
377
-
378
-	/**
379
-	 * Check if an update for the app is available
380
-	 *
381
-	 * @param string $appId
382
-	 * @return string|false false or the version number of the update
383
-	 */
384
-	public function isUpdateAvailable($appId) {
385
-		if ($this->isInstanceReadyForUpdates === null) {
386
-			$installPath = OC_App::getInstallPath();
387
-			if ($installPath === false || $installPath === null) {
388
-				$this->isInstanceReadyForUpdates = false;
389
-			} else {
390
-				$this->isInstanceReadyForUpdates = true;
391
-			}
392
-		}
393
-
394
-		if ($this->isInstanceReadyForUpdates === false) {
395
-			return false;
396
-		}
397
-
398
-		if ($this->isInstalledFromGit($appId) === true) {
399
-			return false;
400
-		}
401
-
402
-		if ($this->apps === null) {
403
-			$this->apps = $this->appFetcher->get();
404
-		}
405
-
406
-		foreach($this->apps as $app) {
407
-			if($app['id'] === $appId) {
408
-				$currentVersion = OC_App::getAppVersion($appId);
409
-				$newestVersion = $app['releases'][0]['version'];
410
-				if (version_compare($newestVersion, $currentVersion, '>')) {
411
-					return $newestVersion;
412
-				} else {
413
-					return false;
414
-				}
415
-			}
416
-		}
417
-
418
-		return false;
419
-	}
420
-
421
-	/**
422
-	 * Check if app has been installed from git
423
-	 * @param string $name name of the application to remove
424
-	 * @return boolean
425
-	 *
426
-	 * The function will check if the path contains a .git folder
427
-	 */
428
-	private function isInstalledFromGit($appId) {
429
-		$app = \OC_App::findAppInDirectories($appId);
430
-		if($app === false) {
431
-			return false;
432
-		}
433
-		$basedir = $app['path'].'/'.$appId;
434
-		return file_exists($basedir.'/.git/');
435
-	}
436
-
437
-	/**
438
-	 * Check if app is already downloaded
439
-	 * @param string $name name of the application to remove
440
-	 * @return boolean
441
-	 *
442
-	 * The function will check if the app is already downloaded in the apps repository
443
-	 */
444
-	public function isDownloaded($name) {
445
-		foreach(\OC::$APPSROOTS as $dir) {
446
-			$dirToTest  = $dir['path'];
447
-			$dirToTest .= '/';
448
-			$dirToTest .= $name;
449
-			$dirToTest .= '/';
450
-
451
-			if (is_dir($dirToTest)) {
452
-				return true;
453
-			}
454
-		}
455
-
456
-		return false;
457
-	}
458
-
459
-	/**
460
-	 * Removes an app
461
-	 * @param string $appId ID of the application to remove
462
-	 * @return boolean
463
-	 *
464
-	 *
465
-	 * This function works as follows
466
-	 *   -# call uninstall repair steps
467
-	 *   -# removing the files
468
-	 *
469
-	 * The function will not delete preferences, tables and the configuration,
470
-	 * this has to be done by the function oc_app_uninstall().
471
-	 */
472
-	public function removeApp($appId) {
473
-		if($this->isDownloaded( $appId )) {
474
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
475
-			OC_Helper::rmdirr($appDir);
476
-			return true;
477
-		}else{
478
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
479
-
480
-			return false;
481
-		}
482
-
483
-	}
484
-
485
-	/**
486
-	 * Installs the app within the bundle and marks the bundle as installed
487
-	 *
488
-	 * @param Bundle $bundle
489
-	 * @throws \Exception If app could not get installed
490
-	 */
491
-	public function installAppBundle(Bundle $bundle) {
492
-		$appIds = $bundle->getAppIdentifiers();
493
-		foreach($appIds as $appId) {
494
-			if(!$this->isDownloaded($appId)) {
495
-				$this->downloadApp($appId);
496
-			}
497
-			$this->installApp($appId);
498
-			$app = new OC_App();
499
-			$app->enable($appId);
500
-		}
501
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
502
-		$bundles[] = $bundle->getIdentifier();
503
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
504
-	}
505
-
506
-	/**
507
-	 * Installs shipped apps
508
-	 *
509
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
510
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
511
-	 *                         working ownCloud at the end instead of an aborted update.
512
-	 * @return array Array of error messages (appid => Exception)
513
-	 */
514
-	public static function installShippedApps($softErrors = false) {
515
-		$errors = [];
516
-		foreach(\OC::$APPSROOTS as $app_dir) {
517
-			if($dir = opendir( $app_dir['path'] )) {
518
-				while( false !== ( $filename = readdir( $dir ))) {
519
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
520
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
521
-							if(!Installer::isInstalled($filename)) {
522
-								$info=OC_App::getAppInfo($filename);
523
-								$enabled = isset($info['default_enable']);
524
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
525
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
526
-									if ($softErrors) {
527
-										try {
528
-											Installer::installShippedApp($filename);
529
-										} catch (HintException $e) {
530
-											if ($e->getPrevious() instanceof TableExistsException) {
531
-												$errors[$filename] = $e;
532
-												continue;
533
-											}
534
-											throw $e;
535
-										}
536
-									} else {
537
-										Installer::installShippedApp($filename);
538
-									}
539
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
540
-								}
541
-							}
542
-						}
543
-					}
544
-				}
545
-				closedir( $dir );
546
-			}
547
-		}
548
-
549
-		return $errors;
550
-	}
551
-
552
-	/**
553
-	 * install an app already placed in the app folder
554
-	 * @param string $app id of the app to install
555
-	 * @return integer
556
-	 */
557
-	public static function installShippedApp($app) {
558
-		//install the database
559
-		$appPath = OC_App::getAppPath($app);
560
-		\OC_App::registerAutoloading($app, $appPath);
561
-
562
-		if(is_file("$appPath/appinfo/database.xml")) {
563
-			try {
564
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
565
-			} catch (TableExistsException $e) {
566
-				throw new HintException(
567
-					'Failed to enable app ' . $app,
568
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
569
-					0, $e
570
-				);
571
-			}
572
-		} else {
573
-			$ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
574
-			$ms->migrate();
575
-		}
576
-
577
-		//run appinfo/install.php
578
-		self::includeAppScript("$appPath/appinfo/install.php");
579
-
580
-		$info = OC_App::getAppInfo($app);
581
-		if (is_null($info)) {
582
-			return false;
583
-		}
584
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
585
-
586
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
587
-
588
-		$config = \OC::$server->getConfig();
589
-
590
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
591
-		if (array_key_exists('ocsid', $info)) {
592
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
593
-		}
594
-
595
-		//set remote/public handlers
596
-		foreach($info['remote'] as $name=>$path) {
597
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
598
-		}
599
-		foreach($info['public'] as $name=>$path) {
600
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
601
-		}
602
-
603
-		OC_App::setAppTypes($info['id']);
604
-
605
-		if(isset($info['settings']) && is_array($info['settings'])) {
606
-			// requires that autoloading was registered for the app,
607
-			// as happens before running the install.php some lines above
608
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
609
-		}
610
-
611
-		return $info['id'];
612
-	}
613
-
614
-	/**
615
-	 * @param string $script
616
-	 */
617
-	private static function includeAppScript($script) {
618
-		if ( file_exists($script) ){
619
-			include $script;
620
-		}
621
-	}
60
+    /** @var AppFetcher */
61
+    private $appFetcher;
62
+    /** @var IClientService */
63
+    private $clientService;
64
+    /** @var ITempManager */
65
+    private $tempManager;
66
+    /** @var ILogger */
67
+    private $logger;
68
+    /** @var IConfig */
69
+    private $config;
70
+    /** @var array - for caching the result of app fetcher */
71
+    private $apps = null;
72
+    /** @var bool|null - for caching the result of the ready status */
73
+    private $isInstanceReadyForUpdates = null;
74
+
75
+    /**
76
+     * @param AppFetcher $appFetcher
77
+     * @param IClientService $clientService
78
+     * @param ITempManager $tempManager
79
+     * @param ILogger $logger
80
+     * @param IConfig $config
81
+     */
82
+    public function __construct(AppFetcher $appFetcher,
83
+                                IClientService $clientService,
84
+                                ITempManager $tempManager,
85
+                                ILogger $logger,
86
+                                IConfig $config) {
87
+        $this->appFetcher = $appFetcher;
88
+        $this->clientService = $clientService;
89
+        $this->tempManager = $tempManager;
90
+        $this->logger = $logger;
91
+        $this->config = $config;
92
+    }
93
+
94
+    /**
95
+     * Installs an app that is located in one of the app folders already
96
+     *
97
+     * @param string $appId App to install
98
+     * @throws \Exception
99
+     * @return string app ID
100
+     */
101
+    public function installApp($appId) {
102
+        $app = \OC_App::findAppInDirectories($appId);
103
+        if($app === false) {
104
+            throw new \Exception('App not found in any app directory');
105
+        }
106
+
107
+        $basedir = $app['path'].'/'.$appId;
108
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
+
110
+        $l = \OC::$server->getL10N('core');
111
+
112
+        if(!is_array($info)) {
113
+            throw new \Exception(
114
+                $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
+                    [$info['name']]
116
+                )
117
+            );
118
+        }
119
+
120
+        $version = \OCP\Util::getVersion();
121
+        if (!\OC_App::isAppCompatible($version, $info)) {
122
+            throw new \Exception(
123
+                // TODO $l
124
+                $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
+                    [$info['name']]
126
+                )
127
+            );
128
+        }
129
+
130
+        // check for required dependencies
131
+        \OC_App::checkAppDependencies($this->config, $l, $info);
132
+        \OC_App::registerAutoloading($appId, $basedir);
133
+
134
+        //install the database
135
+        if(is_file($basedir.'/appinfo/database.xml')) {
136
+            if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
+            } else {
139
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
+            }
141
+        } else {
142
+            $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
+            $ms->migrate();
144
+        }
145
+
146
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
147
+        if(isset($info['settings']) && is_array($info['settings'])) {
148
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
149
+        }
150
+
151
+        //run appinfo/install.php
152
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
153
+            self::includeAppScript($basedir . '/appinfo/install.php');
154
+        }
155
+
156
+        $appData = OC_App::getAppInfo($appId);
157
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
158
+
159
+        //set the installed version
160
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
161
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162
+
163
+        //set remote/public handlers
164
+        foreach($info['remote'] as $name=>$path) {
165
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166
+        }
167
+        foreach($info['public'] as $name=>$path) {
168
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169
+        }
170
+
171
+        OC_App::setAppTypes($info['id']);
172
+
173
+        return $info['id'];
174
+    }
175
+
176
+    /**
177
+     * @brief checks whether or not an app is installed
178
+     * @param string $app app
179
+     * @returns bool
180
+     *
181
+     * Checks whether or not an app is installed, i.e. registered in apps table.
182
+     */
183
+    public static function isInstalled( $app ) {
184
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185
+    }
186
+
187
+    /**
188
+     * Updates the specified app from the appstore
189
+     *
190
+     * @param string $appId
191
+     * @return bool
192
+     */
193
+    public function updateAppstoreApp($appId) {
194
+        if($this->isUpdateAvailable($appId)) {
195
+            try {
196
+                $this->downloadApp($appId);
197
+            } catch (\Exception $e) {
198
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
199
+                return false;
200
+            }
201
+            return OC_App::updateApp($appId);
202
+        }
203
+
204
+        return false;
205
+    }
206
+
207
+    /**
208
+     * Downloads an app and puts it into the app directory
209
+     *
210
+     * @param string $appId
211
+     *
212
+     * @throws \Exception If the installation was not successful
213
+     */
214
+    public function downloadApp($appId) {
215
+        $appId = strtolower($appId);
216
+
217
+        $apps = $this->appFetcher->get();
218
+        foreach($apps as $app) {
219
+            if($app['id'] === $appId) {
220
+                // Load the certificate
221
+                $certificate = new X509();
222
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
223
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
224
+
225
+                // Verify if the certificate has been revoked
226
+                $crl = new X509();
227
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
+                if($crl->validateSignature() !== true) {
230
+                    throw new \Exception('Could not validate CRL signature');
231
+                }
232
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
233
+                $revoked = $crl->getRevoked($csn);
234
+                if ($revoked !== false) {
235
+                    throw new \Exception(
236
+                        sprintf(
237
+                            'Certificate "%s" has been revoked',
238
+                            $csn
239
+                        )
240
+                    );
241
+                }
242
+
243
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
+                if($certificate->validateSignature() !== true) {
245
+                    throw new \Exception(
246
+                        sprintf(
247
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
248
+                            $appId
249
+                        )
250
+                    );
251
+                }
252
+
253
+                // Verify if the certificate is issued for the requested app id
254
+                $certInfo = openssl_x509_parse($app['certificate']);
255
+                if(!isset($certInfo['subject']['CN'])) {
256
+                    throw new \Exception(
257
+                        sprintf(
258
+                            'App with id %s has a cert with no CN',
259
+                            $appId
260
+                        )
261
+                    );
262
+                }
263
+                if($certInfo['subject']['CN'] !== $appId) {
264
+                    throw new \Exception(
265
+                        sprintf(
266
+                            'App with id %s has a cert issued to %s',
267
+                            $appId,
268
+                            $certInfo['subject']['CN']
269
+                        )
270
+                    );
271
+                }
272
+
273
+                // Download the release
274
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
275
+                $client = $this->clientService->newClient();
276
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
277
+
278
+                // Check if the signature actually matches the downloaded content
279
+                $certificate = openssl_get_publickey($app['certificate']);
280
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281
+                openssl_free_key($certificate);
282
+
283
+                if($verified === true) {
284
+                    // Seems to match, let's proceed
285
+                    $extractDir = $this->tempManager->getTemporaryFolder();
286
+                    $archive = new TAR($tempFile);
287
+
288
+                    if($archive) {
289
+                        if (!$archive->extract($extractDir)) {
290
+                            throw new \Exception(
291
+                                sprintf(
292
+                                    'Could not extract app %s',
293
+                                    $appId
294
+                                )
295
+                            );
296
+                        }
297
+                        $allFiles = scandir($extractDir);
298
+                        $folders = array_diff($allFiles, ['.', '..']);
299
+                        $folders = array_values($folders);
300
+
301
+                        if(count($folders) > 1) {
302
+                            throw new \Exception(
303
+                                sprintf(
304
+                                    'Extracted app %s has more than 1 folder',
305
+                                    $appId
306
+                                )
307
+                            );
308
+                        }
309
+
310
+                        // Check if appinfo/info.xml has the same app ID as well
311
+                        $loadEntities = libxml_disable_entity_loader(false);
312
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
313
+                        libxml_disable_entity_loader($loadEntities);
314
+                        if((string)$xml->id !== $appId) {
315
+                            throw new \Exception(
316
+                                sprintf(
317
+                                    'App for id %s has a wrong app ID in info.xml: %s',
318
+                                    $appId,
319
+                                    (string)$xml->id
320
+                                )
321
+                            );
322
+                        }
323
+
324
+                        // Check if the version is lower than before
325
+                        $currentVersion = OC_App::getAppVersion($appId);
326
+                        $newVersion = (string)$xml->version;
327
+                        if(version_compare($currentVersion, $newVersion) === 1) {
328
+                            throw new \Exception(
329
+                                sprintf(
330
+                                    'App for id %s has version %s and tried to update to lower version %s',
331
+                                    $appId,
332
+                                    $currentVersion,
333
+                                    $newVersion
334
+                                )
335
+                            );
336
+                        }
337
+
338
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
339
+                        // Remove old app with the ID if existent
340
+                        OC_Helper::rmdirr($baseDir);
341
+                        // Move to app folder
342
+                        if(@mkdir($baseDir)) {
343
+                            $extractDir .= '/' . $folders[0];
344
+                            OC_Helper::copyr($extractDir, $baseDir);
345
+                        }
346
+                        OC_Helper::copyr($extractDir, $baseDir);
347
+                        OC_Helper::rmdirr($extractDir);
348
+                        return;
349
+                    } else {
350
+                        throw new \Exception(
351
+                            sprintf(
352
+                                'Could not extract app with ID %s to %s',
353
+                                $appId,
354
+                                $extractDir
355
+                            )
356
+                        );
357
+                    }
358
+                } else {
359
+                    // Signature does not match
360
+                    throw new \Exception(
361
+                        sprintf(
362
+                            'App with id %s has invalid signature',
363
+                            $appId
364
+                        )
365
+                    );
366
+                }
367
+            }
368
+        }
369
+
370
+        throw new \Exception(
371
+            sprintf(
372
+                'Could not download app %s',
373
+                $appId
374
+            )
375
+        );
376
+    }
377
+
378
+    /**
379
+     * Check if an update for the app is available
380
+     *
381
+     * @param string $appId
382
+     * @return string|false false or the version number of the update
383
+     */
384
+    public function isUpdateAvailable($appId) {
385
+        if ($this->isInstanceReadyForUpdates === null) {
386
+            $installPath = OC_App::getInstallPath();
387
+            if ($installPath === false || $installPath === null) {
388
+                $this->isInstanceReadyForUpdates = false;
389
+            } else {
390
+                $this->isInstanceReadyForUpdates = true;
391
+            }
392
+        }
393
+
394
+        if ($this->isInstanceReadyForUpdates === false) {
395
+            return false;
396
+        }
397
+
398
+        if ($this->isInstalledFromGit($appId) === true) {
399
+            return false;
400
+        }
401
+
402
+        if ($this->apps === null) {
403
+            $this->apps = $this->appFetcher->get();
404
+        }
405
+
406
+        foreach($this->apps as $app) {
407
+            if($app['id'] === $appId) {
408
+                $currentVersion = OC_App::getAppVersion($appId);
409
+                $newestVersion = $app['releases'][0]['version'];
410
+                if (version_compare($newestVersion, $currentVersion, '>')) {
411
+                    return $newestVersion;
412
+                } else {
413
+                    return false;
414
+                }
415
+            }
416
+        }
417
+
418
+        return false;
419
+    }
420
+
421
+    /**
422
+     * Check if app has been installed from git
423
+     * @param string $name name of the application to remove
424
+     * @return boolean
425
+     *
426
+     * The function will check if the path contains a .git folder
427
+     */
428
+    private function isInstalledFromGit($appId) {
429
+        $app = \OC_App::findAppInDirectories($appId);
430
+        if($app === false) {
431
+            return false;
432
+        }
433
+        $basedir = $app['path'].'/'.$appId;
434
+        return file_exists($basedir.'/.git/');
435
+    }
436
+
437
+    /**
438
+     * Check if app is already downloaded
439
+     * @param string $name name of the application to remove
440
+     * @return boolean
441
+     *
442
+     * The function will check if the app is already downloaded in the apps repository
443
+     */
444
+    public function isDownloaded($name) {
445
+        foreach(\OC::$APPSROOTS as $dir) {
446
+            $dirToTest  = $dir['path'];
447
+            $dirToTest .= '/';
448
+            $dirToTest .= $name;
449
+            $dirToTest .= '/';
450
+
451
+            if (is_dir($dirToTest)) {
452
+                return true;
453
+            }
454
+        }
455
+
456
+        return false;
457
+    }
458
+
459
+    /**
460
+     * Removes an app
461
+     * @param string $appId ID of the application to remove
462
+     * @return boolean
463
+     *
464
+     *
465
+     * This function works as follows
466
+     *   -# call uninstall repair steps
467
+     *   -# removing the files
468
+     *
469
+     * The function will not delete preferences, tables and the configuration,
470
+     * this has to be done by the function oc_app_uninstall().
471
+     */
472
+    public function removeApp($appId) {
473
+        if($this->isDownloaded( $appId )) {
474
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
475
+            OC_Helper::rmdirr($appDir);
476
+            return true;
477
+        }else{
478
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
479
+
480
+            return false;
481
+        }
482
+
483
+    }
484
+
485
+    /**
486
+     * Installs the app within the bundle and marks the bundle as installed
487
+     *
488
+     * @param Bundle $bundle
489
+     * @throws \Exception If app could not get installed
490
+     */
491
+    public function installAppBundle(Bundle $bundle) {
492
+        $appIds = $bundle->getAppIdentifiers();
493
+        foreach($appIds as $appId) {
494
+            if(!$this->isDownloaded($appId)) {
495
+                $this->downloadApp($appId);
496
+            }
497
+            $this->installApp($appId);
498
+            $app = new OC_App();
499
+            $app->enable($appId);
500
+        }
501
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
502
+        $bundles[] = $bundle->getIdentifier();
503
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
504
+    }
505
+
506
+    /**
507
+     * Installs shipped apps
508
+     *
509
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
510
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
511
+     *                         working ownCloud at the end instead of an aborted update.
512
+     * @return array Array of error messages (appid => Exception)
513
+     */
514
+    public static function installShippedApps($softErrors = false) {
515
+        $errors = [];
516
+        foreach(\OC::$APPSROOTS as $app_dir) {
517
+            if($dir = opendir( $app_dir['path'] )) {
518
+                while( false !== ( $filename = readdir( $dir ))) {
519
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
520
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
521
+                            if(!Installer::isInstalled($filename)) {
522
+                                $info=OC_App::getAppInfo($filename);
523
+                                $enabled = isset($info['default_enable']);
524
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
525
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
526
+                                    if ($softErrors) {
527
+                                        try {
528
+                                            Installer::installShippedApp($filename);
529
+                                        } catch (HintException $e) {
530
+                                            if ($e->getPrevious() instanceof TableExistsException) {
531
+                                                $errors[$filename] = $e;
532
+                                                continue;
533
+                                            }
534
+                                            throw $e;
535
+                                        }
536
+                                    } else {
537
+                                        Installer::installShippedApp($filename);
538
+                                    }
539
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
540
+                                }
541
+                            }
542
+                        }
543
+                    }
544
+                }
545
+                closedir( $dir );
546
+            }
547
+        }
548
+
549
+        return $errors;
550
+    }
551
+
552
+    /**
553
+     * install an app already placed in the app folder
554
+     * @param string $app id of the app to install
555
+     * @return integer
556
+     */
557
+    public static function installShippedApp($app) {
558
+        //install the database
559
+        $appPath = OC_App::getAppPath($app);
560
+        \OC_App::registerAutoloading($app, $appPath);
561
+
562
+        if(is_file("$appPath/appinfo/database.xml")) {
563
+            try {
564
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
565
+            } catch (TableExistsException $e) {
566
+                throw new HintException(
567
+                    'Failed to enable app ' . $app,
568
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
569
+                    0, $e
570
+                );
571
+            }
572
+        } else {
573
+            $ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
574
+            $ms->migrate();
575
+        }
576
+
577
+        //run appinfo/install.php
578
+        self::includeAppScript("$appPath/appinfo/install.php");
579
+
580
+        $info = OC_App::getAppInfo($app);
581
+        if (is_null($info)) {
582
+            return false;
583
+        }
584
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
585
+
586
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
587
+
588
+        $config = \OC::$server->getConfig();
589
+
590
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
591
+        if (array_key_exists('ocsid', $info)) {
592
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
593
+        }
594
+
595
+        //set remote/public handlers
596
+        foreach($info['remote'] as $name=>$path) {
597
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
598
+        }
599
+        foreach($info['public'] as $name=>$path) {
600
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
601
+        }
602
+
603
+        OC_App::setAppTypes($info['id']);
604
+
605
+        if(isset($info['settings']) && is_array($info['settings'])) {
606
+            // requires that autoloading was registered for the app,
607
+            // as happens before running the install.php some lines above
608
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
609
+        }
610
+
611
+        return $info['id'];
612
+    }
613
+
614
+    /**
615
+     * @param string $script
616
+     */
617
+    private static function includeAppScript($script) {
618
+        if ( file_exists($script) ){
619
+            include $script;
620
+        }
621
+    }
622 622
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function installApp($appId) {
102 102
 		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
103
+		if ($app === false) {
104 104
 			throw new \Exception('App not found in any app directory');
105 105
 		}
106 106
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 
110 110
 		$l = \OC::$server->getL10N('core');
111 111
 
112
-		if(!is_array($info)) {
112
+		if (!is_array($info)) {
113 113
 			throw new \Exception(
114 114
 				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115 115
 					[$info['name']]
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		\OC_App::registerAutoloading($appId, $basedir);
133 133
 
134 134
 		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
135
+		if (is_file($basedir.'/appinfo/database.xml')) {
136 136
 			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137 137
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138 138
 			} else {
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
 		}
145 145
 
146 146
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-		if(isset($info['settings']) && is_array($info['settings'])) {
147
+		if (isset($info['settings']) && is_array($info['settings'])) {
148 148
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
149 149
 		}
150 150
 
151 151
 		//run appinfo/install.php
152
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
153
-			self::includeAppScript($basedir . '/appinfo/install.php');
152
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
153
+			self::includeAppScript($basedir.'/appinfo/install.php');
154 154
 		}
155 155
 
156 156
 		$appData = OC_App::getAppInfo($appId);
@@ -161,10 +161,10 @@  discard block
 block discarded – undo
161 161
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
162 162
 
163 163
 		//set remote/public handlers
164
-		foreach($info['remote'] as $name=>$path) {
164
+		foreach ($info['remote'] as $name=>$path) {
165 165
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
166 166
 		}
167
-		foreach($info['public'] as $name=>$path) {
167
+		foreach ($info['public'] as $name=>$path) {
168 168
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
169 169
 		}
170 170
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 	 *
181 181
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
182 182
 	 */
183
-	public static function isInstalled( $app ) {
183
+	public static function isInstalled($app) {
184 184
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
185 185
 	}
186 186
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 	 * @return bool
192 192
 	 */
193 193
 	public function updateAppstoreApp($appId) {
194
-		if($this->isUpdateAvailable($appId)) {
194
+		if ($this->isUpdateAvailable($appId)) {
195 195
 			try {
196 196
 				$this->downloadApp($appId);
197 197
 			} catch (\Exception $e) {
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
 		$appId = strtolower($appId);
216 216
 
217 217
 		$apps = $this->appFetcher->get();
218
-		foreach($apps as $app) {
219
-			if($app['id'] === $appId) {
218
+		foreach ($apps as $app) {
219
+			if ($app['id'] === $appId) {
220 220
 				// Load the certificate
221 221
 				$certificate = new X509();
222
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
222
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
223 223
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
224 224
 
225 225
 				// Verify if the certificate has been revoked
226 226
 				$crl = new X509();
227
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
-				if($crl->validateSignature() !== true) {
227
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
228
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
229
+				if ($crl->validateSignature() !== true) {
230 230
 					throw new \Exception('Could not validate CRL signature');
231 231
 				}
232 232
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 				}
242 242
 
243 243
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
-				if($certificate->validateSignature() !== true) {
244
+				if ($certificate->validateSignature() !== true) {
245 245
 					throw new \Exception(
246 246
 						sprintf(
247 247
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 
253 253
 				// Verify if the certificate is issued for the requested app id
254 254
 				$certInfo = openssl_x509_parse($app['certificate']);
255
-				if(!isset($certInfo['subject']['CN'])) {
255
+				if (!isset($certInfo['subject']['CN'])) {
256 256
 					throw new \Exception(
257 257
 						sprintf(
258 258
 							'App with id %s has a cert with no CN',
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 						)
261 261
 					);
262 262
 				}
263
-				if($certInfo['subject']['CN'] !== $appId) {
263
+				if ($certInfo['subject']['CN'] !== $appId) {
264 264
 					throw new \Exception(
265 265
 						sprintf(
266 266
 							'App with id %s has a cert issued to %s',
@@ -277,15 +277,15 @@  discard block
 block discarded – undo
277 277
 
278 278
 				// Check if the signature actually matches the downloaded content
279 279
 				$certificate = openssl_get_publickey($app['certificate']);
280
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
280
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281 281
 				openssl_free_key($certificate);
282 282
 
283
-				if($verified === true) {
283
+				if ($verified === true) {
284 284
 					// Seems to match, let's proceed
285 285
 					$extractDir = $this->tempManager->getTemporaryFolder();
286 286
 					$archive = new TAR($tempFile);
287 287
 
288
-					if($archive) {
288
+					if ($archive) {
289 289
 						if (!$archive->extract($extractDir)) {
290 290
 							throw new \Exception(
291 291
 								sprintf(
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 						$folders = array_diff($allFiles, ['.', '..']);
299 299
 						$folders = array_values($folders);
300 300
 
301
-						if(count($folders) > 1) {
301
+						if (count($folders) > 1) {
302 302
 							throw new \Exception(
303 303
 								sprintf(
304 304
 									'Extracted app %s has more than 1 folder',
@@ -309,22 +309,22 @@  discard block
 block discarded – undo
309 309
 
310 310
 						// Check if appinfo/info.xml has the same app ID as well
311 311
 						$loadEntities = libxml_disable_entity_loader(false);
312
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
312
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
313 313
 						libxml_disable_entity_loader($loadEntities);
314
-						if((string)$xml->id !== $appId) {
314
+						if ((string) $xml->id !== $appId) {
315 315
 							throw new \Exception(
316 316
 								sprintf(
317 317
 									'App for id %s has a wrong app ID in info.xml: %s',
318 318
 									$appId,
319
-									(string)$xml->id
319
+									(string) $xml->id
320 320
 								)
321 321
 							);
322 322
 						}
323 323
 
324 324
 						// Check if the version is lower than before
325 325
 						$currentVersion = OC_App::getAppVersion($appId);
326
-						$newVersion = (string)$xml->version;
327
-						if(version_compare($currentVersion, $newVersion) === 1) {
326
+						$newVersion = (string) $xml->version;
327
+						if (version_compare($currentVersion, $newVersion) === 1) {
328 328
 							throw new \Exception(
329 329
 								sprintf(
330 330
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -335,12 +335,12 @@  discard block
 block discarded – undo
335 335
 							);
336 336
 						}
337 337
 
338
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
338
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
339 339
 						// Remove old app with the ID if existent
340 340
 						OC_Helper::rmdirr($baseDir);
341 341
 						// Move to app folder
342
-						if(@mkdir($baseDir)) {
343
-							$extractDir .= '/' . $folders[0];
342
+						if (@mkdir($baseDir)) {
343
+							$extractDir .= '/'.$folders[0];
344 344
 							OC_Helper::copyr($extractDir, $baseDir);
345 345
 						}
346 346
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -403,8 +403,8 @@  discard block
 block discarded – undo
403 403
 			$this->apps = $this->appFetcher->get();
404 404
 		}
405 405
 
406
-		foreach($this->apps as $app) {
407
-			if($app['id'] === $appId) {
406
+		foreach ($this->apps as $app) {
407
+			if ($app['id'] === $appId) {
408 408
 				$currentVersion = OC_App::getAppVersion($appId);
409 409
 				$newestVersion = $app['releases'][0]['version'];
410 410
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 	 */
428 428
 	private function isInstalledFromGit($appId) {
429 429
 		$app = \OC_App::findAppInDirectories($appId);
430
-		if($app === false) {
430
+		if ($app === false) {
431 431
 			return false;
432 432
 		}
433 433
 		$basedir = $app['path'].'/'.$appId;
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 	 * The function will check if the app is already downloaded in the apps repository
443 443
 	 */
444 444
 	public function isDownloaded($name) {
445
-		foreach(\OC::$APPSROOTS as $dir) {
445
+		foreach (\OC::$APPSROOTS as $dir) {
446 446
 			$dirToTest  = $dir['path'];
447 447
 			$dirToTest .= '/';
448 448
 			$dirToTest .= $name;
@@ -470,11 +470,11 @@  discard block
 block discarded – undo
470 470
 	 * this has to be done by the function oc_app_uninstall().
471 471
 	 */
472 472
 	public function removeApp($appId) {
473
-		if($this->isDownloaded( $appId )) {
474
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
473
+		if ($this->isDownloaded($appId)) {
474
+			$appDir = OC_App::getInstallPath().'/'.$appId;
475 475
 			OC_Helper::rmdirr($appDir);
476 476
 			return true;
477
-		}else{
477
+		} else {
478 478
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
479 479
 
480 480
 			return false;
@@ -490,8 +490,8 @@  discard block
 block discarded – undo
490 490
 	 */
491 491
 	public function installAppBundle(Bundle $bundle) {
492 492
 		$appIds = $bundle->getAppIdentifiers();
493
-		foreach($appIds as $appId) {
494
-			if(!$this->isDownloaded($appId)) {
493
+		foreach ($appIds as $appId) {
494
+			if (!$this->isDownloaded($appId)) {
495 495
 				$this->downloadApp($appId);
496 496
 			}
497 497
 			$this->installApp($appId);
@@ -513,13 +513,13 @@  discard block
 block discarded – undo
513 513
 	 */
514 514
 	public static function installShippedApps($softErrors = false) {
515 515
 		$errors = [];
516
-		foreach(\OC::$APPSROOTS as $app_dir) {
517
-			if($dir = opendir( $app_dir['path'] )) {
518
-				while( false !== ( $filename = readdir( $dir ))) {
519
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
520
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
521
-							if(!Installer::isInstalled($filename)) {
522
-								$info=OC_App::getAppInfo($filename);
516
+		foreach (\OC::$APPSROOTS as $app_dir) {
517
+			if ($dir = opendir($app_dir['path'])) {
518
+				while (false !== ($filename = readdir($dir))) {
519
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
520
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
521
+							if (!Installer::isInstalled($filename)) {
522
+								$info = OC_App::getAppInfo($filename);
523 523
 								$enabled = isset($info['default_enable']);
524 524
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
525 525
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 						}
543 543
 					}
544 544
 				}
545
-				closedir( $dir );
545
+				closedir($dir);
546 546
 			}
547 547
 		}
548 548
 
@@ -559,12 +559,12 @@  discard block
 block discarded – undo
559 559
 		$appPath = OC_App::getAppPath($app);
560 560
 		\OC_App::registerAutoloading($app, $appPath);
561 561
 
562
-		if(is_file("$appPath/appinfo/database.xml")) {
562
+		if (is_file("$appPath/appinfo/database.xml")) {
563 563
 			try {
564 564
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
565 565
 			} catch (TableExistsException $e) {
566 566
 				throw new HintException(
567
-					'Failed to enable app ' . $app,
567
+					'Failed to enable app '.$app,
568 568
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
569 569
 					0, $e
570 570
 				);
@@ -593,16 +593,16 @@  discard block
 block discarded – undo
593 593
 		}
594 594
 
595 595
 		//set remote/public handlers
596
-		foreach($info['remote'] as $name=>$path) {
596
+		foreach ($info['remote'] as $name=>$path) {
597 597
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
598 598
 		}
599
-		foreach($info['public'] as $name=>$path) {
599
+		foreach ($info['public'] as $name=>$path) {
600 600
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
601 601
 		}
602 602
 
603 603
 		OC_App::setAppTypes($info['id']);
604 604
 
605
-		if(isset($info['settings']) && is_array($info['settings'])) {
605
+		if (isset($info['settings']) && is_array($info['settings'])) {
606 606
 			// requires that autoloading was registered for the app,
607 607
 			// as happens before running the install.php some lines above
608 608
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -615,7 +615,7 @@  discard block
 block discarded – undo
615 615
 	 * @param string $script
616 616
 	 */
617 617
 	private static function includeAppScript($script) {
618
-		if ( file_exists($script) ){
618
+		if (file_exists($script)) {
619 619
 			include $script;
620 620
 		}
621 621
 	}
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1817 added lines, -1817 removed lines patch added patch discarded remove patch
@@ -147,1826 +147,1826 @@
 block discarded – undo
147 147
  * TODO: hookup all manager classes
148 148
  */
149 149
 class Server extends ServerContainer implements IServerContainer {
150
-	/** @var string */
151
-	private $webRoot;
152
-
153
-	/**
154
-	 * @param string $webRoot
155
-	 * @param \OC\Config $config
156
-	 */
157
-	public function __construct($webRoot, \OC\Config $config) {
158
-		parent::__construct();
159
-		$this->webRoot = $webRoot;
160
-
161
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
162
-			return $c;
163
-		});
164
-
165
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
166
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
167
-
168
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
169
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
170
-
171
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
172
-
173
-
174
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
175
-			return new PreviewManager(
176
-				$c->getConfig(),
177
-				$c->getRootFolder(),
178
-				$c->getAppDataDir('preview'),
179
-				$c->getEventDispatcher(),
180
-				$c->getSession()->get('user_id')
181
-			);
182
-		});
183
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
184
-
185
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
186
-			return new \OC\Preview\Watcher(
187
-				$c->getAppDataDir('preview')
188
-			);
189
-		});
190
-
191
-		$this->registerService('EncryptionManager', function (Server $c) {
192
-			$view = new View();
193
-			$util = new Encryption\Util(
194
-				$view,
195
-				$c->getUserManager(),
196
-				$c->getGroupManager(),
197
-				$c->getConfig()
198
-			);
199
-			return new Encryption\Manager(
200
-				$c->getConfig(),
201
-				$c->getLogger(),
202
-				$c->getL10N('core'),
203
-				new View(),
204
-				$util,
205
-				new ArrayCache()
206
-			);
207
-		});
208
-
209
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
210
-			$util = new Encryption\Util(
211
-				new View(),
212
-				$c->getUserManager(),
213
-				$c->getGroupManager(),
214
-				$c->getConfig()
215
-			);
216
-			return new Encryption\File(
217
-				$util,
218
-				$c->getRootFolder(),
219
-				$c->getShareManager()
220
-			);
221
-		});
222
-
223
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
224
-			$view = new View();
225
-			$util = new Encryption\Util(
226
-				$view,
227
-				$c->getUserManager(),
228
-				$c->getGroupManager(),
229
-				$c->getConfig()
230
-			);
231
-
232
-			return new Encryption\Keys\Storage($view, $util);
233
-		});
234
-		$this->registerService('TagMapper', function (Server $c) {
235
-			return new TagMapper($c->getDatabaseConnection());
236
-		});
237
-
238
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
239
-			$tagMapper = $c->query('TagMapper');
240
-			return new TagManager($tagMapper, $c->getUserSession());
241
-		});
242
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
243
-
244
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
245
-			$config = $c->getConfig();
246
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
247
-			/** @var \OC\SystemTag\ManagerFactory $factory */
248
-			$factory = new $factoryClass($this);
249
-			return $factory;
250
-		});
251
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
-			return $c->query('SystemTagManagerFactory')->getManager();
253
-		});
254
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255
-
256
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
258
-		});
259
-		$this->registerService('RootFolder', function (Server $c) {
260
-			$manager = \OC\Files\Filesystem::getMountManager(null);
261
-			$view = new View();
262
-			$root = new Root(
263
-				$manager,
264
-				$view,
265
-				null,
266
-				$c->getUserMountCache(),
267
-				$this->getLogger(),
268
-				$this->getUserManager()
269
-			);
270
-			$connector = new HookConnector($root, $view);
271
-			$connector->viewToNode();
272
-
273
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
274
-			$previewConnector->connectWatcher();
275
-
276
-			return $root;
277
-		});
278
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279
-
280
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
-			return new LazyRoot(function () use ($c) {
282
-				return $c->query('RootFolder');
283
-			});
284
-		});
285
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286
-
287
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
288
-			$config = $c->getConfig();
289
-			return new \OC\User\Manager($config);
290
-		});
291
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
292
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
293
-
294
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304
-			});
305
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307
-			});
308
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310
-			});
311
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
315
-			});
316
-			return $groupManager;
317
-		});
318
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319
-
320
-		$this->registerService(Store::class, function (Server $c) {
321
-			$session = $c->getSession();
322
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
324
-			} else {
325
-				$tokenProvider = null;
326
-			}
327
-			$logger = $c->getLogger();
328
-			return new Store($session, $logger, $tokenProvider);
329
-		});
330
-		$this->registerAlias(IStore::class, Store::class);
331
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
332
-			$dbConnection = $c->getDatabaseConnection();
333
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
334
-		});
335
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
336
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
337
-			$crypto = $c->getCrypto();
338
-			$config = $c->getConfig();
339
-			$logger = $c->getLogger();
340
-			$timeFactory = new TimeFactory();
341
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
342
-		});
343
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
344
-
345
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
-			$manager = $c->getUserManager();
347
-			$session = new \OC\Session\Memory('');
348
-			$timeFactory = new TimeFactory();
349
-			// Token providers might require a working database. This code
350
-			// might however be called when ownCloud is not yet setup.
351
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
352
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
353
-			} else {
354
-				$defaultTokenProvider = null;
355
-			}
356
-
357
-			$dispatcher = $c->getEventDispatcher();
358
-
359
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
360
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
361
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
362
-			});
363
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
364
-				/** @var $user \OC\User\User */
365
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
366
-			});
367
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
368
-				/** @var $user \OC\User\User */
369
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
370
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
371
-			});
372
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
373
-				/** @var $user \OC\User\User */
374
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
375
-			});
376
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
377
-				/** @var $user \OC\User\User */
378
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
379
-			});
380
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
381
-				/** @var $user \OC\User\User */
382
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
383
-			});
384
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
385
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
386
-			});
387
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
388
-				/** @var $user \OC\User\User */
389
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
390
-			});
391
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
392
-				/** @var $user \OC\User\User */
393
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
394
-			});
395
-			$userSession->listen('\OC\User', 'logout', function () {
396
-				\OC_Hook::emit('OC_User', 'logout', array());
397
-			});
398
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
399
-				/** @var $user \OC\User\User */
400
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
401
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
402
-			});
403
-			return $userSession;
404
-		});
405
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
406
-
407
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
408
-			return new \OC\Authentication\TwoFactorAuth\Manager(
409
-				$c->getAppManager(),
410
-				$c->getSession(),
411
-				$c->getConfig(),
412
-				$c->getActivityManager(),
413
-				$c->getLogger(),
414
-				$c->query(\OC\Authentication\Token\IProvider::class),
415
-				$c->query(ITimeFactory::class)
416
-			);
417
-		});
418
-
419
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
420
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
421
-
422
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
423
-			return new \OC\AllConfig(
424
-				$c->getSystemConfig()
425
-			);
426
-		});
427
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
428
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
429
-
430
-		$this->registerService('SystemConfig', function ($c) use ($config) {
431
-			return new \OC\SystemConfig($config);
432
-		});
433
-
434
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
435
-			return new \OC\AppConfig($c->getDatabaseConnection());
436
-		});
437
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
438
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
439
-
440
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
441
-			return new \OC\L10N\Factory(
442
-				$c->getConfig(),
443
-				$c->getRequest(),
444
-				$c->getUserSession(),
445
-				\OC::$SERVERROOT
446
-			);
447
-		});
448
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
449
-
450
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
451
-			$config = $c->getConfig();
452
-			$cacheFactory = $c->getMemCacheFactory();
453
-			$request = $c->getRequest();
454
-			return new \OC\URLGenerator(
455
-				$config,
456
-				$cacheFactory,
457
-				$request
458
-			);
459
-		});
460
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
461
-
462
-		$this->registerService('AppHelper', function ($c) {
463
-			return new \OC\AppHelper();
464
-		});
465
-		$this->registerAlias('AppFetcher', AppFetcher::class);
466
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
467
-
468
-		$this->registerService(\OCP\ICache::class, function ($c) {
469
-			return new Cache\File();
470
-		});
471
-		$this->registerAlias('UserCache', \OCP\ICache::class);
472
-
473
-		$this->registerService(Factory::class, function (Server $c) {
474
-
475
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
476
-				'\\OC\\Memcache\\ArrayCache',
477
-				'\\OC\\Memcache\\ArrayCache',
478
-				'\\OC\\Memcache\\ArrayCache'
479
-			);
480
-			$config = $c->getConfig();
481
-			$request = $c->getRequest();
482
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
483
-
484
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
485
-				$v = \OC_App::getAppVersions();
486
-				$v['core'] = implode(',', \OC_Util::getVersion());
487
-				$version = implode(',', $v);
488
-				$instanceId = \OC_Util::getInstanceId();
489
-				$path = \OC::$SERVERROOT;
490
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
491
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
492
-					$config->getSystemValue('memcache.local', null),
493
-					$config->getSystemValue('memcache.distributed', null),
494
-					$config->getSystemValue('memcache.locking', null)
495
-				);
496
-			}
497
-			return $arrayCacheFactory;
498
-
499
-		});
500
-		$this->registerAlias('MemCacheFactory', Factory::class);
501
-		$this->registerAlias(ICacheFactory::class, Factory::class);
502
-
503
-		$this->registerService('RedisFactory', function (Server $c) {
504
-			$systemConfig = $c->getSystemConfig();
505
-			return new RedisFactory($systemConfig);
506
-		});
507
-
508
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
509
-			return new \OC\Activity\Manager(
510
-				$c->getRequest(),
511
-				$c->getUserSession(),
512
-				$c->getConfig(),
513
-				$c->query(IValidator::class)
514
-			);
515
-		});
516
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
517
-
518
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
519
-			return new \OC\Activity\EventMerger(
520
-				$c->getL10N('lib')
521
-			);
522
-		});
523
-		$this->registerAlias(IValidator::class, Validator::class);
524
-
525
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
526
-			return new AvatarManager(
527
-				$c->query(\OC\User\Manager::class),
528
-				$c->getAppDataDir('avatar'),
529
-				$c->getL10N('lib'),
530
-				$c->getLogger(),
531
-				$c->getConfig()
532
-			);
533
-		});
534
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
535
-
536
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
537
-
538
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
539
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
540
-			$logger = Log::getLogClass($logType);
541
-			call_user_func(array($logger, 'init'));
542
-			$config = $this->getSystemConfig();
543
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
544
-
545
-			return new Log($logger, $config, null, $registry);
546
-		});
547
-		$this->registerAlias('Logger', \OCP\ILogger::class);
548
-
549
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
550
-			$config = $c->getConfig();
551
-			return new \OC\BackgroundJob\JobList(
552
-				$c->getDatabaseConnection(),
553
-				$config,
554
-				new TimeFactory()
555
-			);
556
-		});
557
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
558
-
559
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
560
-			$cacheFactory = $c->getMemCacheFactory();
561
-			$logger = $c->getLogger();
562
-			if ($cacheFactory->isAvailableLowLatency()) {
563
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
564
-			} else {
565
-				$router = new \OC\Route\Router($logger);
566
-			}
567
-			return $router;
568
-		});
569
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
570
-
571
-		$this->registerService(\OCP\ISearch::class, function ($c) {
572
-			return new Search();
573
-		});
574
-		$this->registerAlias('Search', \OCP\ISearch::class);
575
-
576
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
577
-			return new \OC\Security\RateLimiting\Limiter(
578
-				$this->getUserSession(),
579
-				$this->getRequest(),
580
-				new \OC\AppFramework\Utility\TimeFactory(),
581
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
582
-			);
583
-		});
584
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
585
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
586
-				$this->getMemCacheFactory(),
587
-				new \OC\AppFramework\Utility\TimeFactory()
588
-			);
589
-		});
590
-
591
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
592
-			return new SecureRandom();
593
-		});
594
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
595
-
596
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
597
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
598
-		});
599
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
600
-
601
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
602
-			return new Hasher($c->getConfig());
603
-		});
604
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
605
-
606
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
607
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
608
-		});
609
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
610
-
611
-		$this->registerService(IDBConnection::class, function (Server $c) {
612
-			$systemConfig = $c->getSystemConfig();
613
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
614
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
615
-			if (!$factory->isValidType($type)) {
616
-				throw new \OC\DatabaseException('Invalid database type');
617
-			}
618
-			$connectionParams = $factory->createConnectionParams();
619
-			$connection = $factory->getConnection($type, $connectionParams);
620
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
621
-			return $connection;
622
-		});
623
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
624
-
625
-		$this->registerService('HTTPHelper', function (Server $c) {
626
-			$config = $c->getConfig();
627
-			return new HTTPHelper(
628
-				$config,
629
-				$c->getHTTPClientService()
630
-			);
631
-		});
632
-
633
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
634
-			$user = \OC_User::getUser();
635
-			$uid = $user ? $user : null;
636
-			return new ClientService(
637
-				$c->getConfig(),
638
-				new \OC\Security\CertificateManager(
639
-					$uid,
640
-					new View(),
641
-					$c->getConfig(),
642
-					$c->getLogger(),
643
-					$c->getSecureRandom()
644
-				)
645
-			);
646
-		});
647
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
648
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
649
-			$eventLogger = new EventLogger();
650
-			if ($c->getSystemConfig()->getValue('debug', false)) {
651
-				// In debug mode, module is being activated by default
652
-				$eventLogger->activate();
653
-			}
654
-			return $eventLogger;
655
-		});
656
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
657
-
658
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
659
-			$queryLogger = new QueryLogger();
660
-			if ($c->getSystemConfig()->getValue('debug', false)) {
661
-				// In debug mode, module is being activated by default
662
-				$queryLogger->activate();
663
-			}
664
-			return $queryLogger;
665
-		});
666
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
667
-
668
-		$this->registerService(TempManager::class, function (Server $c) {
669
-			return new TempManager(
670
-				$c->getLogger(),
671
-				$c->getConfig()
672
-			);
673
-		});
674
-		$this->registerAlias('TempManager', TempManager::class);
675
-		$this->registerAlias(ITempManager::class, TempManager::class);
676
-
677
-		$this->registerService(AppManager::class, function (Server $c) {
678
-			return new \OC\App\AppManager(
679
-				$c->getUserSession(),
680
-				$c->query(\OC\AppConfig::class),
681
-				$c->getGroupManager(),
682
-				$c->getMemCacheFactory(),
683
-				$c->getEventDispatcher()
684
-			);
685
-		});
686
-		$this->registerAlias('AppManager', AppManager::class);
687
-		$this->registerAlias(IAppManager::class, AppManager::class);
688
-
689
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
690
-			return new DateTimeZone(
691
-				$c->getConfig(),
692
-				$c->getSession()
693
-			);
694
-		});
695
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
696
-
697
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
698
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
699
-
700
-			return new DateTimeFormatter(
701
-				$c->getDateTimeZone()->getTimeZone(),
702
-				$c->getL10N('lib', $language)
703
-			);
704
-		});
705
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
706
-
707
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
708
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
709
-			$listener = new UserMountCacheListener($mountCache);
710
-			$listener->listen($c->getUserManager());
711
-			return $mountCache;
712
-		});
713
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
714
-
715
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
716
-			$loader = \OC\Files\Filesystem::getLoader();
717
-			$mountCache = $c->query('UserMountCache');
718
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
719
-
720
-			// builtin providers
721
-
722
-			$config = $c->getConfig();
723
-			$manager->registerProvider(new CacheMountProvider($config));
724
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
725
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
726
-
727
-			return $manager;
728
-		});
729
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
730
-
731
-		$this->registerService('IniWrapper', function ($c) {
732
-			return new IniGetWrapper();
733
-		});
734
-		$this->registerService('AsyncCommandBus', function (Server $c) {
735
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
736
-			if ($busClass) {
737
-				list($app, $class) = explode('::', $busClass, 2);
738
-				if ($c->getAppManager()->isInstalled($app)) {
739
-					\OC_App::loadApp($app);
740
-					return $c->query($class);
741
-				} else {
742
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
743
-				}
744
-			} else {
745
-				$jobList = $c->getJobList();
746
-				return new CronBus($jobList);
747
-			}
748
-		});
749
-		$this->registerService('TrustedDomainHelper', function ($c) {
750
-			return new TrustedDomainHelper($this->getConfig());
751
-		});
752
-		$this->registerService('Throttler', function (Server $c) {
753
-			return new Throttler(
754
-				$c->getDatabaseConnection(),
755
-				new TimeFactory(),
756
-				$c->getLogger(),
757
-				$c->getConfig()
758
-			);
759
-		});
760
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
761
-			// IConfig and IAppManager requires a working database. This code
762
-			// might however be called when ownCloud is not yet setup.
763
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
764
-				$config = $c->getConfig();
765
-				$appManager = $c->getAppManager();
766
-			} else {
767
-				$config = null;
768
-				$appManager = null;
769
-			}
770
-
771
-			return new Checker(
772
-				new EnvironmentHelper(),
773
-				new FileAccessHelper(),
774
-				new AppLocator(),
775
-				$config,
776
-				$c->getMemCacheFactory(),
777
-				$appManager,
778
-				$c->getTempManager()
779
-			);
780
-		});
781
-		$this->registerService(\OCP\IRequest::class, function ($c) {
782
-			if (isset($this['urlParams'])) {
783
-				$urlParams = $this['urlParams'];
784
-			} else {
785
-				$urlParams = [];
786
-			}
787
-
788
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
789
-				&& in_array('fakeinput', stream_get_wrappers())
790
-			) {
791
-				$stream = 'fakeinput://data';
792
-			} else {
793
-				$stream = 'php://input';
794
-			}
795
-
796
-			return new Request(
797
-				[
798
-					'get' => $_GET,
799
-					'post' => $_POST,
800
-					'files' => $_FILES,
801
-					'server' => $_SERVER,
802
-					'env' => $_ENV,
803
-					'cookies' => $_COOKIE,
804
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
805
-						? $_SERVER['REQUEST_METHOD']
806
-						: null,
807
-					'urlParams' => $urlParams,
808
-				],
809
-				$this->getSecureRandom(),
810
-				$this->getConfig(),
811
-				$this->getCsrfTokenManager(),
812
-				$stream
813
-			);
814
-		});
815
-		$this->registerAlias('Request', \OCP\IRequest::class);
816
-
817
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
818
-			return new Mailer(
819
-				$c->getConfig(),
820
-				$c->getLogger(),
821
-				$c->query(Defaults::class),
822
-				$c->getURLGenerator(),
823
-				$c->getL10N('lib')
824
-			);
825
-		});
826
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
827
-
828
-		$this->registerService('LDAPProvider', function (Server $c) {
829
-			$config = $c->getConfig();
830
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
831
-			if (is_null($factoryClass)) {
832
-				throw new \Exception('ldapProviderFactory not set');
833
-			}
834
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
835
-			$factory = new $factoryClass($this);
836
-			return $factory->getLDAPProvider();
837
-		});
838
-		$this->registerService(ILockingProvider::class, function (Server $c) {
839
-			$ini = $c->getIniWrapper();
840
-			$config = $c->getConfig();
841
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
842
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
843
-				/** @var \OC\Memcache\Factory $memcacheFactory */
844
-				$memcacheFactory = $c->getMemCacheFactory();
845
-				$memcache = $memcacheFactory->createLocking('lock');
846
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
847
-					return new MemcacheLockingProvider($memcache, $ttl);
848
-				}
849
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
850
-			}
851
-			return new NoopLockingProvider();
852
-		});
853
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
854
-
855
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
856
-			return new \OC\Files\Mount\Manager();
857
-		});
858
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
859
-
860
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
861
-			return new \OC\Files\Type\Detection(
862
-				$c->getURLGenerator(),
863
-				\OC::$configDir,
864
-				\OC::$SERVERROOT . '/resources/config/'
865
-			);
866
-		});
867
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
868
-
869
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
870
-			return new \OC\Files\Type\Loader(
871
-				$c->getDatabaseConnection()
872
-			);
873
-		});
874
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
875
-		$this->registerService(BundleFetcher::class, function () {
876
-			return new BundleFetcher($this->getL10N('lib'));
877
-		});
878
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
879
-			return new Manager(
880
-				$c->query(IValidator::class)
881
-			);
882
-		});
883
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
884
-
885
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
886
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
887
-			$manager->registerCapability(function () use ($c) {
888
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
889
-			});
890
-			$manager->registerCapability(function () use ($c) {
891
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
892
-			});
893
-			return $manager;
894
-		});
895
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
896
-
897
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
898
-			$config = $c->getConfig();
899
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
900
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
901
-			$factory = new $factoryClass($this);
902
-			$manager = $factory->getManager();
903
-
904
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
905
-				$manager = $c->getUserManager();
906
-				$user = $manager->get($id);
907
-				if(is_null($user)) {
908
-					$l = $c->getL10N('core');
909
-					$displayName = $l->t('Unknown user');
910
-				} else {
911
-					$displayName = $user->getDisplayName();
912
-				}
913
-				return $displayName;
914
-			});
915
-
916
-			return $manager;
917
-		});
918
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
919
-
920
-		$this->registerService('ThemingDefaults', function (Server $c) {
921
-			/*
150
+    /** @var string */
151
+    private $webRoot;
152
+
153
+    /**
154
+     * @param string $webRoot
155
+     * @param \OC\Config $config
156
+     */
157
+    public function __construct($webRoot, \OC\Config $config) {
158
+        parent::__construct();
159
+        $this->webRoot = $webRoot;
160
+
161
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
162
+            return $c;
163
+        });
164
+
165
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
166
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
167
+
168
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
169
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
170
+
171
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
172
+
173
+
174
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
175
+            return new PreviewManager(
176
+                $c->getConfig(),
177
+                $c->getRootFolder(),
178
+                $c->getAppDataDir('preview'),
179
+                $c->getEventDispatcher(),
180
+                $c->getSession()->get('user_id')
181
+            );
182
+        });
183
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
184
+
185
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
186
+            return new \OC\Preview\Watcher(
187
+                $c->getAppDataDir('preview')
188
+            );
189
+        });
190
+
191
+        $this->registerService('EncryptionManager', function (Server $c) {
192
+            $view = new View();
193
+            $util = new Encryption\Util(
194
+                $view,
195
+                $c->getUserManager(),
196
+                $c->getGroupManager(),
197
+                $c->getConfig()
198
+            );
199
+            return new Encryption\Manager(
200
+                $c->getConfig(),
201
+                $c->getLogger(),
202
+                $c->getL10N('core'),
203
+                new View(),
204
+                $util,
205
+                new ArrayCache()
206
+            );
207
+        });
208
+
209
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
210
+            $util = new Encryption\Util(
211
+                new View(),
212
+                $c->getUserManager(),
213
+                $c->getGroupManager(),
214
+                $c->getConfig()
215
+            );
216
+            return new Encryption\File(
217
+                $util,
218
+                $c->getRootFolder(),
219
+                $c->getShareManager()
220
+            );
221
+        });
222
+
223
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
224
+            $view = new View();
225
+            $util = new Encryption\Util(
226
+                $view,
227
+                $c->getUserManager(),
228
+                $c->getGroupManager(),
229
+                $c->getConfig()
230
+            );
231
+
232
+            return new Encryption\Keys\Storage($view, $util);
233
+        });
234
+        $this->registerService('TagMapper', function (Server $c) {
235
+            return new TagMapper($c->getDatabaseConnection());
236
+        });
237
+
238
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
239
+            $tagMapper = $c->query('TagMapper');
240
+            return new TagManager($tagMapper, $c->getUserSession());
241
+        });
242
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
243
+
244
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
245
+            $config = $c->getConfig();
246
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
247
+            /** @var \OC\SystemTag\ManagerFactory $factory */
248
+            $factory = new $factoryClass($this);
249
+            return $factory;
250
+        });
251
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
+            return $c->query('SystemTagManagerFactory')->getManager();
253
+        });
254
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255
+
256
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
258
+        });
259
+        $this->registerService('RootFolder', function (Server $c) {
260
+            $manager = \OC\Files\Filesystem::getMountManager(null);
261
+            $view = new View();
262
+            $root = new Root(
263
+                $manager,
264
+                $view,
265
+                null,
266
+                $c->getUserMountCache(),
267
+                $this->getLogger(),
268
+                $this->getUserManager()
269
+            );
270
+            $connector = new HookConnector($root, $view);
271
+            $connector->viewToNode();
272
+
273
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
274
+            $previewConnector->connectWatcher();
275
+
276
+            return $root;
277
+        });
278
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279
+
280
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
+            return new LazyRoot(function () use ($c) {
282
+                return $c->query('RootFolder');
283
+            });
284
+        });
285
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286
+
287
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
288
+            $config = $c->getConfig();
289
+            return new \OC\User\Manager($config);
290
+        });
291
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
292
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
293
+
294
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304
+            });
305
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307
+            });
308
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310
+            });
311
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
315
+            });
316
+            return $groupManager;
317
+        });
318
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319
+
320
+        $this->registerService(Store::class, function (Server $c) {
321
+            $session = $c->getSession();
322
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
324
+            } else {
325
+                $tokenProvider = null;
326
+            }
327
+            $logger = $c->getLogger();
328
+            return new Store($session, $logger, $tokenProvider);
329
+        });
330
+        $this->registerAlias(IStore::class, Store::class);
331
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
332
+            $dbConnection = $c->getDatabaseConnection();
333
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
334
+        });
335
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
336
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
337
+            $crypto = $c->getCrypto();
338
+            $config = $c->getConfig();
339
+            $logger = $c->getLogger();
340
+            $timeFactory = new TimeFactory();
341
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
342
+        });
343
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
344
+
345
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
+            $manager = $c->getUserManager();
347
+            $session = new \OC\Session\Memory('');
348
+            $timeFactory = new TimeFactory();
349
+            // Token providers might require a working database. This code
350
+            // might however be called when ownCloud is not yet setup.
351
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
352
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
353
+            } else {
354
+                $defaultTokenProvider = null;
355
+            }
356
+
357
+            $dispatcher = $c->getEventDispatcher();
358
+
359
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
360
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
361
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
362
+            });
363
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
364
+                /** @var $user \OC\User\User */
365
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
366
+            });
367
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
368
+                /** @var $user \OC\User\User */
369
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
370
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
371
+            });
372
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
373
+                /** @var $user \OC\User\User */
374
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
375
+            });
376
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
377
+                /** @var $user \OC\User\User */
378
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
379
+            });
380
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
381
+                /** @var $user \OC\User\User */
382
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
383
+            });
384
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
385
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
386
+            });
387
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
388
+                /** @var $user \OC\User\User */
389
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
390
+            });
391
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
392
+                /** @var $user \OC\User\User */
393
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
394
+            });
395
+            $userSession->listen('\OC\User', 'logout', function () {
396
+                \OC_Hook::emit('OC_User', 'logout', array());
397
+            });
398
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
399
+                /** @var $user \OC\User\User */
400
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
401
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
402
+            });
403
+            return $userSession;
404
+        });
405
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
406
+
407
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
408
+            return new \OC\Authentication\TwoFactorAuth\Manager(
409
+                $c->getAppManager(),
410
+                $c->getSession(),
411
+                $c->getConfig(),
412
+                $c->getActivityManager(),
413
+                $c->getLogger(),
414
+                $c->query(\OC\Authentication\Token\IProvider::class),
415
+                $c->query(ITimeFactory::class)
416
+            );
417
+        });
418
+
419
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
420
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
421
+
422
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
423
+            return new \OC\AllConfig(
424
+                $c->getSystemConfig()
425
+            );
426
+        });
427
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
428
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
429
+
430
+        $this->registerService('SystemConfig', function ($c) use ($config) {
431
+            return new \OC\SystemConfig($config);
432
+        });
433
+
434
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
435
+            return new \OC\AppConfig($c->getDatabaseConnection());
436
+        });
437
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
438
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
439
+
440
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
441
+            return new \OC\L10N\Factory(
442
+                $c->getConfig(),
443
+                $c->getRequest(),
444
+                $c->getUserSession(),
445
+                \OC::$SERVERROOT
446
+            );
447
+        });
448
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
449
+
450
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
451
+            $config = $c->getConfig();
452
+            $cacheFactory = $c->getMemCacheFactory();
453
+            $request = $c->getRequest();
454
+            return new \OC\URLGenerator(
455
+                $config,
456
+                $cacheFactory,
457
+                $request
458
+            );
459
+        });
460
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
461
+
462
+        $this->registerService('AppHelper', function ($c) {
463
+            return new \OC\AppHelper();
464
+        });
465
+        $this->registerAlias('AppFetcher', AppFetcher::class);
466
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
467
+
468
+        $this->registerService(\OCP\ICache::class, function ($c) {
469
+            return new Cache\File();
470
+        });
471
+        $this->registerAlias('UserCache', \OCP\ICache::class);
472
+
473
+        $this->registerService(Factory::class, function (Server $c) {
474
+
475
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
476
+                '\\OC\\Memcache\\ArrayCache',
477
+                '\\OC\\Memcache\\ArrayCache',
478
+                '\\OC\\Memcache\\ArrayCache'
479
+            );
480
+            $config = $c->getConfig();
481
+            $request = $c->getRequest();
482
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
483
+
484
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
485
+                $v = \OC_App::getAppVersions();
486
+                $v['core'] = implode(',', \OC_Util::getVersion());
487
+                $version = implode(',', $v);
488
+                $instanceId = \OC_Util::getInstanceId();
489
+                $path = \OC::$SERVERROOT;
490
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
491
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
492
+                    $config->getSystemValue('memcache.local', null),
493
+                    $config->getSystemValue('memcache.distributed', null),
494
+                    $config->getSystemValue('memcache.locking', null)
495
+                );
496
+            }
497
+            return $arrayCacheFactory;
498
+
499
+        });
500
+        $this->registerAlias('MemCacheFactory', Factory::class);
501
+        $this->registerAlias(ICacheFactory::class, Factory::class);
502
+
503
+        $this->registerService('RedisFactory', function (Server $c) {
504
+            $systemConfig = $c->getSystemConfig();
505
+            return new RedisFactory($systemConfig);
506
+        });
507
+
508
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
509
+            return new \OC\Activity\Manager(
510
+                $c->getRequest(),
511
+                $c->getUserSession(),
512
+                $c->getConfig(),
513
+                $c->query(IValidator::class)
514
+            );
515
+        });
516
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
517
+
518
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
519
+            return new \OC\Activity\EventMerger(
520
+                $c->getL10N('lib')
521
+            );
522
+        });
523
+        $this->registerAlias(IValidator::class, Validator::class);
524
+
525
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
526
+            return new AvatarManager(
527
+                $c->query(\OC\User\Manager::class),
528
+                $c->getAppDataDir('avatar'),
529
+                $c->getL10N('lib'),
530
+                $c->getLogger(),
531
+                $c->getConfig()
532
+            );
533
+        });
534
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
535
+
536
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
537
+
538
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
539
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
540
+            $logger = Log::getLogClass($logType);
541
+            call_user_func(array($logger, 'init'));
542
+            $config = $this->getSystemConfig();
543
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
544
+
545
+            return new Log($logger, $config, null, $registry);
546
+        });
547
+        $this->registerAlias('Logger', \OCP\ILogger::class);
548
+
549
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
550
+            $config = $c->getConfig();
551
+            return new \OC\BackgroundJob\JobList(
552
+                $c->getDatabaseConnection(),
553
+                $config,
554
+                new TimeFactory()
555
+            );
556
+        });
557
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
558
+
559
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
560
+            $cacheFactory = $c->getMemCacheFactory();
561
+            $logger = $c->getLogger();
562
+            if ($cacheFactory->isAvailableLowLatency()) {
563
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
564
+            } else {
565
+                $router = new \OC\Route\Router($logger);
566
+            }
567
+            return $router;
568
+        });
569
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
570
+
571
+        $this->registerService(\OCP\ISearch::class, function ($c) {
572
+            return new Search();
573
+        });
574
+        $this->registerAlias('Search', \OCP\ISearch::class);
575
+
576
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
577
+            return new \OC\Security\RateLimiting\Limiter(
578
+                $this->getUserSession(),
579
+                $this->getRequest(),
580
+                new \OC\AppFramework\Utility\TimeFactory(),
581
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
582
+            );
583
+        });
584
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
585
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
586
+                $this->getMemCacheFactory(),
587
+                new \OC\AppFramework\Utility\TimeFactory()
588
+            );
589
+        });
590
+
591
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
592
+            return new SecureRandom();
593
+        });
594
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
595
+
596
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
597
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
598
+        });
599
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
600
+
601
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
602
+            return new Hasher($c->getConfig());
603
+        });
604
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
605
+
606
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
607
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
608
+        });
609
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
610
+
611
+        $this->registerService(IDBConnection::class, function (Server $c) {
612
+            $systemConfig = $c->getSystemConfig();
613
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
614
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
615
+            if (!$factory->isValidType($type)) {
616
+                throw new \OC\DatabaseException('Invalid database type');
617
+            }
618
+            $connectionParams = $factory->createConnectionParams();
619
+            $connection = $factory->getConnection($type, $connectionParams);
620
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
621
+            return $connection;
622
+        });
623
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
624
+
625
+        $this->registerService('HTTPHelper', function (Server $c) {
626
+            $config = $c->getConfig();
627
+            return new HTTPHelper(
628
+                $config,
629
+                $c->getHTTPClientService()
630
+            );
631
+        });
632
+
633
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
634
+            $user = \OC_User::getUser();
635
+            $uid = $user ? $user : null;
636
+            return new ClientService(
637
+                $c->getConfig(),
638
+                new \OC\Security\CertificateManager(
639
+                    $uid,
640
+                    new View(),
641
+                    $c->getConfig(),
642
+                    $c->getLogger(),
643
+                    $c->getSecureRandom()
644
+                )
645
+            );
646
+        });
647
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
648
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
649
+            $eventLogger = new EventLogger();
650
+            if ($c->getSystemConfig()->getValue('debug', false)) {
651
+                // In debug mode, module is being activated by default
652
+                $eventLogger->activate();
653
+            }
654
+            return $eventLogger;
655
+        });
656
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
657
+
658
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
659
+            $queryLogger = new QueryLogger();
660
+            if ($c->getSystemConfig()->getValue('debug', false)) {
661
+                // In debug mode, module is being activated by default
662
+                $queryLogger->activate();
663
+            }
664
+            return $queryLogger;
665
+        });
666
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
667
+
668
+        $this->registerService(TempManager::class, function (Server $c) {
669
+            return new TempManager(
670
+                $c->getLogger(),
671
+                $c->getConfig()
672
+            );
673
+        });
674
+        $this->registerAlias('TempManager', TempManager::class);
675
+        $this->registerAlias(ITempManager::class, TempManager::class);
676
+
677
+        $this->registerService(AppManager::class, function (Server $c) {
678
+            return new \OC\App\AppManager(
679
+                $c->getUserSession(),
680
+                $c->query(\OC\AppConfig::class),
681
+                $c->getGroupManager(),
682
+                $c->getMemCacheFactory(),
683
+                $c->getEventDispatcher()
684
+            );
685
+        });
686
+        $this->registerAlias('AppManager', AppManager::class);
687
+        $this->registerAlias(IAppManager::class, AppManager::class);
688
+
689
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
690
+            return new DateTimeZone(
691
+                $c->getConfig(),
692
+                $c->getSession()
693
+            );
694
+        });
695
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
696
+
697
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
698
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
699
+
700
+            return new DateTimeFormatter(
701
+                $c->getDateTimeZone()->getTimeZone(),
702
+                $c->getL10N('lib', $language)
703
+            );
704
+        });
705
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
706
+
707
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
708
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
709
+            $listener = new UserMountCacheListener($mountCache);
710
+            $listener->listen($c->getUserManager());
711
+            return $mountCache;
712
+        });
713
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
714
+
715
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
716
+            $loader = \OC\Files\Filesystem::getLoader();
717
+            $mountCache = $c->query('UserMountCache');
718
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
719
+
720
+            // builtin providers
721
+
722
+            $config = $c->getConfig();
723
+            $manager->registerProvider(new CacheMountProvider($config));
724
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
725
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
726
+
727
+            return $manager;
728
+        });
729
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
730
+
731
+        $this->registerService('IniWrapper', function ($c) {
732
+            return new IniGetWrapper();
733
+        });
734
+        $this->registerService('AsyncCommandBus', function (Server $c) {
735
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
736
+            if ($busClass) {
737
+                list($app, $class) = explode('::', $busClass, 2);
738
+                if ($c->getAppManager()->isInstalled($app)) {
739
+                    \OC_App::loadApp($app);
740
+                    return $c->query($class);
741
+                } else {
742
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
743
+                }
744
+            } else {
745
+                $jobList = $c->getJobList();
746
+                return new CronBus($jobList);
747
+            }
748
+        });
749
+        $this->registerService('TrustedDomainHelper', function ($c) {
750
+            return new TrustedDomainHelper($this->getConfig());
751
+        });
752
+        $this->registerService('Throttler', function (Server $c) {
753
+            return new Throttler(
754
+                $c->getDatabaseConnection(),
755
+                new TimeFactory(),
756
+                $c->getLogger(),
757
+                $c->getConfig()
758
+            );
759
+        });
760
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
761
+            // IConfig and IAppManager requires a working database. This code
762
+            // might however be called when ownCloud is not yet setup.
763
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
764
+                $config = $c->getConfig();
765
+                $appManager = $c->getAppManager();
766
+            } else {
767
+                $config = null;
768
+                $appManager = null;
769
+            }
770
+
771
+            return new Checker(
772
+                new EnvironmentHelper(),
773
+                new FileAccessHelper(),
774
+                new AppLocator(),
775
+                $config,
776
+                $c->getMemCacheFactory(),
777
+                $appManager,
778
+                $c->getTempManager()
779
+            );
780
+        });
781
+        $this->registerService(\OCP\IRequest::class, function ($c) {
782
+            if (isset($this['urlParams'])) {
783
+                $urlParams = $this['urlParams'];
784
+            } else {
785
+                $urlParams = [];
786
+            }
787
+
788
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
789
+                && in_array('fakeinput', stream_get_wrappers())
790
+            ) {
791
+                $stream = 'fakeinput://data';
792
+            } else {
793
+                $stream = 'php://input';
794
+            }
795
+
796
+            return new Request(
797
+                [
798
+                    'get' => $_GET,
799
+                    'post' => $_POST,
800
+                    'files' => $_FILES,
801
+                    'server' => $_SERVER,
802
+                    'env' => $_ENV,
803
+                    'cookies' => $_COOKIE,
804
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
805
+                        ? $_SERVER['REQUEST_METHOD']
806
+                        : null,
807
+                    'urlParams' => $urlParams,
808
+                ],
809
+                $this->getSecureRandom(),
810
+                $this->getConfig(),
811
+                $this->getCsrfTokenManager(),
812
+                $stream
813
+            );
814
+        });
815
+        $this->registerAlias('Request', \OCP\IRequest::class);
816
+
817
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
818
+            return new Mailer(
819
+                $c->getConfig(),
820
+                $c->getLogger(),
821
+                $c->query(Defaults::class),
822
+                $c->getURLGenerator(),
823
+                $c->getL10N('lib')
824
+            );
825
+        });
826
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
827
+
828
+        $this->registerService('LDAPProvider', function (Server $c) {
829
+            $config = $c->getConfig();
830
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
831
+            if (is_null($factoryClass)) {
832
+                throw new \Exception('ldapProviderFactory not set');
833
+            }
834
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
835
+            $factory = new $factoryClass($this);
836
+            return $factory->getLDAPProvider();
837
+        });
838
+        $this->registerService(ILockingProvider::class, function (Server $c) {
839
+            $ini = $c->getIniWrapper();
840
+            $config = $c->getConfig();
841
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
842
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
843
+                /** @var \OC\Memcache\Factory $memcacheFactory */
844
+                $memcacheFactory = $c->getMemCacheFactory();
845
+                $memcache = $memcacheFactory->createLocking('lock');
846
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
847
+                    return new MemcacheLockingProvider($memcache, $ttl);
848
+                }
849
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
850
+            }
851
+            return new NoopLockingProvider();
852
+        });
853
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
854
+
855
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
856
+            return new \OC\Files\Mount\Manager();
857
+        });
858
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
859
+
860
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
861
+            return new \OC\Files\Type\Detection(
862
+                $c->getURLGenerator(),
863
+                \OC::$configDir,
864
+                \OC::$SERVERROOT . '/resources/config/'
865
+            );
866
+        });
867
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
868
+
869
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
870
+            return new \OC\Files\Type\Loader(
871
+                $c->getDatabaseConnection()
872
+            );
873
+        });
874
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
875
+        $this->registerService(BundleFetcher::class, function () {
876
+            return new BundleFetcher($this->getL10N('lib'));
877
+        });
878
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
879
+            return new Manager(
880
+                $c->query(IValidator::class)
881
+            );
882
+        });
883
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
884
+
885
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
886
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
887
+            $manager->registerCapability(function () use ($c) {
888
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
889
+            });
890
+            $manager->registerCapability(function () use ($c) {
891
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
892
+            });
893
+            return $manager;
894
+        });
895
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
896
+
897
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
898
+            $config = $c->getConfig();
899
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
900
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
901
+            $factory = new $factoryClass($this);
902
+            $manager = $factory->getManager();
903
+
904
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
905
+                $manager = $c->getUserManager();
906
+                $user = $manager->get($id);
907
+                if(is_null($user)) {
908
+                    $l = $c->getL10N('core');
909
+                    $displayName = $l->t('Unknown user');
910
+                } else {
911
+                    $displayName = $user->getDisplayName();
912
+                }
913
+                return $displayName;
914
+            });
915
+
916
+            return $manager;
917
+        });
918
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
919
+
920
+        $this->registerService('ThemingDefaults', function (Server $c) {
921
+            /*
922 922
 			 * Dark magic for autoloader.
923 923
 			 * If we do a class_exists it will try to load the class which will
924 924
 			 * make composer cache the result. Resulting in errors when enabling
925 925
 			 * the theming app.
926 926
 			 */
927
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
928
-			if (isset($prefixes['OCA\\Theming\\'])) {
929
-				$classExists = true;
930
-			} else {
931
-				$classExists = false;
932
-			}
933
-
934
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
935
-				return new ThemingDefaults(
936
-					$c->getConfig(),
937
-					$c->getL10N('theming'),
938
-					$c->getURLGenerator(),
939
-					$c->getAppDataDir('theming'),
940
-					$c->getMemCacheFactory(),
941
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
942
-					$this->getAppManager()
943
-				);
944
-			}
945
-			return new \OC_Defaults();
946
-		});
947
-		$this->registerService(SCSSCacher::class, function (Server $c) {
948
-			/** @var Factory $cacheFactory */
949
-			$cacheFactory = $c->query(Factory::class);
950
-			return new SCSSCacher(
951
-				$c->getLogger(),
952
-				$c->query(\OC\Files\AppData\Factory::class),
953
-				$c->getURLGenerator(),
954
-				$c->getConfig(),
955
-				$c->getThemingDefaults(),
956
-				\OC::$SERVERROOT,
957
-				$cacheFactory->createDistributed('SCSS')
958
-			);
959
-		});
960
-		$this->registerService(EventDispatcher::class, function () {
961
-			return new EventDispatcher();
962
-		});
963
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
964
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
965
-
966
-		$this->registerService('CryptoWrapper', function (Server $c) {
967
-			// FIXME: Instantiiated here due to cyclic dependency
968
-			$request = new Request(
969
-				[
970
-					'get' => $_GET,
971
-					'post' => $_POST,
972
-					'files' => $_FILES,
973
-					'server' => $_SERVER,
974
-					'env' => $_ENV,
975
-					'cookies' => $_COOKIE,
976
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
977
-						? $_SERVER['REQUEST_METHOD']
978
-						: null,
979
-				],
980
-				$c->getSecureRandom(),
981
-				$c->getConfig()
982
-			);
983
-
984
-			return new CryptoWrapper(
985
-				$c->getConfig(),
986
-				$c->getCrypto(),
987
-				$c->getSecureRandom(),
988
-				$request
989
-			);
990
-		});
991
-		$this->registerService('CsrfTokenManager', function (Server $c) {
992
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
993
-
994
-			return new CsrfTokenManager(
995
-				$tokenGenerator,
996
-				$c->query(SessionStorage::class)
997
-			);
998
-		});
999
-		$this->registerService(SessionStorage::class, function (Server $c) {
1000
-			return new SessionStorage($c->getSession());
1001
-		});
1002
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1003
-			return new ContentSecurityPolicyManager();
1004
-		});
1005
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1006
-
1007
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1008
-			return new ContentSecurityPolicyNonceManager(
1009
-				$c->getCsrfTokenManager(),
1010
-				$c->getRequest()
1011
-			);
1012
-		});
1013
-
1014
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1015
-			$config = $c->getConfig();
1016
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1017
-			/** @var \OCP\Share\IProviderFactory $factory */
1018
-			$factory = new $factoryClass($this);
1019
-
1020
-			$manager = new \OC\Share20\Manager(
1021
-				$c->getLogger(),
1022
-				$c->getConfig(),
1023
-				$c->getSecureRandom(),
1024
-				$c->getHasher(),
1025
-				$c->getMountManager(),
1026
-				$c->getGroupManager(),
1027
-				$c->getL10N('lib'),
1028
-				$c->getL10NFactory(),
1029
-				$factory,
1030
-				$c->getUserManager(),
1031
-				$c->getLazyRootFolder(),
1032
-				$c->getEventDispatcher(),
1033
-				$c->getMailer(),
1034
-				$c->getURLGenerator(),
1035
-				$c->getThemingDefaults()
1036
-			);
1037
-
1038
-			return $manager;
1039
-		});
1040
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1041
-
1042
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1043
-			$instance = new Collaboration\Collaborators\Search($c);
1044
-
1045
-			// register default plugins
1046
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1047
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1048
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1049
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1050
-
1051
-			return $instance;
1052
-		});
1053
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1054
-
1055
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1056
-
1057
-		$this->registerService('SettingsManager', function (Server $c) {
1058
-			$manager = new \OC\Settings\Manager(
1059
-				$c->getLogger(),
1060
-				$c->getDatabaseConnection(),
1061
-				$c->getL10N('lib'),
1062
-				$c->getConfig(),
1063
-				$c->getEncryptionManager(),
1064
-				$c->getUserManager(),
1065
-				$c->getLockingProvider(),
1066
-				$c->getRequest(),
1067
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
1068
-				$c->getURLGenerator(),
1069
-				$c->query(AccountManager::class),
1070
-				$c->getGroupManager(),
1071
-				$c->getL10NFactory(),
1072
-				$c->getThemingDefaults(),
1073
-				$c->getAppManager()
1074
-			);
1075
-			return $manager;
1076
-		});
1077
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1078
-			return new \OC\Files\AppData\Factory(
1079
-				$c->getRootFolder(),
1080
-				$c->getSystemConfig()
1081
-			);
1082
-		});
1083
-
1084
-		$this->registerService('LockdownManager', function (Server $c) {
1085
-			return new LockdownManager(function () use ($c) {
1086
-				return $c->getSession();
1087
-			});
1088
-		});
1089
-
1090
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1091
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1092
-		});
1093
-
1094
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1095
-			return new CloudIdManager();
1096
-		});
1097
-
1098
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1099
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1100
-
1101
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1102
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1103
-
1104
-		$this->registerService(Defaults::class, function (Server $c) {
1105
-			return new Defaults(
1106
-				$c->getThemingDefaults()
1107
-			);
1108
-		});
1109
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1110
-
1111
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1112
-			return $c->query(\OCP\IUserSession::class)->getSession();
1113
-		});
1114
-
1115
-		$this->registerService(IShareHelper::class, function (Server $c) {
1116
-			return new ShareHelper(
1117
-				$c->query(\OCP\Share\IManager::class)
1118
-			);
1119
-		});
1120
-
1121
-		$this->registerService(Installer::class, function(Server $c) {
1122
-			return new Installer(
1123
-				$c->getAppFetcher(),
1124
-				$c->getHTTPClientService(),
1125
-				$c->getTempManager(),
1126
-				$c->getLogger(),
1127
-				$c->getConfig()
1128
-			);
1129
-		});
1130
-
1131
-		$this->registerService(IApiFactory::class, function(Server $c) {
1132
-			return new ApiFactory($c->getHTTPClientService());
1133
-		});
1134
-
1135
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1136
-			$memcacheFactory = $c->getMemCacheFactory();
1137
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1138
-		});
1139
-
1140
-		$this->registerService(IContactsStore::class, function(Server $c) {
1141
-			return new ContactsStore(
1142
-				$c->getContactsManager(),
1143
-				$c->getConfig(),
1144
-				$c->getUserManager(),
1145
-				$c->getGroupManager()
1146
-			);
1147
-		});
1148
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1149
-
1150
-		$this->connectDispatcher();
1151
-	}
1152
-
1153
-	/**
1154
-	 * @return \OCP\Calendar\IManager
1155
-	 */
1156
-	public function getCalendarManager() {
1157
-		return $this->query('CalendarManager');
1158
-	}
1159
-
1160
-	private function connectDispatcher() {
1161
-		$dispatcher = $this->getEventDispatcher();
1162
-
1163
-		// Delete avatar on user deletion
1164
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1165
-			$logger = $this->getLogger();
1166
-			$manager = $this->getAvatarManager();
1167
-			/** @var IUser $user */
1168
-			$user = $e->getSubject();
1169
-
1170
-			try {
1171
-				$avatar = $manager->getAvatar($user->getUID());
1172
-				$avatar->remove();
1173
-			} catch (NotFoundException $e) {
1174
-				// no avatar to remove
1175
-			} catch (\Exception $e) {
1176
-				// Ignore exceptions
1177
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1178
-			}
1179
-		});
1180
-
1181
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1182
-			$manager = $this->getAvatarManager();
1183
-			/** @var IUser $user */
1184
-			$user = $e->getSubject();
1185
-			$feature = $e->getArgument('feature');
1186
-			$oldValue = $e->getArgument('oldValue');
1187
-			$value = $e->getArgument('value');
1188
-
1189
-			try {
1190
-				$avatar = $manager->getAvatar($user->getUID());
1191
-				$avatar->userChanged($feature, $oldValue, $value);
1192
-			} catch (NotFoundException $e) {
1193
-				// no avatar to remove
1194
-			}
1195
-		});
1196
-	}
1197
-
1198
-	/**
1199
-	 * @return \OCP\Contacts\IManager
1200
-	 */
1201
-	public function getContactsManager() {
1202
-		return $this->query('ContactsManager');
1203
-	}
1204
-
1205
-	/**
1206
-	 * @return \OC\Encryption\Manager
1207
-	 */
1208
-	public function getEncryptionManager() {
1209
-		return $this->query('EncryptionManager');
1210
-	}
1211
-
1212
-	/**
1213
-	 * @return \OC\Encryption\File
1214
-	 */
1215
-	public function getEncryptionFilesHelper() {
1216
-		return $this->query('EncryptionFileHelper');
1217
-	}
1218
-
1219
-	/**
1220
-	 * @return \OCP\Encryption\Keys\IStorage
1221
-	 */
1222
-	public function getEncryptionKeyStorage() {
1223
-		return $this->query('EncryptionKeyStorage');
1224
-	}
1225
-
1226
-	/**
1227
-	 * The current request object holding all information about the request
1228
-	 * currently being processed is returned from this method.
1229
-	 * In case the current execution was not initiated by a web request null is returned
1230
-	 *
1231
-	 * @return \OCP\IRequest
1232
-	 */
1233
-	public function getRequest() {
1234
-		return $this->query('Request');
1235
-	}
1236
-
1237
-	/**
1238
-	 * Returns the preview manager which can create preview images for a given file
1239
-	 *
1240
-	 * @return \OCP\IPreview
1241
-	 */
1242
-	public function getPreviewManager() {
1243
-		return $this->query('PreviewManager');
1244
-	}
1245
-
1246
-	/**
1247
-	 * Returns the tag manager which can get and set tags for different object types
1248
-	 *
1249
-	 * @see \OCP\ITagManager::load()
1250
-	 * @return \OCP\ITagManager
1251
-	 */
1252
-	public function getTagManager() {
1253
-		return $this->query('TagManager');
1254
-	}
1255
-
1256
-	/**
1257
-	 * Returns the system-tag manager
1258
-	 *
1259
-	 * @return \OCP\SystemTag\ISystemTagManager
1260
-	 *
1261
-	 * @since 9.0.0
1262
-	 */
1263
-	public function getSystemTagManager() {
1264
-		return $this->query('SystemTagManager');
1265
-	}
1266
-
1267
-	/**
1268
-	 * Returns the system-tag object mapper
1269
-	 *
1270
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1271
-	 *
1272
-	 * @since 9.0.0
1273
-	 */
1274
-	public function getSystemTagObjectMapper() {
1275
-		return $this->query('SystemTagObjectMapper');
1276
-	}
1277
-
1278
-	/**
1279
-	 * Returns the avatar manager, used for avatar functionality
1280
-	 *
1281
-	 * @return \OCP\IAvatarManager
1282
-	 */
1283
-	public function getAvatarManager() {
1284
-		return $this->query('AvatarManager');
1285
-	}
1286
-
1287
-	/**
1288
-	 * Returns the root folder of ownCloud's data directory
1289
-	 *
1290
-	 * @return \OCP\Files\IRootFolder
1291
-	 */
1292
-	public function getRootFolder() {
1293
-		return $this->query('LazyRootFolder');
1294
-	}
1295
-
1296
-	/**
1297
-	 * Returns the root folder of ownCloud's data directory
1298
-	 * This is the lazy variant so this gets only initialized once it
1299
-	 * is actually used.
1300
-	 *
1301
-	 * @return \OCP\Files\IRootFolder
1302
-	 */
1303
-	public function getLazyRootFolder() {
1304
-		return $this->query('LazyRootFolder');
1305
-	}
1306
-
1307
-	/**
1308
-	 * Returns a view to ownCloud's files folder
1309
-	 *
1310
-	 * @param string $userId user ID
1311
-	 * @return \OCP\Files\Folder|null
1312
-	 */
1313
-	public function getUserFolder($userId = null) {
1314
-		if ($userId === null) {
1315
-			$user = $this->getUserSession()->getUser();
1316
-			if (!$user) {
1317
-				return null;
1318
-			}
1319
-			$userId = $user->getUID();
1320
-		}
1321
-		$root = $this->getRootFolder();
1322
-		return $root->getUserFolder($userId);
1323
-	}
1324
-
1325
-	/**
1326
-	 * Returns an app-specific view in ownClouds data directory
1327
-	 *
1328
-	 * @return \OCP\Files\Folder
1329
-	 * @deprecated since 9.2.0 use IAppData
1330
-	 */
1331
-	public function getAppFolder() {
1332
-		$dir = '/' . \OC_App::getCurrentApp();
1333
-		$root = $this->getRootFolder();
1334
-		if (!$root->nodeExists($dir)) {
1335
-			$folder = $root->newFolder($dir);
1336
-		} else {
1337
-			$folder = $root->get($dir);
1338
-		}
1339
-		return $folder;
1340
-	}
1341
-
1342
-	/**
1343
-	 * @return \OC\User\Manager
1344
-	 */
1345
-	public function getUserManager() {
1346
-		return $this->query('UserManager');
1347
-	}
1348
-
1349
-	/**
1350
-	 * @return \OC\Group\Manager
1351
-	 */
1352
-	public function getGroupManager() {
1353
-		return $this->query('GroupManager');
1354
-	}
1355
-
1356
-	/**
1357
-	 * @return \OC\User\Session
1358
-	 */
1359
-	public function getUserSession() {
1360
-		return $this->query('UserSession');
1361
-	}
1362
-
1363
-	/**
1364
-	 * @return \OCP\ISession
1365
-	 */
1366
-	public function getSession() {
1367
-		return $this->query('UserSession')->getSession();
1368
-	}
1369
-
1370
-	/**
1371
-	 * @param \OCP\ISession $session
1372
-	 */
1373
-	public function setSession(\OCP\ISession $session) {
1374
-		$this->query(SessionStorage::class)->setSession($session);
1375
-		$this->query('UserSession')->setSession($session);
1376
-		$this->query(Store::class)->setSession($session);
1377
-	}
1378
-
1379
-	/**
1380
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1381
-	 */
1382
-	public function getTwoFactorAuthManager() {
1383
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1384
-	}
1385
-
1386
-	/**
1387
-	 * @return \OC\NavigationManager
1388
-	 */
1389
-	public function getNavigationManager() {
1390
-		return $this->query('NavigationManager');
1391
-	}
1392
-
1393
-	/**
1394
-	 * @return \OCP\IConfig
1395
-	 */
1396
-	public function getConfig() {
1397
-		return $this->query('AllConfig');
1398
-	}
1399
-
1400
-	/**
1401
-	 * @return \OC\SystemConfig
1402
-	 */
1403
-	public function getSystemConfig() {
1404
-		return $this->query('SystemConfig');
1405
-	}
1406
-
1407
-	/**
1408
-	 * Returns the app config manager
1409
-	 *
1410
-	 * @return \OCP\IAppConfig
1411
-	 */
1412
-	public function getAppConfig() {
1413
-		return $this->query('AppConfig');
1414
-	}
1415
-
1416
-	/**
1417
-	 * @return \OCP\L10N\IFactory
1418
-	 */
1419
-	public function getL10NFactory() {
1420
-		return $this->query('L10NFactory');
1421
-	}
1422
-
1423
-	/**
1424
-	 * get an L10N instance
1425
-	 *
1426
-	 * @param string $app appid
1427
-	 * @param string $lang
1428
-	 * @return IL10N
1429
-	 */
1430
-	public function getL10N($app, $lang = null) {
1431
-		return $this->getL10NFactory()->get($app, $lang);
1432
-	}
1433
-
1434
-	/**
1435
-	 * @return \OCP\IURLGenerator
1436
-	 */
1437
-	public function getURLGenerator() {
1438
-		return $this->query('URLGenerator');
1439
-	}
1440
-
1441
-	/**
1442
-	 * @return \OCP\IHelper
1443
-	 */
1444
-	public function getHelper() {
1445
-		return $this->query('AppHelper');
1446
-	}
1447
-
1448
-	/**
1449
-	 * @return AppFetcher
1450
-	 */
1451
-	public function getAppFetcher() {
1452
-		return $this->query(AppFetcher::class);
1453
-	}
1454
-
1455
-	/**
1456
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1457
-	 * getMemCacheFactory() instead.
1458
-	 *
1459
-	 * @return \OCP\ICache
1460
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1461
-	 */
1462
-	public function getCache() {
1463
-		return $this->query('UserCache');
1464
-	}
1465
-
1466
-	/**
1467
-	 * Returns an \OCP\CacheFactory instance
1468
-	 *
1469
-	 * @return \OCP\ICacheFactory
1470
-	 */
1471
-	public function getMemCacheFactory() {
1472
-		return $this->query('MemCacheFactory');
1473
-	}
1474
-
1475
-	/**
1476
-	 * Returns an \OC\RedisFactory instance
1477
-	 *
1478
-	 * @return \OC\RedisFactory
1479
-	 */
1480
-	public function getGetRedisFactory() {
1481
-		return $this->query('RedisFactory');
1482
-	}
1483
-
1484
-
1485
-	/**
1486
-	 * Returns the current session
1487
-	 *
1488
-	 * @return \OCP\IDBConnection
1489
-	 */
1490
-	public function getDatabaseConnection() {
1491
-		return $this->query('DatabaseConnection');
1492
-	}
1493
-
1494
-	/**
1495
-	 * Returns the activity manager
1496
-	 *
1497
-	 * @return \OCP\Activity\IManager
1498
-	 */
1499
-	public function getActivityManager() {
1500
-		return $this->query('ActivityManager');
1501
-	}
1502
-
1503
-	/**
1504
-	 * Returns an job list for controlling background jobs
1505
-	 *
1506
-	 * @return \OCP\BackgroundJob\IJobList
1507
-	 */
1508
-	public function getJobList() {
1509
-		return $this->query('JobList');
1510
-	}
1511
-
1512
-	/**
1513
-	 * Returns a logger instance
1514
-	 *
1515
-	 * @return \OCP\ILogger
1516
-	 */
1517
-	public function getLogger() {
1518
-		return $this->query('Logger');
1519
-	}
1520
-
1521
-	/**
1522
-	 * Returns a router for generating and matching urls
1523
-	 *
1524
-	 * @return \OCP\Route\IRouter
1525
-	 */
1526
-	public function getRouter() {
1527
-		return $this->query('Router');
1528
-	}
1529
-
1530
-	/**
1531
-	 * Returns a search instance
1532
-	 *
1533
-	 * @return \OCP\ISearch
1534
-	 */
1535
-	public function getSearch() {
1536
-		return $this->query('Search');
1537
-	}
1538
-
1539
-	/**
1540
-	 * Returns a SecureRandom instance
1541
-	 *
1542
-	 * @return \OCP\Security\ISecureRandom
1543
-	 */
1544
-	public function getSecureRandom() {
1545
-		return $this->query('SecureRandom');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Returns a Crypto instance
1550
-	 *
1551
-	 * @return \OCP\Security\ICrypto
1552
-	 */
1553
-	public function getCrypto() {
1554
-		return $this->query('Crypto');
1555
-	}
1556
-
1557
-	/**
1558
-	 * Returns a Hasher instance
1559
-	 *
1560
-	 * @return \OCP\Security\IHasher
1561
-	 */
1562
-	public function getHasher() {
1563
-		return $this->query('Hasher');
1564
-	}
1565
-
1566
-	/**
1567
-	 * Returns a CredentialsManager instance
1568
-	 *
1569
-	 * @return \OCP\Security\ICredentialsManager
1570
-	 */
1571
-	public function getCredentialsManager() {
1572
-		return $this->query('CredentialsManager');
1573
-	}
1574
-
1575
-	/**
1576
-	 * Returns an instance of the HTTP helper class
1577
-	 *
1578
-	 * @deprecated Use getHTTPClientService()
1579
-	 * @return \OC\HTTPHelper
1580
-	 */
1581
-	public function getHTTPHelper() {
1582
-		return $this->query('HTTPHelper');
1583
-	}
1584
-
1585
-	/**
1586
-	 * Get the certificate manager for the user
1587
-	 *
1588
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1589
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1590
-	 */
1591
-	public function getCertificateManager($userId = '') {
1592
-		if ($userId === '') {
1593
-			$userSession = $this->getUserSession();
1594
-			$user = $userSession->getUser();
1595
-			if (is_null($user)) {
1596
-				return null;
1597
-			}
1598
-			$userId = $user->getUID();
1599
-		}
1600
-		return new CertificateManager(
1601
-			$userId,
1602
-			new View(),
1603
-			$this->getConfig(),
1604
-			$this->getLogger(),
1605
-			$this->getSecureRandom()
1606
-		);
1607
-	}
1608
-
1609
-	/**
1610
-	 * Returns an instance of the HTTP client service
1611
-	 *
1612
-	 * @return \OCP\Http\Client\IClientService
1613
-	 */
1614
-	public function getHTTPClientService() {
1615
-		return $this->query('HttpClientService');
1616
-	}
1617
-
1618
-	/**
1619
-	 * Create a new event source
1620
-	 *
1621
-	 * @return \OCP\IEventSource
1622
-	 */
1623
-	public function createEventSource() {
1624
-		return new \OC_EventSource();
1625
-	}
1626
-
1627
-	/**
1628
-	 * Get the active event logger
1629
-	 *
1630
-	 * The returned logger only logs data when debug mode is enabled
1631
-	 *
1632
-	 * @return \OCP\Diagnostics\IEventLogger
1633
-	 */
1634
-	public function getEventLogger() {
1635
-		return $this->query('EventLogger');
1636
-	}
1637
-
1638
-	/**
1639
-	 * Get the active query logger
1640
-	 *
1641
-	 * The returned logger only logs data when debug mode is enabled
1642
-	 *
1643
-	 * @return \OCP\Diagnostics\IQueryLogger
1644
-	 */
1645
-	public function getQueryLogger() {
1646
-		return $this->query('QueryLogger');
1647
-	}
1648
-
1649
-	/**
1650
-	 * Get the manager for temporary files and folders
1651
-	 *
1652
-	 * @return \OCP\ITempManager
1653
-	 */
1654
-	public function getTempManager() {
1655
-		return $this->query('TempManager');
1656
-	}
1657
-
1658
-	/**
1659
-	 * Get the app manager
1660
-	 *
1661
-	 * @return \OCP\App\IAppManager
1662
-	 */
1663
-	public function getAppManager() {
1664
-		return $this->query('AppManager');
1665
-	}
1666
-
1667
-	/**
1668
-	 * Creates a new mailer
1669
-	 *
1670
-	 * @return \OCP\Mail\IMailer
1671
-	 */
1672
-	public function getMailer() {
1673
-		return $this->query('Mailer');
1674
-	}
1675
-
1676
-	/**
1677
-	 * Get the webroot
1678
-	 *
1679
-	 * @return string
1680
-	 */
1681
-	public function getWebRoot() {
1682
-		return $this->webRoot;
1683
-	}
1684
-
1685
-	/**
1686
-	 * @return \OC\OCSClient
1687
-	 */
1688
-	public function getOcsClient() {
1689
-		return $this->query('OcsClient');
1690
-	}
1691
-
1692
-	/**
1693
-	 * @return \OCP\IDateTimeZone
1694
-	 */
1695
-	public function getDateTimeZone() {
1696
-		return $this->query('DateTimeZone');
1697
-	}
1698
-
1699
-	/**
1700
-	 * @return \OCP\IDateTimeFormatter
1701
-	 */
1702
-	public function getDateTimeFormatter() {
1703
-		return $this->query('DateTimeFormatter');
1704
-	}
1705
-
1706
-	/**
1707
-	 * @return \OCP\Files\Config\IMountProviderCollection
1708
-	 */
1709
-	public function getMountProviderCollection() {
1710
-		return $this->query('MountConfigManager');
1711
-	}
1712
-
1713
-	/**
1714
-	 * Get the IniWrapper
1715
-	 *
1716
-	 * @return IniGetWrapper
1717
-	 */
1718
-	public function getIniWrapper() {
1719
-		return $this->query('IniWrapper');
1720
-	}
1721
-
1722
-	/**
1723
-	 * @return \OCP\Command\IBus
1724
-	 */
1725
-	public function getCommandBus() {
1726
-		return $this->query('AsyncCommandBus');
1727
-	}
1728
-
1729
-	/**
1730
-	 * Get the trusted domain helper
1731
-	 *
1732
-	 * @return TrustedDomainHelper
1733
-	 */
1734
-	public function getTrustedDomainHelper() {
1735
-		return $this->query('TrustedDomainHelper');
1736
-	}
1737
-
1738
-	/**
1739
-	 * Get the locking provider
1740
-	 *
1741
-	 * @return \OCP\Lock\ILockingProvider
1742
-	 * @since 8.1.0
1743
-	 */
1744
-	public function getLockingProvider() {
1745
-		return $this->query('LockingProvider');
1746
-	}
1747
-
1748
-	/**
1749
-	 * @return \OCP\Files\Mount\IMountManager
1750
-	 **/
1751
-	function getMountManager() {
1752
-		return $this->query('MountManager');
1753
-	}
1754
-
1755
-	/** @return \OCP\Files\Config\IUserMountCache */
1756
-	function getUserMountCache() {
1757
-		return $this->query('UserMountCache');
1758
-	}
1759
-
1760
-	/**
1761
-	 * Get the MimeTypeDetector
1762
-	 *
1763
-	 * @return \OCP\Files\IMimeTypeDetector
1764
-	 */
1765
-	public function getMimeTypeDetector() {
1766
-		return $this->query('MimeTypeDetector');
1767
-	}
1768
-
1769
-	/**
1770
-	 * Get the MimeTypeLoader
1771
-	 *
1772
-	 * @return \OCP\Files\IMimeTypeLoader
1773
-	 */
1774
-	public function getMimeTypeLoader() {
1775
-		return $this->query('MimeTypeLoader');
1776
-	}
1777
-
1778
-	/**
1779
-	 * Get the manager of all the capabilities
1780
-	 *
1781
-	 * @return \OC\CapabilitiesManager
1782
-	 */
1783
-	public function getCapabilitiesManager() {
1784
-		return $this->query('CapabilitiesManager');
1785
-	}
1786
-
1787
-	/**
1788
-	 * Get the EventDispatcher
1789
-	 *
1790
-	 * @return EventDispatcherInterface
1791
-	 * @since 8.2.0
1792
-	 */
1793
-	public function getEventDispatcher() {
1794
-		return $this->query('EventDispatcher');
1795
-	}
1796
-
1797
-	/**
1798
-	 * Get the Notification Manager
1799
-	 *
1800
-	 * @return \OCP\Notification\IManager
1801
-	 * @since 8.2.0
1802
-	 */
1803
-	public function getNotificationManager() {
1804
-		return $this->query('NotificationManager');
1805
-	}
1806
-
1807
-	/**
1808
-	 * @return \OCP\Comments\ICommentsManager
1809
-	 */
1810
-	public function getCommentsManager() {
1811
-		return $this->query('CommentsManager');
1812
-	}
1813
-
1814
-	/**
1815
-	 * @return \OCA\Theming\ThemingDefaults
1816
-	 */
1817
-	public function getThemingDefaults() {
1818
-		return $this->query('ThemingDefaults');
1819
-	}
1820
-
1821
-	/**
1822
-	 * @return \OC\IntegrityCheck\Checker
1823
-	 */
1824
-	public function getIntegrityCodeChecker() {
1825
-		return $this->query('IntegrityCodeChecker');
1826
-	}
1827
-
1828
-	/**
1829
-	 * @return \OC\Session\CryptoWrapper
1830
-	 */
1831
-	public function getSessionCryptoWrapper() {
1832
-		return $this->query('CryptoWrapper');
1833
-	}
1834
-
1835
-	/**
1836
-	 * @return CsrfTokenManager
1837
-	 */
1838
-	public function getCsrfTokenManager() {
1839
-		return $this->query('CsrfTokenManager');
1840
-	}
1841
-
1842
-	/**
1843
-	 * @return Throttler
1844
-	 */
1845
-	public function getBruteForceThrottler() {
1846
-		return $this->query('Throttler');
1847
-	}
1848
-
1849
-	/**
1850
-	 * @return IContentSecurityPolicyManager
1851
-	 */
1852
-	public function getContentSecurityPolicyManager() {
1853
-		return $this->query('ContentSecurityPolicyManager');
1854
-	}
1855
-
1856
-	/**
1857
-	 * @return ContentSecurityPolicyNonceManager
1858
-	 */
1859
-	public function getContentSecurityPolicyNonceManager() {
1860
-		return $this->query('ContentSecurityPolicyNonceManager');
1861
-	}
1862
-
1863
-	/**
1864
-	 * Not a public API as of 8.2, wait for 9.0
1865
-	 *
1866
-	 * @return \OCA\Files_External\Service\BackendService
1867
-	 */
1868
-	public function getStoragesBackendService() {
1869
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1870
-	}
1871
-
1872
-	/**
1873
-	 * Not a public API as of 8.2, wait for 9.0
1874
-	 *
1875
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1876
-	 */
1877
-	public function getGlobalStoragesService() {
1878
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1879
-	}
1880
-
1881
-	/**
1882
-	 * Not a public API as of 8.2, wait for 9.0
1883
-	 *
1884
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1885
-	 */
1886
-	public function getUserGlobalStoragesService() {
1887
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1888
-	}
1889
-
1890
-	/**
1891
-	 * Not a public API as of 8.2, wait for 9.0
1892
-	 *
1893
-	 * @return \OCA\Files_External\Service\UserStoragesService
1894
-	 */
1895
-	public function getUserStoragesService() {
1896
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1897
-	}
1898
-
1899
-	/**
1900
-	 * @return \OCP\Share\IManager
1901
-	 */
1902
-	public function getShareManager() {
1903
-		return $this->query('ShareManager');
1904
-	}
1905
-
1906
-	/**
1907
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1908
-	 */
1909
-	public function getCollaboratorSearch() {
1910
-		return $this->query('CollaboratorSearch');
1911
-	}
1912
-
1913
-	/**
1914
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1915
-	 */
1916
-	public function getAutoCompleteManager(){
1917
-		return $this->query(IManager::class);
1918
-	}
1919
-
1920
-	/**
1921
-	 * Returns the LDAP Provider
1922
-	 *
1923
-	 * @return \OCP\LDAP\ILDAPProvider
1924
-	 */
1925
-	public function getLDAPProvider() {
1926
-		return $this->query('LDAPProvider');
1927
-	}
1928
-
1929
-	/**
1930
-	 * @return \OCP\Settings\IManager
1931
-	 */
1932
-	public function getSettingsManager() {
1933
-		return $this->query('SettingsManager');
1934
-	}
1935
-
1936
-	/**
1937
-	 * @return \OCP\Files\IAppData
1938
-	 */
1939
-	public function getAppDataDir($app) {
1940
-		/** @var \OC\Files\AppData\Factory $factory */
1941
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1942
-		return $factory->get($app);
1943
-	}
1944
-
1945
-	/**
1946
-	 * @return \OCP\Lockdown\ILockdownManager
1947
-	 */
1948
-	public function getLockdownManager() {
1949
-		return $this->query('LockdownManager');
1950
-	}
1951
-
1952
-	/**
1953
-	 * @return \OCP\Federation\ICloudIdManager
1954
-	 */
1955
-	public function getCloudIdManager() {
1956
-		return $this->query(ICloudIdManager::class);
1957
-	}
1958
-
1959
-	/**
1960
-	 * @return \OCP\Remote\Api\IApiFactory
1961
-	 */
1962
-	public function getRemoteApiFactory() {
1963
-		return $this->query(IApiFactory::class);
1964
-	}
1965
-
1966
-	/**
1967
-	 * @return \OCP\Remote\IInstanceFactory
1968
-	 */
1969
-	public function getRemoteInstanceFactory() {
1970
-		return $this->query(IInstanceFactory::class);
1971
-	}
927
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
928
+            if (isset($prefixes['OCA\\Theming\\'])) {
929
+                $classExists = true;
930
+            } else {
931
+                $classExists = false;
932
+            }
933
+
934
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
935
+                return new ThemingDefaults(
936
+                    $c->getConfig(),
937
+                    $c->getL10N('theming'),
938
+                    $c->getURLGenerator(),
939
+                    $c->getAppDataDir('theming'),
940
+                    $c->getMemCacheFactory(),
941
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
942
+                    $this->getAppManager()
943
+                );
944
+            }
945
+            return new \OC_Defaults();
946
+        });
947
+        $this->registerService(SCSSCacher::class, function (Server $c) {
948
+            /** @var Factory $cacheFactory */
949
+            $cacheFactory = $c->query(Factory::class);
950
+            return new SCSSCacher(
951
+                $c->getLogger(),
952
+                $c->query(\OC\Files\AppData\Factory::class),
953
+                $c->getURLGenerator(),
954
+                $c->getConfig(),
955
+                $c->getThemingDefaults(),
956
+                \OC::$SERVERROOT,
957
+                $cacheFactory->createDistributed('SCSS')
958
+            );
959
+        });
960
+        $this->registerService(EventDispatcher::class, function () {
961
+            return new EventDispatcher();
962
+        });
963
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
964
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
965
+
966
+        $this->registerService('CryptoWrapper', function (Server $c) {
967
+            // FIXME: Instantiiated here due to cyclic dependency
968
+            $request = new Request(
969
+                [
970
+                    'get' => $_GET,
971
+                    'post' => $_POST,
972
+                    'files' => $_FILES,
973
+                    'server' => $_SERVER,
974
+                    'env' => $_ENV,
975
+                    'cookies' => $_COOKIE,
976
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
977
+                        ? $_SERVER['REQUEST_METHOD']
978
+                        : null,
979
+                ],
980
+                $c->getSecureRandom(),
981
+                $c->getConfig()
982
+            );
983
+
984
+            return new CryptoWrapper(
985
+                $c->getConfig(),
986
+                $c->getCrypto(),
987
+                $c->getSecureRandom(),
988
+                $request
989
+            );
990
+        });
991
+        $this->registerService('CsrfTokenManager', function (Server $c) {
992
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
993
+
994
+            return new CsrfTokenManager(
995
+                $tokenGenerator,
996
+                $c->query(SessionStorage::class)
997
+            );
998
+        });
999
+        $this->registerService(SessionStorage::class, function (Server $c) {
1000
+            return new SessionStorage($c->getSession());
1001
+        });
1002
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1003
+            return new ContentSecurityPolicyManager();
1004
+        });
1005
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1006
+
1007
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1008
+            return new ContentSecurityPolicyNonceManager(
1009
+                $c->getCsrfTokenManager(),
1010
+                $c->getRequest()
1011
+            );
1012
+        });
1013
+
1014
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1015
+            $config = $c->getConfig();
1016
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1017
+            /** @var \OCP\Share\IProviderFactory $factory */
1018
+            $factory = new $factoryClass($this);
1019
+
1020
+            $manager = new \OC\Share20\Manager(
1021
+                $c->getLogger(),
1022
+                $c->getConfig(),
1023
+                $c->getSecureRandom(),
1024
+                $c->getHasher(),
1025
+                $c->getMountManager(),
1026
+                $c->getGroupManager(),
1027
+                $c->getL10N('lib'),
1028
+                $c->getL10NFactory(),
1029
+                $factory,
1030
+                $c->getUserManager(),
1031
+                $c->getLazyRootFolder(),
1032
+                $c->getEventDispatcher(),
1033
+                $c->getMailer(),
1034
+                $c->getURLGenerator(),
1035
+                $c->getThemingDefaults()
1036
+            );
1037
+
1038
+            return $manager;
1039
+        });
1040
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1041
+
1042
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1043
+            $instance = new Collaboration\Collaborators\Search($c);
1044
+
1045
+            // register default plugins
1046
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1047
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1048
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1049
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1050
+
1051
+            return $instance;
1052
+        });
1053
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1054
+
1055
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1056
+
1057
+        $this->registerService('SettingsManager', function (Server $c) {
1058
+            $manager = new \OC\Settings\Manager(
1059
+                $c->getLogger(),
1060
+                $c->getDatabaseConnection(),
1061
+                $c->getL10N('lib'),
1062
+                $c->getConfig(),
1063
+                $c->getEncryptionManager(),
1064
+                $c->getUserManager(),
1065
+                $c->getLockingProvider(),
1066
+                $c->getRequest(),
1067
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
1068
+                $c->getURLGenerator(),
1069
+                $c->query(AccountManager::class),
1070
+                $c->getGroupManager(),
1071
+                $c->getL10NFactory(),
1072
+                $c->getThemingDefaults(),
1073
+                $c->getAppManager()
1074
+            );
1075
+            return $manager;
1076
+        });
1077
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1078
+            return new \OC\Files\AppData\Factory(
1079
+                $c->getRootFolder(),
1080
+                $c->getSystemConfig()
1081
+            );
1082
+        });
1083
+
1084
+        $this->registerService('LockdownManager', function (Server $c) {
1085
+            return new LockdownManager(function () use ($c) {
1086
+                return $c->getSession();
1087
+            });
1088
+        });
1089
+
1090
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1091
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1092
+        });
1093
+
1094
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1095
+            return new CloudIdManager();
1096
+        });
1097
+
1098
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1099
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1100
+
1101
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1102
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1103
+
1104
+        $this->registerService(Defaults::class, function (Server $c) {
1105
+            return new Defaults(
1106
+                $c->getThemingDefaults()
1107
+            );
1108
+        });
1109
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1110
+
1111
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1112
+            return $c->query(\OCP\IUserSession::class)->getSession();
1113
+        });
1114
+
1115
+        $this->registerService(IShareHelper::class, function (Server $c) {
1116
+            return new ShareHelper(
1117
+                $c->query(\OCP\Share\IManager::class)
1118
+            );
1119
+        });
1120
+
1121
+        $this->registerService(Installer::class, function(Server $c) {
1122
+            return new Installer(
1123
+                $c->getAppFetcher(),
1124
+                $c->getHTTPClientService(),
1125
+                $c->getTempManager(),
1126
+                $c->getLogger(),
1127
+                $c->getConfig()
1128
+            );
1129
+        });
1130
+
1131
+        $this->registerService(IApiFactory::class, function(Server $c) {
1132
+            return new ApiFactory($c->getHTTPClientService());
1133
+        });
1134
+
1135
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1136
+            $memcacheFactory = $c->getMemCacheFactory();
1137
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1138
+        });
1139
+
1140
+        $this->registerService(IContactsStore::class, function(Server $c) {
1141
+            return new ContactsStore(
1142
+                $c->getContactsManager(),
1143
+                $c->getConfig(),
1144
+                $c->getUserManager(),
1145
+                $c->getGroupManager()
1146
+            );
1147
+        });
1148
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1149
+
1150
+        $this->connectDispatcher();
1151
+    }
1152
+
1153
+    /**
1154
+     * @return \OCP\Calendar\IManager
1155
+     */
1156
+    public function getCalendarManager() {
1157
+        return $this->query('CalendarManager');
1158
+    }
1159
+
1160
+    private function connectDispatcher() {
1161
+        $dispatcher = $this->getEventDispatcher();
1162
+
1163
+        // Delete avatar on user deletion
1164
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1165
+            $logger = $this->getLogger();
1166
+            $manager = $this->getAvatarManager();
1167
+            /** @var IUser $user */
1168
+            $user = $e->getSubject();
1169
+
1170
+            try {
1171
+                $avatar = $manager->getAvatar($user->getUID());
1172
+                $avatar->remove();
1173
+            } catch (NotFoundException $e) {
1174
+                // no avatar to remove
1175
+            } catch (\Exception $e) {
1176
+                // Ignore exceptions
1177
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1178
+            }
1179
+        });
1180
+
1181
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1182
+            $manager = $this->getAvatarManager();
1183
+            /** @var IUser $user */
1184
+            $user = $e->getSubject();
1185
+            $feature = $e->getArgument('feature');
1186
+            $oldValue = $e->getArgument('oldValue');
1187
+            $value = $e->getArgument('value');
1188
+
1189
+            try {
1190
+                $avatar = $manager->getAvatar($user->getUID());
1191
+                $avatar->userChanged($feature, $oldValue, $value);
1192
+            } catch (NotFoundException $e) {
1193
+                // no avatar to remove
1194
+            }
1195
+        });
1196
+    }
1197
+
1198
+    /**
1199
+     * @return \OCP\Contacts\IManager
1200
+     */
1201
+    public function getContactsManager() {
1202
+        return $this->query('ContactsManager');
1203
+    }
1204
+
1205
+    /**
1206
+     * @return \OC\Encryption\Manager
1207
+     */
1208
+    public function getEncryptionManager() {
1209
+        return $this->query('EncryptionManager');
1210
+    }
1211
+
1212
+    /**
1213
+     * @return \OC\Encryption\File
1214
+     */
1215
+    public function getEncryptionFilesHelper() {
1216
+        return $this->query('EncryptionFileHelper');
1217
+    }
1218
+
1219
+    /**
1220
+     * @return \OCP\Encryption\Keys\IStorage
1221
+     */
1222
+    public function getEncryptionKeyStorage() {
1223
+        return $this->query('EncryptionKeyStorage');
1224
+    }
1225
+
1226
+    /**
1227
+     * The current request object holding all information about the request
1228
+     * currently being processed is returned from this method.
1229
+     * In case the current execution was not initiated by a web request null is returned
1230
+     *
1231
+     * @return \OCP\IRequest
1232
+     */
1233
+    public function getRequest() {
1234
+        return $this->query('Request');
1235
+    }
1236
+
1237
+    /**
1238
+     * Returns the preview manager which can create preview images for a given file
1239
+     *
1240
+     * @return \OCP\IPreview
1241
+     */
1242
+    public function getPreviewManager() {
1243
+        return $this->query('PreviewManager');
1244
+    }
1245
+
1246
+    /**
1247
+     * Returns the tag manager which can get and set tags for different object types
1248
+     *
1249
+     * @see \OCP\ITagManager::load()
1250
+     * @return \OCP\ITagManager
1251
+     */
1252
+    public function getTagManager() {
1253
+        return $this->query('TagManager');
1254
+    }
1255
+
1256
+    /**
1257
+     * Returns the system-tag manager
1258
+     *
1259
+     * @return \OCP\SystemTag\ISystemTagManager
1260
+     *
1261
+     * @since 9.0.0
1262
+     */
1263
+    public function getSystemTagManager() {
1264
+        return $this->query('SystemTagManager');
1265
+    }
1266
+
1267
+    /**
1268
+     * Returns the system-tag object mapper
1269
+     *
1270
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1271
+     *
1272
+     * @since 9.0.0
1273
+     */
1274
+    public function getSystemTagObjectMapper() {
1275
+        return $this->query('SystemTagObjectMapper');
1276
+    }
1277
+
1278
+    /**
1279
+     * Returns the avatar manager, used for avatar functionality
1280
+     *
1281
+     * @return \OCP\IAvatarManager
1282
+     */
1283
+    public function getAvatarManager() {
1284
+        return $this->query('AvatarManager');
1285
+    }
1286
+
1287
+    /**
1288
+     * Returns the root folder of ownCloud's data directory
1289
+     *
1290
+     * @return \OCP\Files\IRootFolder
1291
+     */
1292
+    public function getRootFolder() {
1293
+        return $this->query('LazyRootFolder');
1294
+    }
1295
+
1296
+    /**
1297
+     * Returns the root folder of ownCloud's data directory
1298
+     * This is the lazy variant so this gets only initialized once it
1299
+     * is actually used.
1300
+     *
1301
+     * @return \OCP\Files\IRootFolder
1302
+     */
1303
+    public function getLazyRootFolder() {
1304
+        return $this->query('LazyRootFolder');
1305
+    }
1306
+
1307
+    /**
1308
+     * Returns a view to ownCloud's files folder
1309
+     *
1310
+     * @param string $userId user ID
1311
+     * @return \OCP\Files\Folder|null
1312
+     */
1313
+    public function getUserFolder($userId = null) {
1314
+        if ($userId === null) {
1315
+            $user = $this->getUserSession()->getUser();
1316
+            if (!$user) {
1317
+                return null;
1318
+            }
1319
+            $userId = $user->getUID();
1320
+        }
1321
+        $root = $this->getRootFolder();
1322
+        return $root->getUserFolder($userId);
1323
+    }
1324
+
1325
+    /**
1326
+     * Returns an app-specific view in ownClouds data directory
1327
+     *
1328
+     * @return \OCP\Files\Folder
1329
+     * @deprecated since 9.2.0 use IAppData
1330
+     */
1331
+    public function getAppFolder() {
1332
+        $dir = '/' . \OC_App::getCurrentApp();
1333
+        $root = $this->getRootFolder();
1334
+        if (!$root->nodeExists($dir)) {
1335
+            $folder = $root->newFolder($dir);
1336
+        } else {
1337
+            $folder = $root->get($dir);
1338
+        }
1339
+        return $folder;
1340
+    }
1341
+
1342
+    /**
1343
+     * @return \OC\User\Manager
1344
+     */
1345
+    public function getUserManager() {
1346
+        return $this->query('UserManager');
1347
+    }
1348
+
1349
+    /**
1350
+     * @return \OC\Group\Manager
1351
+     */
1352
+    public function getGroupManager() {
1353
+        return $this->query('GroupManager');
1354
+    }
1355
+
1356
+    /**
1357
+     * @return \OC\User\Session
1358
+     */
1359
+    public function getUserSession() {
1360
+        return $this->query('UserSession');
1361
+    }
1362
+
1363
+    /**
1364
+     * @return \OCP\ISession
1365
+     */
1366
+    public function getSession() {
1367
+        return $this->query('UserSession')->getSession();
1368
+    }
1369
+
1370
+    /**
1371
+     * @param \OCP\ISession $session
1372
+     */
1373
+    public function setSession(\OCP\ISession $session) {
1374
+        $this->query(SessionStorage::class)->setSession($session);
1375
+        $this->query('UserSession')->setSession($session);
1376
+        $this->query(Store::class)->setSession($session);
1377
+    }
1378
+
1379
+    /**
1380
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1381
+     */
1382
+    public function getTwoFactorAuthManager() {
1383
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1384
+    }
1385
+
1386
+    /**
1387
+     * @return \OC\NavigationManager
1388
+     */
1389
+    public function getNavigationManager() {
1390
+        return $this->query('NavigationManager');
1391
+    }
1392
+
1393
+    /**
1394
+     * @return \OCP\IConfig
1395
+     */
1396
+    public function getConfig() {
1397
+        return $this->query('AllConfig');
1398
+    }
1399
+
1400
+    /**
1401
+     * @return \OC\SystemConfig
1402
+     */
1403
+    public function getSystemConfig() {
1404
+        return $this->query('SystemConfig');
1405
+    }
1406
+
1407
+    /**
1408
+     * Returns the app config manager
1409
+     *
1410
+     * @return \OCP\IAppConfig
1411
+     */
1412
+    public function getAppConfig() {
1413
+        return $this->query('AppConfig');
1414
+    }
1415
+
1416
+    /**
1417
+     * @return \OCP\L10N\IFactory
1418
+     */
1419
+    public function getL10NFactory() {
1420
+        return $this->query('L10NFactory');
1421
+    }
1422
+
1423
+    /**
1424
+     * get an L10N instance
1425
+     *
1426
+     * @param string $app appid
1427
+     * @param string $lang
1428
+     * @return IL10N
1429
+     */
1430
+    public function getL10N($app, $lang = null) {
1431
+        return $this->getL10NFactory()->get($app, $lang);
1432
+    }
1433
+
1434
+    /**
1435
+     * @return \OCP\IURLGenerator
1436
+     */
1437
+    public function getURLGenerator() {
1438
+        return $this->query('URLGenerator');
1439
+    }
1440
+
1441
+    /**
1442
+     * @return \OCP\IHelper
1443
+     */
1444
+    public function getHelper() {
1445
+        return $this->query('AppHelper');
1446
+    }
1447
+
1448
+    /**
1449
+     * @return AppFetcher
1450
+     */
1451
+    public function getAppFetcher() {
1452
+        return $this->query(AppFetcher::class);
1453
+    }
1454
+
1455
+    /**
1456
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1457
+     * getMemCacheFactory() instead.
1458
+     *
1459
+     * @return \OCP\ICache
1460
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1461
+     */
1462
+    public function getCache() {
1463
+        return $this->query('UserCache');
1464
+    }
1465
+
1466
+    /**
1467
+     * Returns an \OCP\CacheFactory instance
1468
+     *
1469
+     * @return \OCP\ICacheFactory
1470
+     */
1471
+    public function getMemCacheFactory() {
1472
+        return $this->query('MemCacheFactory');
1473
+    }
1474
+
1475
+    /**
1476
+     * Returns an \OC\RedisFactory instance
1477
+     *
1478
+     * @return \OC\RedisFactory
1479
+     */
1480
+    public function getGetRedisFactory() {
1481
+        return $this->query('RedisFactory');
1482
+    }
1483
+
1484
+
1485
+    /**
1486
+     * Returns the current session
1487
+     *
1488
+     * @return \OCP\IDBConnection
1489
+     */
1490
+    public function getDatabaseConnection() {
1491
+        return $this->query('DatabaseConnection');
1492
+    }
1493
+
1494
+    /**
1495
+     * Returns the activity manager
1496
+     *
1497
+     * @return \OCP\Activity\IManager
1498
+     */
1499
+    public function getActivityManager() {
1500
+        return $this->query('ActivityManager');
1501
+    }
1502
+
1503
+    /**
1504
+     * Returns an job list for controlling background jobs
1505
+     *
1506
+     * @return \OCP\BackgroundJob\IJobList
1507
+     */
1508
+    public function getJobList() {
1509
+        return $this->query('JobList');
1510
+    }
1511
+
1512
+    /**
1513
+     * Returns a logger instance
1514
+     *
1515
+     * @return \OCP\ILogger
1516
+     */
1517
+    public function getLogger() {
1518
+        return $this->query('Logger');
1519
+    }
1520
+
1521
+    /**
1522
+     * Returns a router for generating and matching urls
1523
+     *
1524
+     * @return \OCP\Route\IRouter
1525
+     */
1526
+    public function getRouter() {
1527
+        return $this->query('Router');
1528
+    }
1529
+
1530
+    /**
1531
+     * Returns a search instance
1532
+     *
1533
+     * @return \OCP\ISearch
1534
+     */
1535
+    public function getSearch() {
1536
+        return $this->query('Search');
1537
+    }
1538
+
1539
+    /**
1540
+     * Returns a SecureRandom instance
1541
+     *
1542
+     * @return \OCP\Security\ISecureRandom
1543
+     */
1544
+    public function getSecureRandom() {
1545
+        return $this->query('SecureRandom');
1546
+    }
1547
+
1548
+    /**
1549
+     * Returns a Crypto instance
1550
+     *
1551
+     * @return \OCP\Security\ICrypto
1552
+     */
1553
+    public function getCrypto() {
1554
+        return $this->query('Crypto');
1555
+    }
1556
+
1557
+    /**
1558
+     * Returns a Hasher instance
1559
+     *
1560
+     * @return \OCP\Security\IHasher
1561
+     */
1562
+    public function getHasher() {
1563
+        return $this->query('Hasher');
1564
+    }
1565
+
1566
+    /**
1567
+     * Returns a CredentialsManager instance
1568
+     *
1569
+     * @return \OCP\Security\ICredentialsManager
1570
+     */
1571
+    public function getCredentialsManager() {
1572
+        return $this->query('CredentialsManager');
1573
+    }
1574
+
1575
+    /**
1576
+     * Returns an instance of the HTTP helper class
1577
+     *
1578
+     * @deprecated Use getHTTPClientService()
1579
+     * @return \OC\HTTPHelper
1580
+     */
1581
+    public function getHTTPHelper() {
1582
+        return $this->query('HTTPHelper');
1583
+    }
1584
+
1585
+    /**
1586
+     * Get the certificate manager for the user
1587
+     *
1588
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1589
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1590
+     */
1591
+    public function getCertificateManager($userId = '') {
1592
+        if ($userId === '') {
1593
+            $userSession = $this->getUserSession();
1594
+            $user = $userSession->getUser();
1595
+            if (is_null($user)) {
1596
+                return null;
1597
+            }
1598
+            $userId = $user->getUID();
1599
+        }
1600
+        return new CertificateManager(
1601
+            $userId,
1602
+            new View(),
1603
+            $this->getConfig(),
1604
+            $this->getLogger(),
1605
+            $this->getSecureRandom()
1606
+        );
1607
+    }
1608
+
1609
+    /**
1610
+     * Returns an instance of the HTTP client service
1611
+     *
1612
+     * @return \OCP\Http\Client\IClientService
1613
+     */
1614
+    public function getHTTPClientService() {
1615
+        return $this->query('HttpClientService');
1616
+    }
1617
+
1618
+    /**
1619
+     * Create a new event source
1620
+     *
1621
+     * @return \OCP\IEventSource
1622
+     */
1623
+    public function createEventSource() {
1624
+        return new \OC_EventSource();
1625
+    }
1626
+
1627
+    /**
1628
+     * Get the active event logger
1629
+     *
1630
+     * The returned logger only logs data when debug mode is enabled
1631
+     *
1632
+     * @return \OCP\Diagnostics\IEventLogger
1633
+     */
1634
+    public function getEventLogger() {
1635
+        return $this->query('EventLogger');
1636
+    }
1637
+
1638
+    /**
1639
+     * Get the active query logger
1640
+     *
1641
+     * The returned logger only logs data when debug mode is enabled
1642
+     *
1643
+     * @return \OCP\Diagnostics\IQueryLogger
1644
+     */
1645
+    public function getQueryLogger() {
1646
+        return $this->query('QueryLogger');
1647
+    }
1648
+
1649
+    /**
1650
+     * Get the manager for temporary files and folders
1651
+     *
1652
+     * @return \OCP\ITempManager
1653
+     */
1654
+    public function getTempManager() {
1655
+        return $this->query('TempManager');
1656
+    }
1657
+
1658
+    /**
1659
+     * Get the app manager
1660
+     *
1661
+     * @return \OCP\App\IAppManager
1662
+     */
1663
+    public function getAppManager() {
1664
+        return $this->query('AppManager');
1665
+    }
1666
+
1667
+    /**
1668
+     * Creates a new mailer
1669
+     *
1670
+     * @return \OCP\Mail\IMailer
1671
+     */
1672
+    public function getMailer() {
1673
+        return $this->query('Mailer');
1674
+    }
1675
+
1676
+    /**
1677
+     * Get the webroot
1678
+     *
1679
+     * @return string
1680
+     */
1681
+    public function getWebRoot() {
1682
+        return $this->webRoot;
1683
+    }
1684
+
1685
+    /**
1686
+     * @return \OC\OCSClient
1687
+     */
1688
+    public function getOcsClient() {
1689
+        return $this->query('OcsClient');
1690
+    }
1691
+
1692
+    /**
1693
+     * @return \OCP\IDateTimeZone
1694
+     */
1695
+    public function getDateTimeZone() {
1696
+        return $this->query('DateTimeZone');
1697
+    }
1698
+
1699
+    /**
1700
+     * @return \OCP\IDateTimeFormatter
1701
+     */
1702
+    public function getDateTimeFormatter() {
1703
+        return $this->query('DateTimeFormatter');
1704
+    }
1705
+
1706
+    /**
1707
+     * @return \OCP\Files\Config\IMountProviderCollection
1708
+     */
1709
+    public function getMountProviderCollection() {
1710
+        return $this->query('MountConfigManager');
1711
+    }
1712
+
1713
+    /**
1714
+     * Get the IniWrapper
1715
+     *
1716
+     * @return IniGetWrapper
1717
+     */
1718
+    public function getIniWrapper() {
1719
+        return $this->query('IniWrapper');
1720
+    }
1721
+
1722
+    /**
1723
+     * @return \OCP\Command\IBus
1724
+     */
1725
+    public function getCommandBus() {
1726
+        return $this->query('AsyncCommandBus');
1727
+    }
1728
+
1729
+    /**
1730
+     * Get the trusted domain helper
1731
+     *
1732
+     * @return TrustedDomainHelper
1733
+     */
1734
+    public function getTrustedDomainHelper() {
1735
+        return $this->query('TrustedDomainHelper');
1736
+    }
1737
+
1738
+    /**
1739
+     * Get the locking provider
1740
+     *
1741
+     * @return \OCP\Lock\ILockingProvider
1742
+     * @since 8.1.0
1743
+     */
1744
+    public function getLockingProvider() {
1745
+        return $this->query('LockingProvider');
1746
+    }
1747
+
1748
+    /**
1749
+     * @return \OCP\Files\Mount\IMountManager
1750
+     **/
1751
+    function getMountManager() {
1752
+        return $this->query('MountManager');
1753
+    }
1754
+
1755
+    /** @return \OCP\Files\Config\IUserMountCache */
1756
+    function getUserMountCache() {
1757
+        return $this->query('UserMountCache');
1758
+    }
1759
+
1760
+    /**
1761
+     * Get the MimeTypeDetector
1762
+     *
1763
+     * @return \OCP\Files\IMimeTypeDetector
1764
+     */
1765
+    public function getMimeTypeDetector() {
1766
+        return $this->query('MimeTypeDetector');
1767
+    }
1768
+
1769
+    /**
1770
+     * Get the MimeTypeLoader
1771
+     *
1772
+     * @return \OCP\Files\IMimeTypeLoader
1773
+     */
1774
+    public function getMimeTypeLoader() {
1775
+        return $this->query('MimeTypeLoader');
1776
+    }
1777
+
1778
+    /**
1779
+     * Get the manager of all the capabilities
1780
+     *
1781
+     * @return \OC\CapabilitiesManager
1782
+     */
1783
+    public function getCapabilitiesManager() {
1784
+        return $this->query('CapabilitiesManager');
1785
+    }
1786
+
1787
+    /**
1788
+     * Get the EventDispatcher
1789
+     *
1790
+     * @return EventDispatcherInterface
1791
+     * @since 8.2.0
1792
+     */
1793
+    public function getEventDispatcher() {
1794
+        return $this->query('EventDispatcher');
1795
+    }
1796
+
1797
+    /**
1798
+     * Get the Notification Manager
1799
+     *
1800
+     * @return \OCP\Notification\IManager
1801
+     * @since 8.2.0
1802
+     */
1803
+    public function getNotificationManager() {
1804
+        return $this->query('NotificationManager');
1805
+    }
1806
+
1807
+    /**
1808
+     * @return \OCP\Comments\ICommentsManager
1809
+     */
1810
+    public function getCommentsManager() {
1811
+        return $this->query('CommentsManager');
1812
+    }
1813
+
1814
+    /**
1815
+     * @return \OCA\Theming\ThemingDefaults
1816
+     */
1817
+    public function getThemingDefaults() {
1818
+        return $this->query('ThemingDefaults');
1819
+    }
1820
+
1821
+    /**
1822
+     * @return \OC\IntegrityCheck\Checker
1823
+     */
1824
+    public function getIntegrityCodeChecker() {
1825
+        return $this->query('IntegrityCodeChecker');
1826
+    }
1827
+
1828
+    /**
1829
+     * @return \OC\Session\CryptoWrapper
1830
+     */
1831
+    public function getSessionCryptoWrapper() {
1832
+        return $this->query('CryptoWrapper');
1833
+    }
1834
+
1835
+    /**
1836
+     * @return CsrfTokenManager
1837
+     */
1838
+    public function getCsrfTokenManager() {
1839
+        return $this->query('CsrfTokenManager');
1840
+    }
1841
+
1842
+    /**
1843
+     * @return Throttler
1844
+     */
1845
+    public function getBruteForceThrottler() {
1846
+        return $this->query('Throttler');
1847
+    }
1848
+
1849
+    /**
1850
+     * @return IContentSecurityPolicyManager
1851
+     */
1852
+    public function getContentSecurityPolicyManager() {
1853
+        return $this->query('ContentSecurityPolicyManager');
1854
+    }
1855
+
1856
+    /**
1857
+     * @return ContentSecurityPolicyNonceManager
1858
+     */
1859
+    public function getContentSecurityPolicyNonceManager() {
1860
+        return $this->query('ContentSecurityPolicyNonceManager');
1861
+    }
1862
+
1863
+    /**
1864
+     * Not a public API as of 8.2, wait for 9.0
1865
+     *
1866
+     * @return \OCA\Files_External\Service\BackendService
1867
+     */
1868
+    public function getStoragesBackendService() {
1869
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1870
+    }
1871
+
1872
+    /**
1873
+     * Not a public API as of 8.2, wait for 9.0
1874
+     *
1875
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1876
+     */
1877
+    public function getGlobalStoragesService() {
1878
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1879
+    }
1880
+
1881
+    /**
1882
+     * Not a public API as of 8.2, wait for 9.0
1883
+     *
1884
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1885
+     */
1886
+    public function getUserGlobalStoragesService() {
1887
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1888
+    }
1889
+
1890
+    /**
1891
+     * Not a public API as of 8.2, wait for 9.0
1892
+     *
1893
+     * @return \OCA\Files_External\Service\UserStoragesService
1894
+     */
1895
+    public function getUserStoragesService() {
1896
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1897
+    }
1898
+
1899
+    /**
1900
+     * @return \OCP\Share\IManager
1901
+     */
1902
+    public function getShareManager() {
1903
+        return $this->query('ShareManager');
1904
+    }
1905
+
1906
+    /**
1907
+     * @return \OCP\Collaboration\Collaborators\ISearch
1908
+     */
1909
+    public function getCollaboratorSearch() {
1910
+        return $this->query('CollaboratorSearch');
1911
+    }
1912
+
1913
+    /**
1914
+     * @return \OCP\Collaboration\AutoComplete\IManager
1915
+     */
1916
+    public function getAutoCompleteManager(){
1917
+        return $this->query(IManager::class);
1918
+    }
1919
+
1920
+    /**
1921
+     * Returns the LDAP Provider
1922
+     *
1923
+     * @return \OCP\LDAP\ILDAPProvider
1924
+     */
1925
+    public function getLDAPProvider() {
1926
+        return $this->query('LDAPProvider');
1927
+    }
1928
+
1929
+    /**
1930
+     * @return \OCP\Settings\IManager
1931
+     */
1932
+    public function getSettingsManager() {
1933
+        return $this->query('SettingsManager');
1934
+    }
1935
+
1936
+    /**
1937
+     * @return \OCP\Files\IAppData
1938
+     */
1939
+    public function getAppDataDir($app) {
1940
+        /** @var \OC\Files\AppData\Factory $factory */
1941
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1942
+        return $factory->get($app);
1943
+    }
1944
+
1945
+    /**
1946
+     * @return \OCP\Lockdown\ILockdownManager
1947
+     */
1948
+    public function getLockdownManager() {
1949
+        return $this->query('LockdownManager');
1950
+    }
1951
+
1952
+    /**
1953
+     * @return \OCP\Federation\ICloudIdManager
1954
+     */
1955
+    public function getCloudIdManager() {
1956
+        return $this->query(ICloudIdManager::class);
1957
+    }
1958
+
1959
+    /**
1960
+     * @return \OCP\Remote\Api\IApiFactory
1961
+     */
1962
+    public function getRemoteApiFactory() {
1963
+        return $this->query(IApiFactory::class);
1964
+    }
1965
+
1966
+    /**
1967
+     * @return \OCP\Remote\IInstanceFactory
1968
+     */
1969
+    public function getRemoteInstanceFactory() {
1970
+        return $this->query(IInstanceFactory::class);
1971
+    }
1972 1972
 }
Please login to merge, or discard this patch.
Spacing   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 		parent::__construct();
159 159
 		$this->webRoot = $webRoot;
160 160
 
161
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
161
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
162 162
 			return $c;
163 163
 		});
164 164
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
172 172
 
173 173
 
174
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
174
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
175 175
 			return new PreviewManager(
176 176
 				$c->getConfig(),
177 177
 				$c->getRootFolder(),
@@ -182,13 +182,13 @@  discard block
 block discarded – undo
182 182
 		});
183 183
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
184 184
 
185
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
185
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
186 186
 			return new \OC\Preview\Watcher(
187 187
 				$c->getAppDataDir('preview')
188 188
 			);
189 189
 		});
190 190
 
191
-		$this->registerService('EncryptionManager', function (Server $c) {
191
+		$this->registerService('EncryptionManager', function(Server $c) {
192 192
 			$view = new View();
193 193
 			$util = new Encryption\Util(
194 194
 				$view,
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 			);
207 207
 		});
208 208
 
209
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
209
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
210 210
 			$util = new Encryption\Util(
211 211
 				new View(),
212 212
 				$c->getUserManager(),
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 			);
221 221
 		});
222 222
 
223
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
223
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
224 224
 			$view = new View();
225 225
 			$util = new Encryption\Util(
226 226
 				$view,
@@ -231,32 +231,32 @@  discard block
 block discarded – undo
231 231
 
232 232
 			return new Encryption\Keys\Storage($view, $util);
233 233
 		});
234
-		$this->registerService('TagMapper', function (Server $c) {
234
+		$this->registerService('TagMapper', function(Server $c) {
235 235
 			return new TagMapper($c->getDatabaseConnection());
236 236
 		});
237 237
 
238
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
238
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
239 239
 			$tagMapper = $c->query('TagMapper');
240 240
 			return new TagManager($tagMapper, $c->getUserSession());
241 241
 		});
242 242
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
243 243
 
244
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
244
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
245 245
 			$config = $c->getConfig();
246 246
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
247 247
 			/** @var \OC\SystemTag\ManagerFactory $factory */
248 248
 			$factory = new $factoryClass($this);
249 249
 			return $factory;
250 250
 		});
251
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
251
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
252 252
 			return $c->query('SystemTagManagerFactory')->getManager();
253 253
 		});
254 254
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255 255
 
256
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
256
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
257 257
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
258 258
 		});
259
-		$this->registerService('RootFolder', function (Server $c) {
259
+		$this->registerService('RootFolder', function(Server $c) {
260 260
 			$manager = \OC\Files\Filesystem::getMountManager(null);
261 261
 			$view = new View();
262 262
 			$root = new Root(
@@ -277,38 +277,38 @@  discard block
 block discarded – undo
277 277
 		});
278 278
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279 279
 
280
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
-			return new LazyRoot(function () use ($c) {
280
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
281
+			return new LazyRoot(function() use ($c) {
282 282
 				return $c->query('RootFolder');
283 283
 			});
284 284
 		});
285 285
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286 286
 
287
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
287
+		$this->registerService(\OC\User\Manager::class, function(Server $c) {
288 288
 			$config = $c->getConfig();
289 289
 			return new \OC\User\Manager($config);
290 290
 		});
291 291
 		$this->registerAlias('UserManager', \OC\User\Manager::class);
292 292
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
293 293
 
294
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
294
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
295 295
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
296
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
297 297
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298 298
 			});
299
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
299
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
300 300
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301 301
 			});
302
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
302
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
303 303
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304 304
 			});
305
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
305
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
306 306
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307 307
 			});
308
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
309 309
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310 310
 			});
311
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
311
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
312 312
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313 313
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314 314
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 		});
318 318
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319 319
 
320
-		$this->registerService(Store::class, function (Server $c) {
320
+		$this->registerService(Store::class, function(Server $c) {
321 321
 			$session = $c->getSession();
322 322
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323 323
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -328,11 +328,11 @@  discard block
 block discarded – undo
328 328
 			return new Store($session, $logger, $tokenProvider);
329 329
 		});
330 330
 		$this->registerAlias(IStore::class, Store::class);
331
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
331
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
332 332
 			$dbConnection = $c->getDatabaseConnection();
333 333
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
334 334
 		});
335
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
335
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
336 336
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
337 337
 			$crypto = $c->getCrypto();
338 338
 			$config = $c->getConfig();
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 		});
343 343
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
344 344
 
345
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
345
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
346 346
 			$manager = $c->getUserManager();
347 347
 			$session = new \OC\Session\Memory('');
348 348
 			$timeFactory = new TimeFactory();
@@ -357,45 +357,45 @@  discard block
 block discarded – undo
357 357
 			$dispatcher = $c->getEventDispatcher();
358 358
 
359 359
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
360
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
360
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
361 361
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
362 362
 			});
363
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
363
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
364 364
 				/** @var $user \OC\User\User */
365 365
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
366 366
 			});
367
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
367
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
368 368
 				/** @var $user \OC\User\User */
369 369
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
370 370
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
371 371
 			});
372
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
372
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
373 373
 				/** @var $user \OC\User\User */
374 374
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
375 375
 			});
376
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
376
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
377 377
 				/** @var $user \OC\User\User */
378 378
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
379 379
 			});
380
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
380
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
381 381
 				/** @var $user \OC\User\User */
382 382
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
383 383
 			});
384
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
384
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
385 385
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
386 386
 			});
387
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
387
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
388 388
 				/** @var $user \OC\User\User */
389 389
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
390 390
 			});
391
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
391
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
392 392
 				/** @var $user \OC\User\User */
393 393
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
394 394
 			});
395
-			$userSession->listen('\OC\User', 'logout', function () {
395
+			$userSession->listen('\OC\User', 'logout', function() {
396 396
 				\OC_Hook::emit('OC_User', 'logout', array());
397 397
 			});
398
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
398
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
399 399
 				/** @var $user \OC\User\User */
400 400
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
401 401
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 		});
405 405
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
406 406
 
407
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
407
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
408 408
 			return new \OC\Authentication\TwoFactorAuth\Manager(
409 409
 				$c->getAppManager(),
410 410
 				$c->getSession(),
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
420 420
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
421 421
 
422
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
422
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
423 423
 			return new \OC\AllConfig(
424 424
 				$c->getSystemConfig()
425 425
 			);
@@ -427,17 +427,17 @@  discard block
 block discarded – undo
427 427
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
428 428
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
429 429
 
430
-		$this->registerService('SystemConfig', function ($c) use ($config) {
430
+		$this->registerService('SystemConfig', function($c) use ($config) {
431 431
 			return new \OC\SystemConfig($config);
432 432
 		});
433 433
 
434
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
434
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
435 435
 			return new \OC\AppConfig($c->getDatabaseConnection());
436 436
 		});
437 437
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
438 438
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
439 439
 
440
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
440
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
441 441
 			return new \OC\L10N\Factory(
442 442
 				$c->getConfig(),
443 443
 				$c->getRequest(),
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 		});
448 448
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
449 449
 
450
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
450
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
451 451
 			$config = $c->getConfig();
452 452
 			$cacheFactory = $c->getMemCacheFactory();
453 453
 			$request = $c->getRequest();
@@ -459,18 +459,18 @@  discard block
 block discarded – undo
459 459
 		});
460 460
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
461 461
 
462
-		$this->registerService('AppHelper', function ($c) {
462
+		$this->registerService('AppHelper', function($c) {
463 463
 			return new \OC\AppHelper();
464 464
 		});
465 465
 		$this->registerAlias('AppFetcher', AppFetcher::class);
466 466
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
467 467
 
468
-		$this->registerService(\OCP\ICache::class, function ($c) {
468
+		$this->registerService(\OCP\ICache::class, function($c) {
469 469
 			return new Cache\File();
470 470
 		});
471 471
 		$this->registerAlias('UserCache', \OCP\ICache::class);
472 472
 
473
-		$this->registerService(Factory::class, function (Server $c) {
473
+		$this->registerService(Factory::class, function(Server $c) {
474 474
 
475 475
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
476 476
 				'\\OC\\Memcache\\ArrayCache',
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
 				$version = implode(',', $v);
488 488
 				$instanceId = \OC_Util::getInstanceId();
489 489
 				$path = \OC::$SERVERROOT;
490
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
490
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
491 491
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
492 492
 					$config->getSystemValue('memcache.local', null),
493 493
 					$config->getSystemValue('memcache.distributed', null),
@@ -500,12 +500,12 @@  discard block
 block discarded – undo
500 500
 		$this->registerAlias('MemCacheFactory', Factory::class);
501 501
 		$this->registerAlias(ICacheFactory::class, Factory::class);
502 502
 
503
-		$this->registerService('RedisFactory', function (Server $c) {
503
+		$this->registerService('RedisFactory', function(Server $c) {
504 504
 			$systemConfig = $c->getSystemConfig();
505 505
 			return new RedisFactory($systemConfig);
506 506
 		});
507 507
 
508
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
508
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
509 509
 			return new \OC\Activity\Manager(
510 510
 				$c->getRequest(),
511 511
 				$c->getUserSession(),
@@ -515,14 +515,14 @@  discard block
 block discarded – undo
515 515
 		});
516 516
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
517 517
 
518
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
518
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
519 519
 			return new \OC\Activity\EventMerger(
520 520
 				$c->getL10N('lib')
521 521
 			);
522 522
 		});
523 523
 		$this->registerAlias(IValidator::class, Validator::class);
524 524
 
525
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
525
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
526 526
 			return new AvatarManager(
527 527
 				$c->query(\OC\User\Manager::class),
528 528
 				$c->getAppDataDir('avatar'),
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 
536 536
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
537 537
 
538
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
538
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
539 539
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
540 540
 			$logger = Log::getLogClass($logType);
541 541
 			call_user_func(array($logger, 'init'));
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 		});
547 547
 		$this->registerAlias('Logger', \OCP\ILogger::class);
548 548
 
549
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
549
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
550 550
 			$config = $c->getConfig();
551 551
 			return new \OC\BackgroundJob\JobList(
552 552
 				$c->getDatabaseConnection(),
@@ -556,7 +556,7 @@  discard block
 block discarded – undo
556 556
 		});
557 557
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
558 558
 
559
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
559
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
560 560
 			$cacheFactory = $c->getMemCacheFactory();
561 561
 			$logger = $c->getLogger();
562 562
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -568,12 +568,12 @@  discard block
 block discarded – undo
568 568
 		});
569 569
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
570 570
 
571
-		$this->registerService(\OCP\ISearch::class, function ($c) {
571
+		$this->registerService(\OCP\ISearch::class, function($c) {
572 572
 			return new Search();
573 573
 		});
574 574
 		$this->registerAlias('Search', \OCP\ISearch::class);
575 575
 
576
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
576
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
577 577
 			return new \OC\Security\RateLimiting\Limiter(
578 578
 				$this->getUserSession(),
579 579
 				$this->getRequest(),
@@ -581,34 +581,34 @@  discard block
 block discarded – undo
581 581
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
582 582
 			);
583 583
 		});
584
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
584
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
585 585
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
586 586
 				$this->getMemCacheFactory(),
587 587
 				new \OC\AppFramework\Utility\TimeFactory()
588 588
 			);
589 589
 		});
590 590
 
591
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
591
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
592 592
 			return new SecureRandom();
593 593
 		});
594 594
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
595 595
 
596
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
596
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
597 597
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
598 598
 		});
599 599
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
600 600
 
601
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
601
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
602 602
 			return new Hasher($c->getConfig());
603 603
 		});
604 604
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
605 605
 
606
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
606
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
607 607
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
608 608
 		});
609 609
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
610 610
 
611
-		$this->registerService(IDBConnection::class, function (Server $c) {
611
+		$this->registerService(IDBConnection::class, function(Server $c) {
612 612
 			$systemConfig = $c->getSystemConfig();
613 613
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
614 614
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
 		});
623 623
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
624 624
 
625
-		$this->registerService('HTTPHelper', function (Server $c) {
625
+		$this->registerService('HTTPHelper', function(Server $c) {
626 626
 			$config = $c->getConfig();
627 627
 			return new HTTPHelper(
628 628
 				$config,
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 			);
631 631
 		});
632 632
 
633
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
633
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
634 634
 			$user = \OC_User::getUser();
635 635
 			$uid = $user ? $user : null;
636 636
 			return new ClientService(
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
 			);
646 646
 		});
647 647
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
648
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
648
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
649 649
 			$eventLogger = new EventLogger();
650 650
 			if ($c->getSystemConfig()->getValue('debug', false)) {
651 651
 				// In debug mode, module is being activated by default
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
 		});
656 656
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
657 657
 
658
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
658
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
659 659
 			$queryLogger = new QueryLogger();
660 660
 			if ($c->getSystemConfig()->getValue('debug', false)) {
661 661
 				// In debug mode, module is being activated by default
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
 		});
666 666
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
667 667
 
668
-		$this->registerService(TempManager::class, function (Server $c) {
668
+		$this->registerService(TempManager::class, function(Server $c) {
669 669
 			return new TempManager(
670 670
 				$c->getLogger(),
671 671
 				$c->getConfig()
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
 		$this->registerAlias('TempManager', TempManager::class);
675 675
 		$this->registerAlias(ITempManager::class, TempManager::class);
676 676
 
677
-		$this->registerService(AppManager::class, function (Server $c) {
677
+		$this->registerService(AppManager::class, function(Server $c) {
678 678
 			return new \OC\App\AppManager(
679 679
 				$c->getUserSession(),
680 680
 				$c->query(\OC\AppConfig::class),
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
 		$this->registerAlias('AppManager', AppManager::class);
687 687
 		$this->registerAlias(IAppManager::class, AppManager::class);
688 688
 
689
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
689
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
690 690
 			return new DateTimeZone(
691 691
 				$c->getConfig(),
692 692
 				$c->getSession()
@@ -694,7 +694,7 @@  discard block
 block discarded – undo
694 694
 		});
695 695
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
696 696
 
697
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
697
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
698 698
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
699 699
 
700 700
 			return new DateTimeFormatter(
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
 		});
705 705
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
706 706
 
707
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
707
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
708 708
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
709 709
 			$listener = new UserMountCacheListener($mountCache);
710 710
 			$listener->listen($c->getUserManager());
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
 		});
713 713
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
714 714
 
715
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
715
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
716 716
 			$loader = \OC\Files\Filesystem::getLoader();
717 717
 			$mountCache = $c->query('UserMountCache');
718 718
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -728,10 +728,10 @@  discard block
 block discarded – undo
728 728
 		});
729 729
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
730 730
 
731
-		$this->registerService('IniWrapper', function ($c) {
731
+		$this->registerService('IniWrapper', function($c) {
732 732
 			return new IniGetWrapper();
733 733
 		});
734
-		$this->registerService('AsyncCommandBus', function (Server $c) {
734
+		$this->registerService('AsyncCommandBus', function(Server $c) {
735 735
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
736 736
 			if ($busClass) {
737 737
 				list($app, $class) = explode('::', $busClass, 2);
@@ -746,10 +746,10 @@  discard block
 block discarded – undo
746 746
 				return new CronBus($jobList);
747 747
 			}
748 748
 		});
749
-		$this->registerService('TrustedDomainHelper', function ($c) {
749
+		$this->registerService('TrustedDomainHelper', function($c) {
750 750
 			return new TrustedDomainHelper($this->getConfig());
751 751
 		});
752
-		$this->registerService('Throttler', function (Server $c) {
752
+		$this->registerService('Throttler', function(Server $c) {
753 753
 			return new Throttler(
754 754
 				$c->getDatabaseConnection(),
755 755
 				new TimeFactory(),
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 				$c->getConfig()
758 758
 			);
759 759
 		});
760
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
760
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
761 761
 			// IConfig and IAppManager requires a working database. This code
762 762
 			// might however be called when ownCloud is not yet setup.
763 763
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 				$c->getTempManager()
779 779
 			);
780 780
 		});
781
-		$this->registerService(\OCP\IRequest::class, function ($c) {
781
+		$this->registerService(\OCP\IRequest::class, function($c) {
782 782
 			if (isset($this['urlParams'])) {
783 783
 				$urlParams = $this['urlParams'];
784 784
 			} else {
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
 		});
815 815
 		$this->registerAlias('Request', \OCP\IRequest::class);
816 816
 
817
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
817
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
818 818
 			return new Mailer(
819 819
 				$c->getConfig(),
820 820
 				$c->getLogger(),
@@ -825,7 +825,7 @@  discard block
 block discarded – undo
825 825
 		});
826 826
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
827 827
 
828
-		$this->registerService('LDAPProvider', function (Server $c) {
828
+		$this->registerService('LDAPProvider', function(Server $c) {
829 829
 			$config = $c->getConfig();
830 830
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
831 831
 			if (is_null($factoryClass)) {
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 			$factory = new $factoryClass($this);
836 836
 			return $factory->getLDAPProvider();
837 837
 		});
838
-		$this->registerService(ILockingProvider::class, function (Server $c) {
838
+		$this->registerService(ILockingProvider::class, function(Server $c) {
839 839
 			$ini = $c->getIniWrapper();
840 840
 			$config = $c->getConfig();
841 841
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -852,49 +852,49 @@  discard block
 block discarded – undo
852 852
 		});
853 853
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
854 854
 
855
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
855
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
856 856
 			return new \OC\Files\Mount\Manager();
857 857
 		});
858 858
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
859 859
 
860
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
860
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
861 861
 			return new \OC\Files\Type\Detection(
862 862
 				$c->getURLGenerator(),
863 863
 				\OC::$configDir,
864
-				\OC::$SERVERROOT . '/resources/config/'
864
+				\OC::$SERVERROOT.'/resources/config/'
865 865
 			);
866 866
 		});
867 867
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
868 868
 
869
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
869
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
870 870
 			return new \OC\Files\Type\Loader(
871 871
 				$c->getDatabaseConnection()
872 872
 			);
873 873
 		});
874 874
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
875
-		$this->registerService(BundleFetcher::class, function () {
875
+		$this->registerService(BundleFetcher::class, function() {
876 876
 			return new BundleFetcher($this->getL10N('lib'));
877 877
 		});
878
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
878
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
879 879
 			return new Manager(
880 880
 				$c->query(IValidator::class)
881 881
 			);
882 882
 		});
883 883
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
884 884
 
885
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
885
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
886 886
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
887
-			$manager->registerCapability(function () use ($c) {
887
+			$manager->registerCapability(function() use ($c) {
888 888
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
889 889
 			});
890
-			$manager->registerCapability(function () use ($c) {
890
+			$manager->registerCapability(function() use ($c) {
891 891
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
892 892
 			});
893 893
 			return $manager;
894 894
 		});
895 895
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
896 896
 
897
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
897
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
898 898
 			$config = $c->getConfig();
899 899
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
900 900
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
905 905
 				$manager = $c->getUserManager();
906 906
 				$user = $manager->get($id);
907
-				if(is_null($user)) {
907
+				if (is_null($user)) {
908 908
 					$l = $c->getL10N('core');
909 909
 					$displayName = $l->t('Unknown user');
910 910
 				} else {
@@ -917,7 +917,7 @@  discard block
 block discarded – undo
917 917
 		});
918 918
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
919 919
 
920
-		$this->registerService('ThemingDefaults', function (Server $c) {
920
+		$this->registerService('ThemingDefaults', function(Server $c) {
921 921
 			/*
922 922
 			 * Dark magic for autoloader.
923 923
 			 * If we do a class_exists it will try to load the class which will
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
 			}
945 945
 			return new \OC_Defaults();
946 946
 		});
947
-		$this->registerService(SCSSCacher::class, function (Server $c) {
947
+		$this->registerService(SCSSCacher::class, function(Server $c) {
948 948
 			/** @var Factory $cacheFactory */
949 949
 			$cacheFactory = $c->query(Factory::class);
950 950
 			return new SCSSCacher(
@@ -957,13 +957,13 @@  discard block
 block discarded – undo
957 957
 				$cacheFactory->createDistributed('SCSS')
958 958
 			);
959 959
 		});
960
-		$this->registerService(EventDispatcher::class, function () {
960
+		$this->registerService(EventDispatcher::class, function() {
961 961
 			return new EventDispatcher();
962 962
 		});
963 963
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
964 964
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
965 965
 
966
-		$this->registerService('CryptoWrapper', function (Server $c) {
966
+		$this->registerService('CryptoWrapper', function(Server $c) {
967 967
 			// FIXME: Instantiiated here due to cyclic dependency
968 968
 			$request = new Request(
969 969
 				[
@@ -988,7 +988,7 @@  discard block
 block discarded – undo
988 988
 				$request
989 989
 			);
990 990
 		});
991
-		$this->registerService('CsrfTokenManager', function (Server $c) {
991
+		$this->registerService('CsrfTokenManager', function(Server $c) {
992 992
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
993 993
 
994 994
 			return new CsrfTokenManager(
@@ -996,22 +996,22 @@  discard block
 block discarded – undo
996 996
 				$c->query(SessionStorage::class)
997 997
 			);
998 998
 		});
999
-		$this->registerService(SessionStorage::class, function (Server $c) {
999
+		$this->registerService(SessionStorage::class, function(Server $c) {
1000 1000
 			return new SessionStorage($c->getSession());
1001 1001
 		});
1002
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1002
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1003 1003
 			return new ContentSecurityPolicyManager();
1004 1004
 		});
1005 1005
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1006 1006
 
1007
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1007
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1008 1008
 			return new ContentSecurityPolicyNonceManager(
1009 1009
 				$c->getCsrfTokenManager(),
1010 1010
 				$c->getRequest()
1011 1011
 			);
1012 1012
 		});
1013 1013
 
1014
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1014
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1015 1015
 			$config = $c->getConfig();
1016 1016
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1017 1017
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1054,7 +1054,7 @@  discard block
 block discarded – undo
1054 1054
 
1055 1055
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1056 1056
 
1057
-		$this->registerService('SettingsManager', function (Server $c) {
1057
+		$this->registerService('SettingsManager', function(Server $c) {
1058 1058
 			$manager = new \OC\Settings\Manager(
1059 1059
 				$c->getLogger(),
1060 1060
 				$c->getDatabaseConnection(),
@@ -1074,24 +1074,24 @@  discard block
 block discarded – undo
1074 1074
 			);
1075 1075
 			return $manager;
1076 1076
 		});
1077
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1077
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1078 1078
 			return new \OC\Files\AppData\Factory(
1079 1079
 				$c->getRootFolder(),
1080 1080
 				$c->getSystemConfig()
1081 1081
 			);
1082 1082
 		});
1083 1083
 
1084
-		$this->registerService('LockdownManager', function (Server $c) {
1085
-			return new LockdownManager(function () use ($c) {
1084
+		$this->registerService('LockdownManager', function(Server $c) {
1085
+			return new LockdownManager(function() use ($c) {
1086 1086
 				return $c->getSession();
1087 1087
 			});
1088 1088
 		});
1089 1089
 
1090
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1090
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1091 1091
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1092 1092
 		});
1093 1093
 
1094
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1094
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1095 1095
 			return new CloudIdManager();
1096 1096
 		});
1097 1097
 
@@ -1101,18 +1101,18 @@  discard block
 block discarded – undo
1101 1101
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1102 1102
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1103 1103
 
1104
-		$this->registerService(Defaults::class, function (Server $c) {
1104
+		$this->registerService(Defaults::class, function(Server $c) {
1105 1105
 			return new Defaults(
1106 1106
 				$c->getThemingDefaults()
1107 1107
 			);
1108 1108
 		});
1109 1109
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1110 1110
 
1111
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1111
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1112 1112
 			return $c->query(\OCP\IUserSession::class)->getSession();
1113 1113
 		});
1114 1114
 
1115
-		$this->registerService(IShareHelper::class, function (Server $c) {
1115
+		$this->registerService(IShareHelper::class, function(Server $c) {
1116 1116
 			return new ShareHelper(
1117 1117
 				$c->query(\OCP\Share\IManager::class)
1118 1118
 			);
@@ -1174,11 +1174,11 @@  discard block
 block discarded – undo
1174 1174
 				// no avatar to remove
1175 1175
 			} catch (\Exception $e) {
1176 1176
 				// Ignore exceptions
1177
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1177
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1178 1178
 			}
1179 1179
 		});
1180 1180
 
1181
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1181
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1182 1182
 			$manager = $this->getAvatarManager();
1183 1183
 			/** @var IUser $user */
1184 1184
 			$user = $e->getSubject();
@@ -1329,7 +1329,7 @@  discard block
 block discarded – undo
1329 1329
 	 * @deprecated since 9.2.0 use IAppData
1330 1330
 	 */
1331 1331
 	public function getAppFolder() {
1332
-		$dir = '/' . \OC_App::getCurrentApp();
1332
+		$dir = '/'.\OC_App::getCurrentApp();
1333 1333
 		$root = $this->getRootFolder();
1334 1334
 		if (!$root->nodeExists($dir)) {
1335 1335
 			$folder = $root->newFolder($dir);
@@ -1913,7 +1913,7 @@  discard block
 block discarded – undo
1913 1913
 	/**
1914 1914
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1915 1915
 	 */
1916
-	public function getAutoCompleteManager(){
1916
+	public function getAutoCompleteManager() {
1917 1917
 		return $this->query(IManager::class);
1918 1918
 	}
1919 1919
 
Please login to merge, or discard this patch.
lib/private/Share/Share.php 1 patch
Indentation   +2180 added lines, -2180 removed lines patch added patch discarded remove patch
@@ -57,2194 +57,2194 @@
 block discarded – undo
57 57
  */
58 58
 class Share extends Constants {
59 59
 
60
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
61
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
62
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
63
-	 *
64
-	 * Check if permission is granted with And (&) e.g. Check if delete is
65
-	 * granted: if ($permissions & PERMISSION_DELETE)
66
-	 *
67
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
68
-	 * permission: $permissions &= ~PERMISSION_UPDATE
69
-	 *
70
-	 * Apps are required to handle permissions on their own, this class only
71
-	 * stores and manages the permissions of shares
72
-	 * @see lib/public/constants.php
73
-	 */
74
-
75
-	/**
76
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
77
-	 * @param string $itemType Item type
78
-	 * @param string $class Backend class
79
-	 * @param string $collectionOf (optional) Depends on item type
80
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
81
-	 * @return boolean true if backend is registered or false if error
82
-	 */
83
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
84
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
85
-			if (!isset(self::$backendTypes[$itemType])) {
86
-				self::$backendTypes[$itemType] = array(
87
-					'class' => $class,
88
-					'collectionOf' => $collectionOf,
89
-					'supportedFileExtensions' => $supportedFileExtensions
90
-				);
91
-				if(count(self::$backendTypes) === 1) {
92
-					Util::addScript('core', 'merged-share-backend');
93
-					\OC_Util::addStyle('core', 'share');
94
-				}
95
-				return true;
96
-			}
97
-			\OCP\Util::writeLog('OCP\Share',
98
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
99
-				.' is already registered for '.$itemType,
100
-				\OCP\Util::WARN);
101
-		}
102
-		return false;
103
-	}
104
-
105
-	/**
106
-	 * Get the items of item type shared with the current user
107
-	 * @param string $itemType
108
-	 * @param int $format (optional) Format type must be defined by the backend
109
-	 * @param mixed $parameters (optional)
110
-	 * @param int $limit Number of items to return (optional) Returns all by default
111
-	 * @param boolean $includeCollections (optional)
112
-	 * @return mixed Return depends on format
113
-	 */
114
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
115
-											  $parameters = null, $limit = -1, $includeCollections = false) {
116
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
117
-			$parameters, $limit, $includeCollections);
118
-	}
119
-
120
-	/**
121
-	 * Get the items of item type shared with a user
122
-	 * @param string $itemType
123
-	 * @param string $user id for which user we want the shares
124
-	 * @param int $format (optional) Format type must be defined by the backend
125
-	 * @param mixed $parameters (optional)
126
-	 * @param int $limit Number of items to return (optional) Returns all by default
127
-	 * @param boolean $includeCollections (optional)
128
-	 * @return mixed Return depends on format
129
-	 */
130
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
131
-												  $parameters = null, $limit = -1, $includeCollections = false) {
132
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
133
-			$parameters, $limit, $includeCollections);
134
-	}
135
-
136
-	/**
137
-	 * Get the item of item type shared with a given user by source
138
-	 * @param string $itemType
139
-	 * @param string $itemSource
140
-	 * @param string $user User to whom the item was shared
141
-	 * @param string $owner Owner of the share
142
-	 * @param int $shareType only look for a specific share type
143
-	 * @return array Return list of items with file_target, permissions and expiration
144
-	 */
145
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
146
-		$shares = array();
147
-		$fileDependent = false;
148
-
149
-		$where = 'WHERE';
150
-		$fileDependentWhere = '';
151
-		if ($itemType === 'file' || $itemType === 'folder') {
152
-			$fileDependent = true;
153
-			$column = 'file_source';
154
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
155
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
156
-		} else {
157
-			$column = 'item_source';
158
-		}
159
-
160
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
161
-
162
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
163
-		$arguments = array($itemSource, $itemType);
164
-		// for link shares $user === null
165
-		if ($user !== null) {
166
-			$where .= ' AND `share_with` = ? ';
167
-			$arguments[] = $user;
168
-		}
169
-
170
-		if ($shareType !== null) {
171
-			$where .= ' AND `share_type` = ? ';
172
-			$arguments[] = $shareType;
173
-		}
174
-
175
-		if ($owner !== null) {
176
-			$where .= ' AND `uid_owner` = ? ';
177
-			$arguments[] = $owner;
178
-		}
179
-
180
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
181
-
182
-		$result = \OC_DB::executeAudited($query, $arguments);
183
-
184
-		while ($row = $result->fetchRow()) {
185
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
186
-				continue;
187
-			}
188
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
189
-				// if it is a mount point we need to get the path from the mount manager
190
-				$mountManager = \OC\Files\Filesystem::getMountManager();
191
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
192
-				if (!empty($mountPoint)) {
193
-					$path = $mountPoint[0]->getMountPoint();
194
-					$path = trim($path, '/');
195
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
196
-					$row['path'] = $path;
197
-				} else {
198
-					\OC::$server->getLogger()->warning(
199
-						'Could not resolve mount point for ' . $row['storage_id'],
200
-						['app' => 'OCP\Share']
201
-					);
202
-				}
203
-			}
204
-			$shares[] = $row;
205
-		}
206
-
207
-		//if didn't found a result than let's look for a group share.
208
-		if(empty($shares) && $user !== null) {
209
-			$userObject = \OC::$server->getUserManager()->get($user);
210
-			$groups = [];
211
-			if ($userObject) {
212
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
213
-			}
214
-
215
-			if (!empty($groups)) {
216
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
217
-				$arguments = array($itemSource, $itemType, $groups);
218
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
219
-
220
-				if ($owner !== null) {
221
-					$where .= ' AND `uid_owner` = ?';
222
-					$arguments[] = $owner;
223
-					$types[] = null;
224
-				}
225
-
226
-				// TODO: inject connection, hopefully one day in the future when this
227
-				// class isn't static anymore...
228
-				$conn = \OC::$server->getDatabaseConnection();
229
-				$result = $conn->executeQuery(
230
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
231
-					$arguments,
232
-					$types
233
-				);
234
-
235
-				while ($row = $result->fetch()) {
236
-					$shares[] = $row;
237
-				}
238
-			}
239
-		}
240
-
241
-		return $shares;
242
-
243
-	}
244
-
245
-	/**
246
-	 * Get the item of item type shared with the current user by source
247
-	 * @param string $itemType
248
-	 * @param string $itemSource
249
-	 * @param int $format (optional) Format type must be defined by the backend
250
-	 * @param mixed $parameters
251
-	 * @param boolean $includeCollections
252
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
253
-	 * @return array
254
-	 */
255
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
256
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
257
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
258
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
259
-			$parameters, 1, $includeCollections, true);
260
-	}
261
-
262
-	/**
263
-	 * Based on the given token the share information will be returned - password protected shares will be verified
264
-	 * @param string $token
265
-	 * @param bool $checkPasswordProtection
266
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
267
-	 */
268
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
269
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
270
-		$result = $query->execute(array($token));
271
-		if ($result === false) {
272
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
273
-		}
274
-		$row = $result->fetchRow();
275
-		if ($row === false) {
276
-			return false;
277
-		}
278
-		if (is_array($row) and self::expireItem($row)) {
279
-			return false;
280
-		}
281
-
282
-		// password protected shares need to be authenticated
283
-		if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
284
-			return false;
285
-		}
286
-
287
-		return $row;
288
-	}
289
-
290
-	/**
291
-	 * resolves reshares down to the last real share
292
-	 * @param array $linkItem
293
-	 * @return array file owner
294
-	 */
295
-	public static function resolveReShare($linkItem)
296
-	{
297
-		if (isset($linkItem['parent'])) {
298
-			$parent = $linkItem['parent'];
299
-			while (isset($parent)) {
300
-				$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
301
-				$item = $query->execute(array($parent))->fetchRow();
302
-				if (isset($item['parent'])) {
303
-					$parent = $item['parent'];
304
-				} else {
305
-					return $item;
306
-				}
307
-			}
308
-		}
309
-		return $linkItem;
310
-	}
311
-
312
-
313
-	/**
314
-	 * Get the shared items of item type owned by the current user
315
-	 * @param string $itemType
316
-	 * @param int $format (optional) Format type must be defined by the backend
317
-	 * @param mixed $parameters
318
-	 * @param int $limit Number of items to return (optional) Returns all by default
319
-	 * @param boolean $includeCollections
320
-	 * @return mixed Return depends on format
321
-	 */
322
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
323
-										  $limit = -1, $includeCollections = false) {
324
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
325
-			$parameters, $limit, $includeCollections);
326
-	}
327
-
328
-	/**
329
-	 * Get the shared item of item type owned by the current user
330
-	 * @param string $itemType
331
-	 * @param string $itemSource
332
-	 * @param int $format (optional) Format type must be defined by the backend
333
-	 * @param mixed $parameters
334
-	 * @param boolean $includeCollections
335
-	 * @return mixed Return depends on format
336
-	 */
337
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
338
-										 $parameters = null, $includeCollections = false) {
339
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
340
-			$parameters, -1, $includeCollections);
341
-	}
342
-
343
-	/**
344
-	 * Share an item with a user, group, or via private link
345
-	 * @param string $itemType
346
-	 * @param string $itemSource
347
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
348
-	 * @param string $shareWith User or group the item is being shared with
349
-	 * @param int $permissions CRUDS
350
-	 * @param string $itemSourceName
351
-	 * @param \DateTime|null $expirationDate
352
-	 * @param bool|null $passwordChanged
353
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
354
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
355
-	 * @throws \Exception
356
-	 * @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
357
-	 */
358
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
359
-
360
-		$backend = self::getBackend($itemType);
361
-		$l = \OC::$server->getL10N('lib');
362
-
363
-		if ($backend->isShareTypeAllowed($shareType) === false) {
364
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
365
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
366
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
367
-			throw new \Exception($message_t);
368
-		}
369
-
370
-		$uidOwner = \OC_User::getUser();
371
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
372
-
373
-		if (is_null($itemSourceName)) {
374
-			$itemSourceName = $itemSource;
375
-		}
376
-		$itemName = $itemSourceName;
377
-
378
-		// check if file can be shared
379
-		if ($itemType === 'file' or $itemType === 'folder') {
380
-			$path = \OC\Files\Filesystem::getPath($itemSource);
381
-			$itemName = $path;
382
-
383
-			// verify that the file exists before we try to share it
384
-			if (!$path) {
385
-				$message = 'Sharing %s failed, because the file does not exist';
386
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
387
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
388
-				throw new \Exception($message_t);
389
-			}
390
-			// verify that the user has share permission
391
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
392
-				$message = 'You are not allowed to share %s';
393
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
394
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
395
-				throw new \Exception($message_t);
396
-			}
397
-		}
398
-
399
-		//verify that we don't share a folder which already contains a share mount point
400
-		if ($itemType === 'folder') {
401
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
402
-			$mountManager = \OC\Files\Filesystem::getMountManager();
403
-			$mounts = $mountManager->findIn($path);
404
-			foreach ($mounts as $mount) {
405
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
406
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
407
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
408
-					throw new \Exception($message);
409
-				}
410
-
411
-			}
412
-		}
413
-
414
-		// single file shares should never have delete permissions
415
-		if ($itemType === 'file') {
416
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
417
-		}
418
-
419
-		//Validate expirationDate
420
-		if ($expirationDate !== null) {
421
-			try {
422
-				/*
60
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
61
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
62
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
63
+     *
64
+     * Check if permission is granted with And (&) e.g. Check if delete is
65
+     * granted: if ($permissions & PERMISSION_DELETE)
66
+     *
67
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
68
+     * permission: $permissions &= ~PERMISSION_UPDATE
69
+     *
70
+     * Apps are required to handle permissions on their own, this class only
71
+     * stores and manages the permissions of shares
72
+     * @see lib/public/constants.php
73
+     */
74
+
75
+    /**
76
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
77
+     * @param string $itemType Item type
78
+     * @param string $class Backend class
79
+     * @param string $collectionOf (optional) Depends on item type
80
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
81
+     * @return boolean true if backend is registered or false if error
82
+     */
83
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
84
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
85
+            if (!isset(self::$backendTypes[$itemType])) {
86
+                self::$backendTypes[$itemType] = array(
87
+                    'class' => $class,
88
+                    'collectionOf' => $collectionOf,
89
+                    'supportedFileExtensions' => $supportedFileExtensions
90
+                );
91
+                if(count(self::$backendTypes) === 1) {
92
+                    Util::addScript('core', 'merged-share-backend');
93
+                    \OC_Util::addStyle('core', 'share');
94
+                }
95
+                return true;
96
+            }
97
+            \OCP\Util::writeLog('OCP\Share',
98
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
99
+                .' is already registered for '.$itemType,
100
+                \OCP\Util::WARN);
101
+        }
102
+        return false;
103
+    }
104
+
105
+    /**
106
+     * Get the items of item type shared with the current user
107
+     * @param string $itemType
108
+     * @param int $format (optional) Format type must be defined by the backend
109
+     * @param mixed $parameters (optional)
110
+     * @param int $limit Number of items to return (optional) Returns all by default
111
+     * @param boolean $includeCollections (optional)
112
+     * @return mixed Return depends on format
113
+     */
114
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
115
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
116
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
117
+            $parameters, $limit, $includeCollections);
118
+    }
119
+
120
+    /**
121
+     * Get the items of item type shared with a user
122
+     * @param string $itemType
123
+     * @param string $user id for which user we want the shares
124
+     * @param int $format (optional) Format type must be defined by the backend
125
+     * @param mixed $parameters (optional)
126
+     * @param int $limit Number of items to return (optional) Returns all by default
127
+     * @param boolean $includeCollections (optional)
128
+     * @return mixed Return depends on format
129
+     */
130
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
131
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
132
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
133
+            $parameters, $limit, $includeCollections);
134
+    }
135
+
136
+    /**
137
+     * Get the item of item type shared with a given user by source
138
+     * @param string $itemType
139
+     * @param string $itemSource
140
+     * @param string $user User to whom the item was shared
141
+     * @param string $owner Owner of the share
142
+     * @param int $shareType only look for a specific share type
143
+     * @return array Return list of items with file_target, permissions and expiration
144
+     */
145
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
146
+        $shares = array();
147
+        $fileDependent = false;
148
+
149
+        $where = 'WHERE';
150
+        $fileDependentWhere = '';
151
+        if ($itemType === 'file' || $itemType === 'folder') {
152
+            $fileDependent = true;
153
+            $column = 'file_source';
154
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
155
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
156
+        } else {
157
+            $column = 'item_source';
158
+        }
159
+
160
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
161
+
162
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
163
+        $arguments = array($itemSource, $itemType);
164
+        // for link shares $user === null
165
+        if ($user !== null) {
166
+            $where .= ' AND `share_with` = ? ';
167
+            $arguments[] = $user;
168
+        }
169
+
170
+        if ($shareType !== null) {
171
+            $where .= ' AND `share_type` = ? ';
172
+            $arguments[] = $shareType;
173
+        }
174
+
175
+        if ($owner !== null) {
176
+            $where .= ' AND `uid_owner` = ? ';
177
+            $arguments[] = $owner;
178
+        }
179
+
180
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
181
+
182
+        $result = \OC_DB::executeAudited($query, $arguments);
183
+
184
+        while ($row = $result->fetchRow()) {
185
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
186
+                continue;
187
+            }
188
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
189
+                // if it is a mount point we need to get the path from the mount manager
190
+                $mountManager = \OC\Files\Filesystem::getMountManager();
191
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
192
+                if (!empty($mountPoint)) {
193
+                    $path = $mountPoint[0]->getMountPoint();
194
+                    $path = trim($path, '/');
195
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
196
+                    $row['path'] = $path;
197
+                } else {
198
+                    \OC::$server->getLogger()->warning(
199
+                        'Could not resolve mount point for ' . $row['storage_id'],
200
+                        ['app' => 'OCP\Share']
201
+                    );
202
+                }
203
+            }
204
+            $shares[] = $row;
205
+        }
206
+
207
+        //if didn't found a result than let's look for a group share.
208
+        if(empty($shares) && $user !== null) {
209
+            $userObject = \OC::$server->getUserManager()->get($user);
210
+            $groups = [];
211
+            if ($userObject) {
212
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
213
+            }
214
+
215
+            if (!empty($groups)) {
216
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
217
+                $arguments = array($itemSource, $itemType, $groups);
218
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
219
+
220
+                if ($owner !== null) {
221
+                    $where .= ' AND `uid_owner` = ?';
222
+                    $arguments[] = $owner;
223
+                    $types[] = null;
224
+                }
225
+
226
+                // TODO: inject connection, hopefully one day in the future when this
227
+                // class isn't static anymore...
228
+                $conn = \OC::$server->getDatabaseConnection();
229
+                $result = $conn->executeQuery(
230
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
231
+                    $arguments,
232
+                    $types
233
+                );
234
+
235
+                while ($row = $result->fetch()) {
236
+                    $shares[] = $row;
237
+                }
238
+            }
239
+        }
240
+
241
+        return $shares;
242
+
243
+    }
244
+
245
+    /**
246
+     * Get the item of item type shared with the current user by source
247
+     * @param string $itemType
248
+     * @param string $itemSource
249
+     * @param int $format (optional) Format type must be defined by the backend
250
+     * @param mixed $parameters
251
+     * @param boolean $includeCollections
252
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
253
+     * @return array
254
+     */
255
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
256
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
257
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
258
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
259
+            $parameters, 1, $includeCollections, true);
260
+    }
261
+
262
+    /**
263
+     * Based on the given token the share information will be returned - password protected shares will be verified
264
+     * @param string $token
265
+     * @param bool $checkPasswordProtection
266
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
267
+     */
268
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
269
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
270
+        $result = $query->execute(array($token));
271
+        if ($result === false) {
272
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
273
+        }
274
+        $row = $result->fetchRow();
275
+        if ($row === false) {
276
+            return false;
277
+        }
278
+        if (is_array($row) and self::expireItem($row)) {
279
+            return false;
280
+        }
281
+
282
+        // password protected shares need to be authenticated
283
+        if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
284
+            return false;
285
+        }
286
+
287
+        return $row;
288
+    }
289
+
290
+    /**
291
+     * resolves reshares down to the last real share
292
+     * @param array $linkItem
293
+     * @return array file owner
294
+     */
295
+    public static function resolveReShare($linkItem)
296
+    {
297
+        if (isset($linkItem['parent'])) {
298
+            $parent = $linkItem['parent'];
299
+            while (isset($parent)) {
300
+                $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
301
+                $item = $query->execute(array($parent))->fetchRow();
302
+                if (isset($item['parent'])) {
303
+                    $parent = $item['parent'];
304
+                } else {
305
+                    return $item;
306
+                }
307
+            }
308
+        }
309
+        return $linkItem;
310
+    }
311
+
312
+
313
+    /**
314
+     * Get the shared items of item type owned by the current user
315
+     * @param string $itemType
316
+     * @param int $format (optional) Format type must be defined by the backend
317
+     * @param mixed $parameters
318
+     * @param int $limit Number of items to return (optional) Returns all by default
319
+     * @param boolean $includeCollections
320
+     * @return mixed Return depends on format
321
+     */
322
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
323
+                                            $limit = -1, $includeCollections = false) {
324
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
325
+            $parameters, $limit, $includeCollections);
326
+    }
327
+
328
+    /**
329
+     * Get the shared item of item type owned by the current user
330
+     * @param string $itemType
331
+     * @param string $itemSource
332
+     * @param int $format (optional) Format type must be defined by the backend
333
+     * @param mixed $parameters
334
+     * @param boolean $includeCollections
335
+     * @return mixed Return depends on format
336
+     */
337
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
338
+                                            $parameters = null, $includeCollections = false) {
339
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
340
+            $parameters, -1, $includeCollections);
341
+    }
342
+
343
+    /**
344
+     * Share an item with a user, group, or via private link
345
+     * @param string $itemType
346
+     * @param string $itemSource
347
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
348
+     * @param string $shareWith User or group the item is being shared with
349
+     * @param int $permissions CRUDS
350
+     * @param string $itemSourceName
351
+     * @param \DateTime|null $expirationDate
352
+     * @param bool|null $passwordChanged
353
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
354
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
355
+     * @throws \Exception
356
+     * @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
357
+     */
358
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
359
+
360
+        $backend = self::getBackend($itemType);
361
+        $l = \OC::$server->getL10N('lib');
362
+
363
+        if ($backend->isShareTypeAllowed($shareType) === false) {
364
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
365
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
366
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
367
+            throw new \Exception($message_t);
368
+        }
369
+
370
+        $uidOwner = \OC_User::getUser();
371
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
372
+
373
+        if (is_null($itemSourceName)) {
374
+            $itemSourceName = $itemSource;
375
+        }
376
+        $itemName = $itemSourceName;
377
+
378
+        // check if file can be shared
379
+        if ($itemType === 'file' or $itemType === 'folder') {
380
+            $path = \OC\Files\Filesystem::getPath($itemSource);
381
+            $itemName = $path;
382
+
383
+            // verify that the file exists before we try to share it
384
+            if (!$path) {
385
+                $message = 'Sharing %s failed, because the file does not exist';
386
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
387
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
388
+                throw new \Exception($message_t);
389
+            }
390
+            // verify that the user has share permission
391
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
392
+                $message = 'You are not allowed to share %s';
393
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
394
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
395
+                throw new \Exception($message_t);
396
+            }
397
+        }
398
+
399
+        //verify that we don't share a folder which already contains a share mount point
400
+        if ($itemType === 'folder') {
401
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
402
+            $mountManager = \OC\Files\Filesystem::getMountManager();
403
+            $mounts = $mountManager->findIn($path);
404
+            foreach ($mounts as $mount) {
405
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
406
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
407
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
408
+                    throw new \Exception($message);
409
+                }
410
+
411
+            }
412
+        }
413
+
414
+        // single file shares should never have delete permissions
415
+        if ($itemType === 'file') {
416
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
417
+        }
418
+
419
+        //Validate expirationDate
420
+        if ($expirationDate !== null) {
421
+            try {
422
+                /*
423 423
 				 * Reuse the validateExpireDate.
424 424
 				 * We have to pass time() since the second arg is the time
425 425
 				 * the file was shared, since it is not shared yet we just use
426 426
 				 * the current time.
427 427
 				 */
428
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
429
-			} catch (\Exception $e) {
430
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
431
-			}
432
-		}
433
-
434
-		// Verify share type and sharing conditions are met
435
-		if ($shareType === self::SHARE_TYPE_USER) {
436
-			if ($shareWith == $uidOwner) {
437
-				$message = 'Sharing %s failed, because you can not share with yourself';
438
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
439
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
440
-				throw new \Exception($message_t);
441
-			}
442
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
443
-				$message = 'Sharing %s failed, because the user %s does not exist';
444
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
445
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
446
-				throw new \Exception($message_t);
447
-			}
448
-			if ($shareWithinGroupOnly) {
449
-				$userManager = \OC::$server->getUserManager();
450
-				$groupManager = \OC::$server->getGroupManager();
451
-				$userOwner = $userManager->get($uidOwner);
452
-				$userShareWith = $userManager->get($shareWith);
453
-				$groupsOwner = [];
454
-				$groupsShareWith = [];
455
-				if ($userOwner) {
456
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
457
-				}
458
-				if ($userShareWith) {
459
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
460
-				}
461
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
462
-				if (empty($inGroup)) {
463
-					$message = 'Sharing %s failed, because the user '
464
-						.'%s is not a member of any groups that %s is a member of';
465
-					$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));
466
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
467
-					throw new \Exception($message_t);
468
-				}
469
-			}
470
-			// Check if the item source is already shared with the user, either from the same owner or a different user
471
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
472
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
473
-				// Only allow the same share to occur again if it is the same
474
-				// owner and is not a user share, this use case is for increasing
475
-				// permissions for a specific user
476
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
477
-					$message = 'Sharing %s failed, because this item is already shared with %s';
478
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
479
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
480
-					throw new \Exception($message_t);
481
-				}
482
-			}
483
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
484
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
485
-				// Only allow the same share to occur again if it is the same
486
-				// owner and is not a user share, this use case is for increasing
487
-				// permissions for a specific user
488
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
489
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
490
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
491
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
492
-					throw new \Exception($message_t);
493
-				}
494
-			}
495
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
496
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
497
-				$message = 'Sharing %s failed, because the group %s does not exist';
498
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
499
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
500
-				throw new \Exception($message_t);
501
-			}
502
-			if ($shareWithinGroupOnly) {
503
-				$group = \OC::$server->getGroupManager()->get($shareWith);
504
-				$user = \OC::$server->getUserManager()->get($uidOwner);
505
-				if (!$group || !$user || !$group->inGroup($user)) {
506
-					$message = 'Sharing %s failed, because '
507
-						. '%s is not a member of the group %s';
508
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
509
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
510
-					throw new \Exception($message_t);
511
-				}
512
-			}
513
-			// Check if the item source is already shared with the group, either from the same owner or a different user
514
-			// The check for each user in the group is done inside the put() function
515
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
516
-				null, self::FORMAT_NONE, null, 1, true, true)) {
517
-
518
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
519
-					$message = 'Sharing %s failed, because this item is already shared with %s';
520
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
521
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
522
-					throw new \Exception($message_t);
523
-				}
524
-			}
525
-			// Convert share with into an array with the keys group and users
526
-			$group = $shareWith;
527
-			$shareWith = array();
528
-			$shareWith['group'] = $group;
529
-
530
-
531
-			$groupObject = \OC::$server->getGroupManager()->get($group);
532
-			$userIds = [];
533
-			if ($groupObject) {
534
-				$users = $groupObject->searchUsers('', -1, 0);
535
-				foreach ($users as $user) {
536
-					$userIds[] = $user->getUID();
537
-				}
538
-			}
539
-
540
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
541
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
542
-			$updateExistingShare = false;
543
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
544
-
545
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
546
-				if ($passwordChanged === true) {
547
-					self::verifyPassword($shareWith);
548
-				}
549
-
550
-				// when updating a link share
551
-				// FIXME Don't delete link if we update it
552
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
553
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
554
-					// remember old token
555
-					$oldToken = $checkExists['token'];
556
-					$oldPermissions = $checkExists['permissions'];
557
-					//delete the old share
558
-					Helper::delete($checkExists['id']);
559
-					$updateExistingShare = true;
560
-				}
561
-
562
-				if ($passwordChanged === null) {
563
-					// Generate hash of password - same method as user passwords
564
-					if (is_string($shareWith) && $shareWith !== '') {
565
-						self::verifyPassword($shareWith);
566
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
567
-					} else {
568
-						// reuse the already set password, but only if we change permissions
569
-						// otherwise the user disabled the password protection
570
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
571
-							$shareWith = $checkExists['share_with'];
572
-						}
573
-					}
574
-				} else {
575
-					if ($passwordChanged === true) {
576
-						if (is_string($shareWith) && $shareWith !== '') {
577
-							self::verifyPassword($shareWith);
578
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
579
-						}
580
-					} else if ($updateExistingShare) {
581
-						$shareWith = $checkExists['share_with'];
582
-					}
583
-				}
584
-
585
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
586
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
587
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
588
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
589
-					throw new \Exception($message_t);
590
-				}
591
-
592
-				if ($updateExistingShare === false &&
593
-					self::isDefaultExpireDateEnabled() &&
594
-					empty($expirationDate)) {
595
-					$expirationDate = Helper::calcExpireDate();
596
-				}
597
-
598
-				// Generate token
599
-				if (isset($oldToken)) {
600
-					$token = $oldToken;
601
-				} else {
602
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
603
-						\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
604
-					);
605
-				}
606
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
607
-					null, $token, $itemSourceName, $expirationDate);
608
-				if ($result) {
609
-					return $token;
610
-				} else {
611
-					return false;
612
-				}
613
-			}
614
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
615
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
616
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
617
-			throw new \Exception($message_t);
618
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
619
-
620
-			/*
428
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
429
+            } catch (\Exception $e) {
430
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
431
+            }
432
+        }
433
+
434
+        // Verify share type and sharing conditions are met
435
+        if ($shareType === self::SHARE_TYPE_USER) {
436
+            if ($shareWith == $uidOwner) {
437
+                $message = 'Sharing %s failed, because you can not share with yourself';
438
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
439
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
440
+                throw new \Exception($message_t);
441
+            }
442
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
443
+                $message = 'Sharing %s failed, because the user %s does not exist';
444
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
445
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
446
+                throw new \Exception($message_t);
447
+            }
448
+            if ($shareWithinGroupOnly) {
449
+                $userManager = \OC::$server->getUserManager();
450
+                $groupManager = \OC::$server->getGroupManager();
451
+                $userOwner = $userManager->get($uidOwner);
452
+                $userShareWith = $userManager->get($shareWith);
453
+                $groupsOwner = [];
454
+                $groupsShareWith = [];
455
+                if ($userOwner) {
456
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
457
+                }
458
+                if ($userShareWith) {
459
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
460
+                }
461
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
462
+                if (empty($inGroup)) {
463
+                    $message = 'Sharing %s failed, because the user '
464
+                        .'%s is not a member of any groups that %s is a member of';
465
+                    $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));
466
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
467
+                    throw new \Exception($message_t);
468
+                }
469
+            }
470
+            // Check if the item source is already shared with the user, either from the same owner or a different user
471
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
472
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
473
+                // Only allow the same share to occur again if it is the same
474
+                // owner and is not a user share, this use case is for increasing
475
+                // permissions for a specific user
476
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
477
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
478
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
479
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
480
+                    throw new \Exception($message_t);
481
+                }
482
+            }
483
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
484
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
485
+                // Only allow the same share to occur again if it is the same
486
+                // owner and is not a user share, this use case is for increasing
487
+                // permissions for a specific user
488
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
489
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
490
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
491
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
492
+                    throw new \Exception($message_t);
493
+                }
494
+            }
495
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
496
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
497
+                $message = 'Sharing %s failed, because the group %s does not exist';
498
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
499
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
500
+                throw new \Exception($message_t);
501
+            }
502
+            if ($shareWithinGroupOnly) {
503
+                $group = \OC::$server->getGroupManager()->get($shareWith);
504
+                $user = \OC::$server->getUserManager()->get($uidOwner);
505
+                if (!$group || !$user || !$group->inGroup($user)) {
506
+                    $message = 'Sharing %s failed, because '
507
+                        . '%s is not a member of the group %s';
508
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
509
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
510
+                    throw new \Exception($message_t);
511
+                }
512
+            }
513
+            // Check if the item source is already shared with the group, either from the same owner or a different user
514
+            // The check for each user in the group is done inside the put() function
515
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
516
+                null, self::FORMAT_NONE, null, 1, true, true)) {
517
+
518
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
519
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
520
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
521
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
522
+                    throw new \Exception($message_t);
523
+                }
524
+            }
525
+            // Convert share with into an array with the keys group and users
526
+            $group = $shareWith;
527
+            $shareWith = array();
528
+            $shareWith['group'] = $group;
529
+
530
+
531
+            $groupObject = \OC::$server->getGroupManager()->get($group);
532
+            $userIds = [];
533
+            if ($groupObject) {
534
+                $users = $groupObject->searchUsers('', -1, 0);
535
+                foreach ($users as $user) {
536
+                    $userIds[] = $user->getUID();
537
+                }
538
+            }
539
+
540
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
541
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
542
+            $updateExistingShare = false;
543
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
544
+
545
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
546
+                if ($passwordChanged === true) {
547
+                    self::verifyPassword($shareWith);
548
+                }
549
+
550
+                // when updating a link share
551
+                // FIXME Don't delete link if we update it
552
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
553
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
554
+                    // remember old token
555
+                    $oldToken = $checkExists['token'];
556
+                    $oldPermissions = $checkExists['permissions'];
557
+                    //delete the old share
558
+                    Helper::delete($checkExists['id']);
559
+                    $updateExistingShare = true;
560
+                }
561
+
562
+                if ($passwordChanged === null) {
563
+                    // Generate hash of password - same method as user passwords
564
+                    if (is_string($shareWith) && $shareWith !== '') {
565
+                        self::verifyPassword($shareWith);
566
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
567
+                    } else {
568
+                        // reuse the already set password, but only if we change permissions
569
+                        // otherwise the user disabled the password protection
570
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
571
+                            $shareWith = $checkExists['share_with'];
572
+                        }
573
+                    }
574
+                } else {
575
+                    if ($passwordChanged === true) {
576
+                        if (is_string($shareWith) && $shareWith !== '') {
577
+                            self::verifyPassword($shareWith);
578
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
579
+                        }
580
+                    } else if ($updateExistingShare) {
581
+                        $shareWith = $checkExists['share_with'];
582
+                    }
583
+                }
584
+
585
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
586
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
587
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
588
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
589
+                    throw new \Exception($message_t);
590
+                }
591
+
592
+                if ($updateExistingShare === false &&
593
+                    self::isDefaultExpireDateEnabled() &&
594
+                    empty($expirationDate)) {
595
+                    $expirationDate = Helper::calcExpireDate();
596
+                }
597
+
598
+                // Generate token
599
+                if (isset($oldToken)) {
600
+                    $token = $oldToken;
601
+                } else {
602
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
603
+                        \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
604
+                    );
605
+                }
606
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
607
+                    null, $token, $itemSourceName, $expirationDate);
608
+                if ($result) {
609
+                    return $token;
610
+                } else {
611
+                    return false;
612
+                }
613
+            }
614
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
615
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
616
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
617
+            throw new \Exception($message_t);
618
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
619
+
620
+            /*
621 621
 			 * Check if file is not already shared with the remote user
622 622
 			 */
623
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
624
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
625
-					$message = 'Sharing %s failed, because this item is already shared with %s';
626
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
627
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
628
-					throw new \Exception($message_t);
629
-			}
630
-
631
-			// don't allow federated shares if source and target server are the same
632
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
633
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
634
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
635
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
636
-				$message = 'Not allowed to create a federated share with the same user.';
637
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
638
-				\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
639
-				throw new \Exception($message_t);
640
-			}
641
-
642
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
643
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
644
-
645
-			$shareWith = $user . '@' . $remote;
646
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
647
-
648
-			$send = false;
649
-			if ($shareId) {
650
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
651
-			}
652
-
653
-			if ($send === false) {
654
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
655
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
656
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
657
-				throw new \Exception($message_t);
658
-			}
659
-
660
-			return $send;
661
-		} else {
662
-			// Future share types need to include their own conditions
663
-			$message = 'Share type %s is not valid for %s';
664
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
665
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
666
-			throw new \Exception($message_t);
667
-		}
668
-
669
-		// Put the item into the database
670
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
671
-
672
-		return $result ? true : false;
673
-	}
674
-
675
-	/**
676
-	 * Unshare an item from a user, group, or delete a private link
677
-	 * @param string $itemType
678
-	 * @param string $itemSource
679
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
680
-	 * @param string $shareWith User or group the item is being shared with
681
-	 * @param string $owner owner of the share, if null the current user is used
682
-	 * @return boolean true on success or false on failure
683
-	 */
684
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
685
-
686
-		// check if it is a valid itemType
687
-		self::getBackend($itemType);
688
-
689
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
690
-
691
-		$toDelete = array();
692
-		$newParent = null;
693
-		$currentUser = $owner ? $owner : \OC_User::getUser();
694
-		foreach ($items as $item) {
695
-			// delete the item with the expected share_type and owner
696
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
697
-				$toDelete = $item;
698
-				// if there is more then one result we don't have to delete the children
699
-				// but update their parent. For group shares the new parent should always be
700
-				// the original group share and not the db entry with the unique name
701
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
702
-				$newParent = $item['parent'];
703
-			} else {
704
-				$newParent = $item['id'];
705
-			}
706
-		}
707
-
708
-		if (!empty($toDelete)) {
709
-			self::unshareItem($toDelete, $newParent);
710
-			return true;
711
-		}
712
-		return false;
713
-	}
714
-
715
-	/**
716
-	 * sent status if users got informed by mail about share
717
-	 * @param string $itemType
718
-	 * @param string $itemSource
719
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
720
-	 * @param string $recipient with whom was the file shared
721
-	 * @param boolean $status
722
-	 */
723
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
724
-		$status = $status ? 1 : 0;
725
-
726
-		$query = \OC_DB::prepare(
727
-			'UPDATE `*PREFIX*share`
623
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
624
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
625
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
626
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
627
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
628
+                    throw new \Exception($message_t);
629
+            }
630
+
631
+            // don't allow federated shares if source and target server are the same
632
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
633
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
634
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
635
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
636
+                $message = 'Not allowed to create a federated share with the same user.';
637
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
638
+                \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
639
+                throw new \Exception($message_t);
640
+            }
641
+
642
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
643
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
644
+
645
+            $shareWith = $user . '@' . $remote;
646
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
647
+
648
+            $send = false;
649
+            if ($shareId) {
650
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
651
+            }
652
+
653
+            if ($send === false) {
654
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
655
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
656
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
657
+                throw new \Exception($message_t);
658
+            }
659
+
660
+            return $send;
661
+        } else {
662
+            // Future share types need to include their own conditions
663
+            $message = 'Share type %s is not valid for %s';
664
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
665
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
666
+            throw new \Exception($message_t);
667
+        }
668
+
669
+        // Put the item into the database
670
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
671
+
672
+        return $result ? true : false;
673
+    }
674
+
675
+    /**
676
+     * Unshare an item from a user, group, or delete a private link
677
+     * @param string $itemType
678
+     * @param string $itemSource
679
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
680
+     * @param string $shareWith User or group the item is being shared with
681
+     * @param string $owner owner of the share, if null the current user is used
682
+     * @return boolean true on success or false on failure
683
+     */
684
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
685
+
686
+        // check if it is a valid itemType
687
+        self::getBackend($itemType);
688
+
689
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
690
+
691
+        $toDelete = array();
692
+        $newParent = null;
693
+        $currentUser = $owner ? $owner : \OC_User::getUser();
694
+        foreach ($items as $item) {
695
+            // delete the item with the expected share_type and owner
696
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
697
+                $toDelete = $item;
698
+                // if there is more then one result we don't have to delete the children
699
+                // but update their parent. For group shares the new parent should always be
700
+                // the original group share and not the db entry with the unique name
701
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
702
+                $newParent = $item['parent'];
703
+            } else {
704
+                $newParent = $item['id'];
705
+            }
706
+        }
707
+
708
+        if (!empty($toDelete)) {
709
+            self::unshareItem($toDelete, $newParent);
710
+            return true;
711
+        }
712
+        return false;
713
+    }
714
+
715
+    /**
716
+     * sent status if users got informed by mail about share
717
+     * @param string $itemType
718
+     * @param string $itemSource
719
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
720
+     * @param string $recipient with whom was the file shared
721
+     * @param boolean $status
722
+     */
723
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
724
+        $status = $status ? 1 : 0;
725
+
726
+        $query = \OC_DB::prepare(
727
+            'UPDATE `*PREFIX*share`
728 728
 					SET `mail_send` = ?
729 729
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
730 730
 
731
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
732
-
733
-		if($result === false) {
734
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
735
-		}
736
-	}
737
-
738
-	/**
739
-	 * validate expiration date if it meets all constraints
740
-	 *
741
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
742
-	 * @param string $shareTime timestamp when the file was shared
743
-	 * @param string $itemType
744
-	 * @param string $itemSource
745
-	 * @return \DateTime validated date
746
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
747
-	 */
748
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
749
-		$l = \OC::$server->getL10N('lib');
750
-		$date = new \DateTime($expireDate);
751
-		$today = new \DateTime('now');
752
-
753
-		// if the user doesn't provide a share time we need to get it from the database
754
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
755
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
756
-		if ($defaultExpireDateEnforced && $shareTime === null) {
757
-			$items = self::getItemShared($itemType, $itemSource);
758
-			$firstItem = reset($items);
759
-			$shareTime = (int)$firstItem['stime'];
760
-		}
761
-
762
-		if ($defaultExpireDateEnforced) {
763
-			// initialize max date with share time
764
-			$maxDate = new \DateTime();
765
-			$maxDate->setTimestamp($shareTime);
766
-			$maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
767
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
768
-			if ($date > $maxDate) {
769
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
770
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
771
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
772
-				throw new \Exception($warning_t);
773
-			}
774
-		}
775
-
776
-		if ($date < $today) {
777
-			$message = 'Cannot set expiration date. Expiration date is in the past';
778
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
779
-			\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
780
-			throw new \Exception($message_t);
781
-		}
782
-
783
-		return $date;
784
-	}
785
-
786
-	/**
787
-	 * Retrieve the owner of a connection
788
-	 *
789
-	 * @param IDBConnection $connection
790
-	 * @param int $shareId
791
-	 * @throws \Exception
792
-	 * @return string uid of share owner
793
-	 */
794
-	private static function getShareOwner(IDBConnection $connection, $shareId) {
795
-		$qb = $connection->getQueryBuilder();
796
-
797
-		$qb->select('uid_owner')
798
-			->from('share')
799
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
800
-			->setParameter(':shareId', $shareId);
801
-		$dbResult = $qb->execute();
802
-		$result = $dbResult->fetch();
803
-		$dbResult->closeCursor();
804
-
805
-		if (empty($result)) {
806
-			throw new \Exception('Share not found');
807
-		}
808
-
809
-		return $result['uid_owner'];
810
-	}
811
-
812
-	/**
813
-	 * Set password for a public link share
814
-	 *
815
-	 * @param IUserSession $userSession
816
-	 * @param IDBConnection $connection
817
-	 * @param IConfig $config
818
-	 * @param int $shareId
819
-	 * @param string $password
820
-	 * @throws \Exception
821
-	 * @return boolean
822
-	 */
823
-	public static function setPassword(IUserSession $userSession,
824
-	                                   IDBConnection $connection,
825
-	                                   IConfig $config,
826
-	                                   $shareId, $password) {
827
-		$user = $userSession->getUser();
828
-		if (is_null($user)) {
829
-			throw new \Exception("User not logged in");
830
-		}
831
-
832
-		$uid = self::getShareOwner($connection, $shareId);
833
-
834
-		if ($uid !== $user->getUID()) {
835
-			throw new \Exception('Cannot update share of a different user');
836
-		}
837
-
838
-		if ($password === '') {
839
-			$password = null;
840
-		}
841
-
842
-		//If passwords are enforced the password can't be null
843
-		if (self::enforcePassword($config) && is_null($password)) {
844
-			throw new \Exception('Cannot remove password');
845
-		}
846
-
847
-		self::verifyPassword($password);
848
-
849
-		$qb = $connection->getQueryBuilder();
850
-		$qb->update('share')
851
-			->set('share_with', $qb->createParameter('pass'))
852
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
853
-			->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
854
-			->setParameter(':shareId', $shareId);
855
-
856
-		$qb->execute();
857
-
858
-		return true;
859
-	}
860
-
861
-	/**
862
-	 * Checks whether a share has expired, calls unshareItem() if yes.
863
-	 * @param array $item Share data (usually database row)
864
-	 * @return boolean True if item was expired, false otherwise.
865
-	 */
866
-	protected static function expireItem(array $item) {
867
-
868
-		$result = false;
869
-
870
-		// only use default expiration date for link shares
871
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
872
-
873
-			// calculate expiration date
874
-			if (!empty($item['expiration'])) {
875
-				$userDefinedExpire = new \DateTime($item['expiration']);
876
-				$expires = $userDefinedExpire->getTimestamp();
877
-			} else {
878
-				$expires = null;
879
-			}
880
-
881
-
882
-			// get default expiration settings
883
-			$defaultSettings = Helper::getDefaultExpireSetting();
884
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
885
-
886
-
887
-			if (is_int($expires)) {
888
-				$now = time();
889
-				if ($now > $expires) {
890
-					self::unshareItem($item);
891
-					$result = true;
892
-				}
893
-			}
894
-		}
895
-		return $result;
896
-	}
897
-
898
-	/**
899
-	 * Unshares a share given a share data array
900
-	 * @param array $item Share data (usually database row)
901
-	 * @param int $newParent parent ID
902
-	 * @return null
903
-	 */
904
-	protected static function unshareItem(array $item, $newParent = null) {
905
-
906
-		$shareType = (int)$item['share_type'];
907
-		$shareWith = null;
908
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
909
-			$shareWith = $item['share_with'];
910
-		}
911
-
912
-		// Pass all the vars we have for now, they may be useful
913
-		$hookParams = array(
914
-			'id'            => $item['id'],
915
-			'itemType'      => $item['item_type'],
916
-			'itemSource'    => $item['item_source'],
917
-			'shareType'     => $shareType,
918
-			'shareWith'     => $shareWith,
919
-			'itemParent'    => $item['parent'],
920
-			'uidOwner'      => $item['uid_owner'],
921
-		);
922
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
923
-			$hookParams['fileSource'] = $item['file_source'];
924
-			$hookParams['fileTarget'] = $item['file_target'];
925
-		}
926
-
927
-		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
928
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
929
-		$deletedShares[] = $hookParams;
930
-		$hookParams['deletedShares'] = $deletedShares;
931
-		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
932
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
933
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
934
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
935
-		}
936
-	}
937
-
938
-	/**
939
-	 * Get the backend class for the specified item type
940
-	 * @param string $itemType
941
-	 * @throws \Exception
942
-	 * @return \OCP\Share_Backend
943
-	 */
944
-	public static function getBackend($itemType) {
945
-		$l = \OC::$server->getL10N('lib');
946
-		if (isset(self::$backends[$itemType])) {
947
-			return self::$backends[$itemType];
948
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
949
-			$class = self::$backendTypes[$itemType]['class'];
950
-			if (class_exists($class)) {
951
-				self::$backends[$itemType] = new $class;
952
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
953
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
954
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
955
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
956
-					throw new \Exception($message_t);
957
-				}
958
-				return self::$backends[$itemType];
959
-			} else {
960
-				$message = 'Sharing backend %s not found';
961
-				$message_t = $l->t('Sharing backend %s not found', array($class));
962
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
963
-				throw new \Exception($message_t);
964
-			}
965
-		}
966
-		$message = 'Sharing backend for %s not found';
967
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
968
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
969
-		throw new \Exception($message_t);
970
-	}
971
-
972
-	/**
973
-	 * Check if resharing is allowed
974
-	 * @return boolean true if allowed or false
975
-	 *
976
-	 * Resharing is allowed by default if not configured
977
-	 */
978
-	public static function isResharingAllowed() {
979
-		if (!isset(self::$isResharingAllowed)) {
980
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
981
-				self::$isResharingAllowed = true;
982
-			} else {
983
-				self::$isResharingAllowed = false;
984
-			}
985
-		}
986
-		return self::$isResharingAllowed;
987
-	}
988
-
989
-	/**
990
-	 * Get a list of collection item types for the specified item type
991
-	 * @param string $itemType
992
-	 * @return array
993
-	 */
994
-	private static function getCollectionItemTypes($itemType) {
995
-		$collectionTypes = array($itemType);
996
-		foreach (self::$backendTypes as $type => $backend) {
997
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
998
-				$collectionTypes[] = $type;
999
-			}
1000
-		}
1001
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1002
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1003
-			unset($collectionTypes[0]);
1004
-		}
1005
-		// Return array if collections were found or the item type is a
1006
-		// collection itself - collections can be inside collections
1007
-		if (count($collectionTypes) > 0) {
1008
-			return $collectionTypes;
1009
-		}
1010
-		return false;
1011
-	}
1012
-
1013
-	/**
1014
-	 * Get the owners of items shared with a user.
1015
-	 *
1016
-	 * @param string $user The user the items are shared with.
1017
-	 * @param string $type The type of the items shared with the user.
1018
-	 * @param boolean $includeCollections Include collection item types (optional)
1019
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1020
-	 * @return array
1021
-	 */
1022
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1023
-		// First, we find out if $type is part of a collection (and if that collection is part of
1024
-		// another one and so on).
1025
-		$collectionTypes = array();
1026
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1027
-			$collectionTypes[] = $type;
1028
-		}
1029
-
1030
-		// Of these collection types, along with our original $type, we make a
1031
-		// list of the ones for which a sharing backend has been registered.
1032
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1033
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1034
-		$allMaybeSharedItems = array();
1035
-		foreach ($collectionTypes as $collectionType) {
1036
-			if (isset(self::$backends[$collectionType])) {
1037
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1038
-					$collectionType,
1039
-					$user,
1040
-					self::FORMAT_NONE
1041
-				);
1042
-			}
1043
-		}
1044
-
1045
-		$owners = array();
1046
-		if ($includeOwner) {
1047
-			$owners[] = $user;
1048
-		}
1049
-
1050
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
1051
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
1052
-		// and return them as elements of a list that look like "Tag (owner)".
1053
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1054
-			foreach ($maybeSharedItems as $sharedItem) {
1055
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1056
-					$owners[] = $sharedItem['uid_owner'];
1057
-				}
1058
-			}
1059
-		}
1060
-
1061
-		return $owners;
1062
-	}
1063
-
1064
-	/**
1065
-	 * Get shared items from the database
1066
-	 * @param string $itemType
1067
-	 * @param string $item Item source or target (optional)
1068
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1069
-	 * @param string $shareWith User or group the item is being shared with
1070
-	 * @param string $uidOwner User that is the owner of shared items (optional)
1071
-	 * @param int $format Format to convert items to with formatItems() (optional)
1072
-	 * @param mixed $parameters to pass to formatItems() (optional)
1073
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
1074
-	 * @param boolean $includeCollections Include collection item types (optional)
1075
-	 * @param boolean $itemShareWithBySource (optional)
1076
-	 * @param boolean $checkExpireDate
1077
-	 * @return array
1078
-	 *
1079
-	 * See public functions getItem(s)... for parameter usage
1080
-	 *
1081
-	 */
1082
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1083
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1084
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1085
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
1086
-			return array();
1087
-		}
1088
-		$backend = self::getBackend($itemType);
1089
-		$collectionTypes = false;
1090
-		// Get filesystem root to add it to the file target and remove from the
1091
-		// file source, match file_source with the file cache
1092
-		if ($itemType == 'file' || $itemType == 'folder') {
1093
-			if(!is_null($uidOwner)) {
1094
-				$root = \OC\Files\Filesystem::getRoot();
1095
-			} else {
1096
-				$root = '';
1097
-			}
1098
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1099
-			if (!isset($item)) {
1100
-				$where .= ' AND `file_target` IS NOT NULL ';
1101
-			}
1102
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1103
-			$fileDependent = true;
1104
-			$queryArgs = array();
1105
-		} else {
1106
-			$fileDependent = false;
1107
-			$root = '';
1108
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1109
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1110
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1111
-				if (!in_array($itemType, $collectionTypes)) {
1112
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1113
-				} else {
1114
-					$itemTypes = $collectionTypes;
1115
-				}
1116
-				$placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1117
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1118
-				$queryArgs = $itemTypes;
1119
-			} else {
1120
-				$where = ' WHERE `item_type` = ?';
1121
-				$queryArgs = array($itemType);
1122
-			}
1123
-		}
1124
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1125
-			$where .= ' AND `share_type` != ?';
1126
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1127
-		}
1128
-		if (isset($shareType)) {
1129
-			// Include all user and group items
1130
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1131
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1132
-				$queryArgs[] = self::SHARE_TYPE_USER;
1133
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1134
-				$queryArgs[] = $shareWith;
1135
-
1136
-				$user = \OC::$server->getUserManager()->get($shareWith);
1137
-				$groups = [];
1138
-				if ($user) {
1139
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1140
-				}
1141
-				if (!empty($groups)) {
1142
-					$placeholders = join(',', array_fill(0, count($groups), '?'));
1143
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1144
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1145
-					$queryArgs = array_merge($queryArgs, $groups);
1146
-				}
1147
-				$where .= ')';
1148
-				// Don't include own group shares
1149
-				$where .= ' AND `uid_owner` != ?';
1150
-				$queryArgs[] = $shareWith;
1151
-			} else {
1152
-				$where .= ' AND `share_type` = ?';
1153
-				$queryArgs[] = $shareType;
1154
-				if (isset($shareWith)) {
1155
-					$where .= ' AND `share_with` = ?';
1156
-					$queryArgs[] = $shareWith;
1157
-				}
1158
-			}
1159
-		}
1160
-		if (isset($uidOwner)) {
1161
-			$where .= ' AND `uid_owner` = ?';
1162
-			$queryArgs[] = $uidOwner;
1163
-			if (!isset($shareType)) {
1164
-				// Prevent unique user targets for group shares from being selected
1165
-				$where .= ' AND `share_type` != ?';
1166
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1167
-			}
1168
-			if ($fileDependent) {
1169
-				$column = 'file_source';
1170
-			} else {
1171
-				$column = 'item_source';
1172
-			}
1173
-		} else {
1174
-			if ($fileDependent) {
1175
-				$column = 'file_target';
1176
-			} else {
1177
-				$column = 'item_target';
1178
-			}
1179
-		}
1180
-		if (isset($item)) {
1181
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1182
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1183
-				$where .= ' AND (';
1184
-			} else {
1185
-				$where .= ' AND';
1186
-			}
1187
-			// If looking for own shared items, check item_source else check item_target
1188
-			if (isset($uidOwner) || $itemShareWithBySource) {
1189
-				// If item type is a file, file source needs to be checked in case the item was converted
1190
-				if ($fileDependent) {
1191
-					$where .= ' `file_source` = ?';
1192
-					$column = 'file_source';
1193
-				} else {
1194
-					$where .= ' `item_source` = ?';
1195
-					$column = 'item_source';
1196
-				}
1197
-			} else {
1198
-				if ($fileDependent) {
1199
-					$where .= ' `file_target` = ?';
1200
-					$item = \OC\Files\Filesystem::normalizePath($item);
1201
-				} else {
1202
-					$where .= ' `item_target` = ?';
1203
-				}
1204
-			}
1205
-			$queryArgs[] = $item;
1206
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1207
-				$placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1208
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1209
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1210
-			}
1211
-		}
1212
-
1213
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1214
-			// Make sure the unique user target is returned if it exists,
1215
-			// unique targets should follow the group share in the database
1216
-			// If the limit is not 1, the filtering can be done later
1217
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1218
-		} else {
1219
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1220
-		}
1221
-
1222
-		if ($limit != -1 && !$includeCollections) {
1223
-			// The limit must be at least 3, because filtering needs to be done
1224
-			if ($limit < 3) {
1225
-				$queryLimit = 3;
1226
-			} else {
1227
-				$queryLimit = $limit;
1228
-			}
1229
-		} else {
1230
-			$queryLimit = null;
1231
-		}
1232
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1233
-		$root = strlen($root);
1234
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1235
-		$result = $query->execute($queryArgs);
1236
-		if ($result === false) {
1237
-			\OCP\Util::writeLog('OCP\Share',
1238
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1239
-				\OCP\Util::ERROR);
1240
-		}
1241
-		$items = array();
1242
-		$targets = array();
1243
-		$switchedItems = array();
1244
-		$mounts = array();
1245
-		while ($row = $result->fetchRow()) {
1246
-			self::transformDBResults($row);
1247
-			// Filter out duplicate group shares for users with unique targets
1248
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1249
-				continue;
1250
-			}
1251
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1252
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1253
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1254
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1255
-				// if the group share was unshared from the user we keep the permission, otherwise
1256
-				// we take the permission from the parent because this is always the up-to-date
1257
-				// permission for the group share
1258
-				if ($row['permissions'] > 0) {
1259
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1260
-				}
1261
-				// Remove the parent group share
1262
-				unset($items[$row['parent']]);
1263
-				if ($row['permissions'] == 0) {
1264
-					continue;
1265
-				}
1266
-			} else if (!isset($uidOwner)) {
1267
-				// Check if the same target already exists
1268
-				if (isset($targets[$row['id']])) {
1269
-					// Check if the same owner shared with the user twice
1270
-					// through a group and user share - this is allowed
1271
-					$id = $targets[$row['id']];
1272
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1273
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1274
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1275
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1276
-							$items[$id]['share_with'] = $row['share_with'];
1277
-						}
1278
-						// Switch ids if sharing permission is granted on only
1279
-						// one share to ensure correct parent is used if resharing
1280
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1281
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1282
-							$items[$row['id']] = $items[$id];
1283
-							$switchedItems[$id] = $row['id'];
1284
-							unset($items[$id]);
1285
-							$id = $row['id'];
1286
-						}
1287
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1288
-
1289
-					}
1290
-					continue;
1291
-				} elseif (!empty($row['parent'])) {
1292
-					$targets[$row['parent']] = $row['id'];
1293
-				}
1294
-			}
1295
-			// Remove root from file source paths if retrieving own shared items
1296
-			if (isset($uidOwner) && isset($row['path'])) {
1297
-				if (isset($row['parent'])) {
1298
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1299
-					$parentResult = $query->execute(array($row['parent']));
1300
-					if ($result === false) {
1301
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1302
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1303
-							\OCP\Util::ERROR);
1304
-					} else {
1305
-						$parentRow = $parentResult->fetchRow();
1306
-						$tmpPath = $parentRow['file_target'];
1307
-						// find the right position where the row path continues from the target path
1308
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1309
-						$subPath = substr($row['path'], $pos);
1310
-						$splitPath = explode('/', $subPath);
1311
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1312
-							$tmpPath = $tmpPath . '/' . $pathPart;
1313
-						}
1314
-						$row['path'] = $tmpPath;
1315
-					}
1316
-				} else {
1317
-					if (!isset($mounts[$row['storage']])) {
1318
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1319
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1320
-							$mounts[$row['storage']] = current($mountPoints);
1321
-						}
1322
-					}
1323
-					if (!empty($mounts[$row['storage']])) {
1324
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1325
-						$relPath = substr($path, $root); // path relative to data/user
1326
-						$row['path'] = rtrim($relPath, '/');
1327
-					}
1328
-				}
1329
-			}
1330
-
1331
-			if($checkExpireDate) {
1332
-				if (self::expireItem($row)) {
1333
-					continue;
1334
-				}
1335
-			}
1336
-			// Check if resharing is allowed, if not remove share permission
1337
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1338
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1339
-			}
1340
-			// Add display names to result
1341
-			$row['share_with_displayname'] = $row['share_with'];
1342
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
1343
-				$row['share_type'] === self::SHARE_TYPE_USER) {
1344
-				$row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
1345
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
1346
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
1347
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1348
-				foreach ($addressBookEntries as $entry) {
1349
-					foreach ($entry['CLOUD'] as $cloudID) {
1350
-						if ($cloudID === $row['share_with']) {
1351
-							$row['share_with_displayname'] = $entry['FN'];
1352
-						}
1353
-					}
1354
-				}
1355
-			}
1356
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1357
-				$row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
1358
-			}
1359
-
1360
-			if ($row['permissions'] > 0) {
1361
-				$items[$row['id']] = $row;
1362
-			}
1363
-
1364
-		}
1365
-
1366
-		// group items if we are looking for items shared with the current user
1367
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1368
-			$items = self::groupItems($items, $itemType);
1369
-		}
1370
-
1371
-		if (!empty($items)) {
1372
-			$collectionItems = array();
1373
-			foreach ($items as &$row) {
1374
-				// Return only the item instead of a 2-dimensional array
1375
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1376
-					if ($format == self::FORMAT_NONE) {
1377
-						return $row;
1378
-					} else {
1379
-						break;
1380
-					}
1381
-				}
1382
-				// Check if this is a collection of the requested item type
1383
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1384
-					if (($collectionBackend = self::getBackend($row['item_type']))
1385
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1386
-						// Collections can be inside collections, check if the item is a collection
1387
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1388
-							$collectionItems[] = $row;
1389
-						} else {
1390
-							$collection = array();
1391
-							$collection['item_type'] = $row['item_type'];
1392
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1393
-								$collection['path'] = basename($row['path']);
1394
-							}
1395
-							$row['collection'] = $collection;
1396
-							// Fetch all of the children sources
1397
-							$children = $collectionBackend->getChildren($row[$column]);
1398
-							foreach ($children as $child) {
1399
-								$childItem = $row;
1400
-								$childItem['item_type'] = $itemType;
1401
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1402
-									$childItem['item_source'] = $child['source'];
1403
-									$childItem['item_target'] = $child['target'];
1404
-								}
1405
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1406
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1407
-										$childItem['file_source'] = $child['source'];
1408
-									} else { // TODO is this really needed if we already know that we use the file backend?
1409
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1410
-										$childItem['file_source'] = $meta['fileid'];
1411
-									}
1412
-									$childItem['file_target'] =
1413
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
1414
-								}
1415
-								if (isset($item)) {
1416
-									if ($childItem[$column] == $item) {
1417
-										// Return only the item instead of a 2-dimensional array
1418
-										if ($limit == 1) {
1419
-											if ($format == self::FORMAT_NONE) {
1420
-												return $childItem;
1421
-											} else {
1422
-												// Unset the items array and break out of both loops
1423
-												$items = array();
1424
-												$items[] = $childItem;
1425
-												break 2;
1426
-											}
1427
-										} else {
1428
-											$collectionItems[] = $childItem;
1429
-										}
1430
-									}
1431
-								} else {
1432
-									$collectionItems[] = $childItem;
1433
-								}
1434
-							}
1435
-						}
1436
-					}
1437
-					// Remove collection item
1438
-					$toRemove = $row['id'];
1439
-					if (array_key_exists($toRemove, $switchedItems)) {
1440
-						$toRemove = $switchedItems[$toRemove];
1441
-					}
1442
-					unset($items[$toRemove]);
1443
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1444
-					// FIXME: Thats a dirty hack to improve file sharing performance,
1445
-					// see github issue #10588 for more details
1446
-					// Need to find a solution which works for all back-ends
1447
-					$collectionBackend = self::getBackend($row['item_type']);
1448
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
1449
-					foreach ($sharedParents as $parent) {
1450
-						$collectionItems[] = $parent;
1451
-					}
1452
-				}
1453
-			}
1454
-			if (!empty($collectionItems)) {
1455
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
1456
-				$items = array_merge($items, $collectionItems);
1457
-			}
1458
-
1459
-			// filter out invalid items, these can appear when subshare entries exist
1460
-			// for a group in which the requested user isn't a member any more
1461
-			$items = array_filter($items, function($item) {
1462
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1463
-			});
1464
-
1465
-			return self::formatResult($items, $column, $backend, $format, $parameters);
1466
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1467
-			// FIXME: Thats a dirty hack to improve file sharing performance,
1468
-			// see github issue #10588 for more details
1469
-			// Need to find a solution which works for all back-ends
1470
-			$collectionItems = array();
1471
-			$collectionBackend = self::getBackend('folder');
1472
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1473
-			foreach ($sharedParents as $parent) {
1474
-				$collectionItems[] = $parent;
1475
-			}
1476
-			if ($limit === 1) {
1477
-				return reset($collectionItems);
1478
-			}
1479
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1480
-		}
1481
-
1482
-		return array();
1483
-	}
1484
-
1485
-	/**
1486
-	 * group items with link to the same source
1487
-	 *
1488
-	 * @param array $items
1489
-	 * @param string $itemType
1490
-	 * @return array of grouped items
1491
-	 */
1492
-	protected static function groupItems($items, $itemType) {
1493
-
1494
-		$fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
1495
-
1496
-		$result = array();
1497
-
1498
-		foreach ($items as $item) {
1499
-			$grouped = false;
1500
-			foreach ($result as $key => $r) {
1501
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1502
-				// only group shares if they already point to the same target, otherwise the file where shared
1503
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1504
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1505
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1506
-					// add the first item to the list of grouped shares
1507
-					if (!isset($result[$key]['grouped'])) {
1508
-						$result[$key]['grouped'][] = $result[$key];
1509
-					}
1510
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1511
-					$result[$key]['grouped'][] = $item;
1512
-					$grouped = true;
1513
-					break;
1514
-				}
1515
-			}
1516
-
1517
-			if (!$grouped) {
1518
-				$result[] = $item;
1519
-			}
1520
-
1521
-		}
1522
-
1523
-		return $result;
1524
-	}
1525
-
1526
-	/**
1527
-	 * Put shared item into the database
1528
-	 * @param string $itemType Item type
1529
-	 * @param string $itemSource Item source
1530
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1531
-	 * @param string $shareWith User or group the item is being shared with
1532
-	 * @param string $uidOwner User that is the owner of shared item
1533
-	 * @param int $permissions CRUDS permissions
1534
-	 * @param boolean|array $parentFolder Parent folder target (optional)
1535
-	 * @param string $token (optional)
1536
-	 * @param string $itemSourceName name of the source item (optional)
1537
-	 * @param \DateTime $expirationDate (optional)
1538
-	 * @throws \Exception
1539
-	 * @return mixed id of the new share or false
1540
-	 */
1541
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1542
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1543
-
1544
-		$queriesToExecute = array();
1545
-		$suggestedItemTarget = null;
1546
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1547
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1548
-
1549
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1550
-		if(!empty($result)) {
1551
-			$parent = $result['parent'];
1552
-			$itemSource = $result['itemSource'];
1553
-			$fileSource = $result['fileSource'];
1554
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1555
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1556
-			$filePath = $result['filePath'];
1557
-		}
1558
-
1559
-		$isGroupShare = false;
1560
-		if ($shareType == self::SHARE_TYPE_GROUP) {
1561
-			$isGroupShare = true;
1562
-			if (isset($shareWith['users'])) {
1563
-				$users = $shareWith['users'];
1564
-			} else {
1565
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
1566
-				if ($group) {
1567
-					$users = $group->searchUsers('', -1, 0);
1568
-					$userIds = [];
1569
-					foreach ($users as $user) {
1570
-						$userIds[] = $user->getUID();
1571
-					}
1572
-					$users = $userIds;
1573
-				} else {
1574
-					$users = [];
1575
-				}
1576
-			}
1577
-			// remove current user from list
1578
-			if (in_array(\OCP\User::getUser(), $users)) {
1579
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
1580
-			}
1581
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1582
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1583
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1584
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
1585
-
1586
-			// add group share to table and remember the id as parent
1587
-			$queriesToExecute['groupShare'] = array(
1588
-				'itemType'			=> $itemType,
1589
-				'itemSource'		=> $itemSource,
1590
-				'itemTarget'		=> $groupItemTarget,
1591
-				'shareType'			=> $shareType,
1592
-				'shareWith'			=> $shareWith['group'],
1593
-				'uidOwner'			=> $uidOwner,
1594
-				'permissions'		=> $permissions,
1595
-				'shareTime'			=> time(),
1596
-				'fileSource'		=> $fileSource,
1597
-				'fileTarget'		=> $groupFileTarget,
1598
-				'token'				=> $token,
1599
-				'parent'			=> $parent,
1600
-				'expiration'		=> $expirationDate,
1601
-			);
1602
-
1603
-		} else {
1604
-			$users = array($shareWith);
1605
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1606
-				$suggestedItemTarget);
1607
-		}
1608
-
1609
-		$run = true;
1610
-		$error = '';
1611
-		$preHookData = array(
1612
-			'itemType' => $itemType,
1613
-			'itemSource' => $itemSource,
1614
-			'shareType' => $shareType,
1615
-			'uidOwner' => $uidOwner,
1616
-			'permissions' => $permissions,
1617
-			'fileSource' => $fileSource,
1618
-			'expiration' => $expirationDate,
1619
-			'token' => $token,
1620
-			'run' => &$run,
1621
-			'error' => &$error
1622
-		);
1623
-
1624
-		$preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1625
-		$preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1626
-
1627
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
1628
-
1629
-		if ($run === false) {
1630
-			throw new \Exception($error);
1631
-		}
1632
-
1633
-		foreach ($users as $user) {
1634
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1635
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1636
-
1637
-			$userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
1638
-
1639
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1640
-				$fileTarget = $sourceExists['file_target'];
1641
-				$itemTarget = $sourceExists['item_target'];
1642
-
1643
-				// for group shares we don't need a additional entry if the target is the same
1644
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
1645
-					continue;
1646
-				}
1647
-
1648
-			} elseif(!$sourceExists && !$isGroupShare)  {
1649
-
1650
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1651
-					$uidOwner, $suggestedItemTarget, $parent);
1652
-				if (isset($fileSource)) {
1653
-					if ($parentFolder) {
1654
-						if ($parentFolder === true) {
1655
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1656
-								$uidOwner, $suggestedFileTarget, $parent);
1657
-							if ($fileTarget != $groupFileTarget) {
1658
-								$parentFolders[$user]['folder'] = $fileTarget;
1659
-							}
1660
-						} else if (isset($parentFolder[$user])) {
1661
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
1662
-							$parent = $parentFolder[$user]['id'];
1663
-						}
1664
-					} else {
1665
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1666
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1667
-					}
1668
-				} else {
1669
-					$fileTarget = null;
1670
-				}
1671
-
1672
-			} else {
1673
-
1674
-				// group share which doesn't exists until now, check if we need a unique target for this user
1675
-
1676
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1677
-					$uidOwner, $suggestedItemTarget, $parent);
1678
-
1679
-				// do we also need a file target
1680
-				if (isset($fileSource)) {
1681
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1682
-						$uidOwner, $suggestedFileTarget, $parent);
1683
-				} else {
1684
-					$fileTarget = null;
1685
-				}
1686
-
1687
-				if (($itemTarget === $groupItemTarget) &&
1688
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1689
-					continue;
1690
-				}
1691
-			}
1692
-
1693
-			$queriesToExecute[] = array(
1694
-				'itemType'			=> $itemType,
1695
-				'itemSource'		=> $itemSource,
1696
-				'itemTarget'		=> $itemTarget,
1697
-				'shareType'			=> $userShareType,
1698
-				'shareWith'			=> $user,
1699
-				'uidOwner'			=> $uidOwner,
1700
-				'permissions'		=> $permissions,
1701
-				'shareTime'			=> time(),
1702
-				'fileSource'		=> $fileSource,
1703
-				'fileTarget'		=> $fileTarget,
1704
-				'token'				=> $token,
1705
-				'parent'			=> $parent,
1706
-				'expiration'		=> $expirationDate,
1707
-			);
1708
-
1709
-		}
1710
-
1711
-		$id = false;
1712
-		if ($isGroupShare) {
1713
-			$id = self::insertShare($queriesToExecute['groupShare']);
1714
-			// Save this id, any extra rows for this group share will need to reference it
1715
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1716
-			unset($queriesToExecute['groupShare']);
1717
-		}
1718
-
1719
-		foreach ($queriesToExecute as $shareQuery) {
1720
-			$shareQuery['parent'] = $parent;
1721
-			$id = self::insertShare($shareQuery);
1722
-		}
1723
-
1724
-		$postHookData = array(
1725
-			'itemType' => $itemType,
1726
-			'itemSource' => $itemSource,
1727
-			'parent' => $parent,
1728
-			'shareType' => $shareType,
1729
-			'uidOwner' => $uidOwner,
1730
-			'permissions' => $permissions,
1731
-			'fileSource' => $fileSource,
1732
-			'id' => $parent,
1733
-			'token' => $token,
1734
-			'expirationDate' => $expirationDate,
1735
-		);
1736
-
1737
-		$postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1738
-		$postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1739
-		$postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
1740
-
1741
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
1742
-
1743
-
1744
-		return $id ? $id : false;
1745
-	}
1746
-
1747
-	/**
1748
-	 * @param string $itemType
1749
-	 * @param string $itemSource
1750
-	 * @param int $shareType
1751
-	 * @param string $shareWith
1752
-	 * @param string $uidOwner
1753
-	 * @param int $permissions
1754
-	 * @param string|null $itemSourceName
1755
-	 * @param null|\DateTime $expirationDate
1756
-	 */
1757
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1758
-		$backend = self::getBackend($itemType);
1759
-
1760
-		$l = \OC::$server->getL10N('lib');
1761
-		$result = array();
1762
-
1763
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1764
-
1765
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1766
-		if ($checkReshare) {
1767
-			// Check if attempting to share back to owner
1768
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1769
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
1770
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1771
-
1772
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
1773
-				throw new \Exception($message_t);
1774
-			}
1775
-		}
1776
-
1777
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1778
-			// Check if share permissions is granted
1779
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1780
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1781
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1782
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1783
-
1784
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
1785
-					throw new \Exception($message_t);
1786
-				} else {
1787
-					// TODO Don't check if inside folder
1788
-					$result['parent'] = $checkReshare['id'];
1789
-
1790
-					$result['expirationDate'] = $expirationDate;
1791
-					// $checkReshare['expiration'] could be null and then is always less than any value
1792
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1793
-						$result['expirationDate'] = $checkReshare['expiration'];
1794
-					}
1795
-
1796
-					// only suggest the same name as new target if it is a reshare of the
1797
-					// same file/folder and not the reshare of a child
1798
-					if ($checkReshare[$column] === $itemSource) {
1799
-						$result['filePath'] = $checkReshare['file_target'];
1800
-						$result['itemSource'] = $checkReshare['item_source'];
1801
-						$result['fileSource'] = $checkReshare['file_source'];
1802
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1803
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1804
-					} else {
1805
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1806
-						$result['suggestedItemTarget'] = null;
1807
-						$result['suggestedFileTarget'] = null;
1808
-						$result['itemSource'] = $itemSource;
1809
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1810
-					}
1811
-				}
1812
-			} else {
1813
-				$message = 'Sharing %s failed, because resharing is not allowed';
1814
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1815
-
1816
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
1817
-				throw new \Exception($message_t);
1818
-			}
1819
-		} else {
1820
-			$result['parent'] = null;
1821
-			$result['suggestedItemTarget'] = null;
1822
-			$result['suggestedFileTarget'] = null;
1823
-			$result['itemSource'] = $itemSource;
1824
-			$result['expirationDate'] = $expirationDate;
1825
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1826
-				$message = 'Sharing %s failed, because the sharing backend for '
1827
-					.'%s could not find its source';
1828
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1829
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
1830
-				throw new \Exception($message_t);
1831
-			}
1832
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1833
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1834
-				if ($itemType == 'file' || $itemType == 'folder') {
1835
-					$result['fileSource'] = $itemSource;
1836
-				} else {
1837
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1838
-					$result['fileSource'] = $meta['fileid'];
1839
-				}
1840
-				if ($result['fileSource'] == -1) {
1841
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1842
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1843
-
1844
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1845
-					throw new \Exception($message_t);
1846
-				}
1847
-			} else {
1848
-				$result['filePath'] = null;
1849
-				$result['fileSource'] = null;
1850
-			}
1851
-		}
1852
-
1853
-		return $result;
1854
-	}
1855
-
1856
-	/**
1857
-	 *
1858
-	 * @param array $shareData
1859
-	 * @return mixed false in case of a failure or the id of the new share
1860
-	 */
1861
-	private static function insertShare(array $shareData) {
1862
-
1863
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1864
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1865
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1866
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1867
-		$query->bindValue(1, $shareData['itemType']);
1868
-		$query->bindValue(2, $shareData['itemSource']);
1869
-		$query->bindValue(3, $shareData['itemTarget']);
1870
-		$query->bindValue(4, $shareData['shareType']);
1871
-		$query->bindValue(5, $shareData['shareWith']);
1872
-		$query->bindValue(6, $shareData['uidOwner']);
1873
-		$query->bindValue(7, $shareData['permissions']);
1874
-		$query->bindValue(8, $shareData['shareTime']);
1875
-		$query->bindValue(9, $shareData['fileSource']);
1876
-		$query->bindValue(10, $shareData['fileTarget']);
1877
-		$query->bindValue(11, $shareData['token']);
1878
-		$query->bindValue(12, $shareData['parent']);
1879
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1880
-		$result = $query->execute();
1881
-
1882
-		$id = false;
1883
-		if ($result) {
1884
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1885
-		}
1886
-
1887
-		return $id;
1888
-
1889
-	}
1890
-
1891
-	/**
1892
-	 * In case a password protected link is not yet authenticated this function will return false
1893
-	 *
1894
-	 * @param array $linkItem
1895
-	 * @return boolean
1896
-	 */
1897
-	public static function checkPasswordProtectedShare(array $linkItem) {
1898
-		if (!isset($linkItem['share_with'])) {
1899
-			return true;
1900
-		}
1901
-		if (!isset($linkItem['share_type'])) {
1902
-			return true;
1903
-		}
1904
-		if (!isset($linkItem['id'])) {
1905
-			return true;
1906
-		}
1907
-
1908
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1909
-			return true;
1910
-		}
1911
-
1912
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
1913
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1914
-			return true;
1915
-		}
1916
-
1917
-		return false;
1918
-	}
1919
-
1920
-	/**
1921
-	 * construct select statement
1922
-	 * @param int $format
1923
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1924
-	 * @param string $uidOwner
1925
-	 * @return string select statement
1926
-	 */
1927
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1928
-		$select = '*';
1929
-		if ($format == self::FORMAT_STATUSES) {
1930
-			if ($fileDependent) {
1931
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1932
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1933
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1934
-					. '`uid_initiator`';
1935
-			} else {
1936
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1937
-			}
1938
-		} else {
1939
-			if (isset($uidOwner)) {
1940
-				if ($fileDependent) {
1941
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1942
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1943
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1944
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1945
-				} else {
1946
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1947
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1948
-				}
1949
-			} else {
1950
-				if ($fileDependent) {
1951
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1952
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1953
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1954
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1955
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1956
-					} else {
1957
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1958
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1959
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1960
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1961
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1962
-					}
1963
-				}
1964
-			}
1965
-		}
1966
-		return $select;
1967
-	}
1968
-
1969
-
1970
-	/**
1971
-	 * transform db results
1972
-	 * @param array $row result
1973
-	 */
1974
-	private static function transformDBResults(&$row) {
1975
-		if (isset($row['id'])) {
1976
-			$row['id'] = (int) $row['id'];
1977
-		}
1978
-		if (isset($row['share_type'])) {
1979
-			$row['share_type'] = (int) $row['share_type'];
1980
-		}
1981
-		if (isset($row['parent'])) {
1982
-			$row['parent'] = (int) $row['parent'];
1983
-		}
1984
-		if (isset($row['file_parent'])) {
1985
-			$row['file_parent'] = (int) $row['file_parent'];
1986
-		}
1987
-		if (isset($row['file_source'])) {
1988
-			$row['file_source'] = (int) $row['file_source'];
1989
-		}
1990
-		if (isset($row['permissions'])) {
1991
-			$row['permissions'] = (int) $row['permissions'];
1992
-		}
1993
-		if (isset($row['storage'])) {
1994
-			$row['storage'] = (int) $row['storage'];
1995
-		}
1996
-		if (isset($row['stime'])) {
1997
-			$row['stime'] = (int) $row['stime'];
1998
-		}
1999
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2000
-			// discard expiration date for non-link shares, which might have been
2001
-			// set by ancient bugs
2002
-			$row['expiration'] = null;
2003
-		}
2004
-	}
2005
-
2006
-	/**
2007
-	 * format result
2008
-	 * @param array $items result
2009
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2010
-	 * @param \OCP\Share_Backend $backend sharing backend
2011
-	 * @param int $format
2012
-	 * @param array $parameters additional format parameters
2013
-	 * @return array format result
2014
-	 */
2015
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2016
-		if ($format === self::FORMAT_NONE) {
2017
-			return $items;
2018
-		} else if ($format === self::FORMAT_STATUSES) {
2019
-			$statuses = array();
2020
-			foreach ($items as $item) {
2021
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2022
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2023
-						continue;
2024
-					}
2025
-					$statuses[$item[$column]]['link'] = true;
2026
-				} else if (!isset($statuses[$item[$column]])) {
2027
-					$statuses[$item[$column]]['link'] = false;
2028
-				}
2029
-				if (!empty($item['file_target'])) {
2030
-					$statuses[$item[$column]]['path'] = $item['path'];
2031
-				}
2032
-			}
2033
-			return $statuses;
2034
-		} else {
2035
-			return $backend->formatItems($items, $format, $parameters);
2036
-		}
2037
-	}
2038
-
2039
-	/**
2040
-	 * remove protocol from URL
2041
-	 *
2042
-	 * @param string $url
2043
-	 * @return string
2044
-	 */
2045
-	public static function removeProtocolFromUrl($url) {
2046
-		if (strpos($url, 'https://') === 0) {
2047
-			return substr($url, strlen('https://'));
2048
-		} else if (strpos($url, 'http://') === 0) {
2049
-			return substr($url, strlen('http://'));
2050
-		}
2051
-
2052
-		return $url;
2053
-	}
2054
-
2055
-	/**
2056
-	 * try http post first with https and then with http as a fallback
2057
-	 *
2058
-	 * @param string $remoteDomain
2059
-	 * @param string $urlSuffix
2060
-	 * @param array $fields post parameters
2061
-	 * @return array
2062
-	 */
2063
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2064
-		$protocol = 'https://';
2065
-		$result = [
2066
-			'success' => false,
2067
-			'result' => '',
2068
-		];
2069
-		$try = 0;
2070
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
2071
-		while ($result['success'] === false && $try < 2) {
2072
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2073
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2074
-			$result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2075
-			$try++;
2076
-			$protocol = 'http://';
2077
-		}
2078
-
2079
-		return $result;
2080
-	}
2081
-
2082
-	/**
2083
-	 * send server-to-server share to remote server
2084
-	 *
2085
-	 * @param string $token
2086
-	 * @param string $shareWith
2087
-	 * @param string $name
2088
-	 * @param int $remote_id
2089
-	 * @param string $owner
2090
-	 * @return bool
2091
-	 */
2092
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2093
-
2094
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2095
-
2096
-		if ($user && $remote) {
2097
-			$url = $remote;
2098
-
2099
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2100
-
2101
-			$fields = array(
2102
-				'shareWith' => $user,
2103
-				'token' => $token,
2104
-				'name' => $name,
2105
-				'remoteId' => $remote_id,
2106
-				'owner' => $owner,
2107
-				'remote' => $local,
2108
-			);
2109
-
2110
-			$url = self::removeProtocolFromUrl($url);
2111
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2112
-			$status = json_decode($result['result'], true);
2113
-
2114
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2115
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2116
-				return true;
2117
-			}
2118
-
2119
-		}
2120
-
2121
-		return false;
2122
-	}
2123
-
2124
-	/**
2125
-	 * send server-to-server unshare to remote server
2126
-	 *
2127
-	 * @param string $remote url
2128
-	 * @param int $id share id
2129
-	 * @param string $token
2130
-	 * @return bool
2131
-	 */
2132
-	private static function sendRemoteUnshare($remote, $id, $token) {
2133
-		$url = rtrim($remote, '/');
2134
-		$fields = array('token' => $token, 'format' => 'json');
2135
-		$url = self::removeProtocolFromUrl($url);
2136
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2137
-		$status = json_decode($result['result'], true);
2138
-
2139
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2140
-	}
2141
-
2142
-	/**
2143
-	 * check if user can only share with group members
2144
-	 * @return bool
2145
-	 */
2146
-	public static function shareWithGroupMembersOnly() {
2147
-		$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2148
-		return ($value === 'yes') ? true : false;
2149
-	}
2150
-
2151
-	/**
2152
-	 * @return bool
2153
-	 */
2154
-	public static function isDefaultExpireDateEnabled() {
2155
-		$defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2156
-		return ($defaultExpireDateEnabled === "yes") ? true : false;
2157
-	}
2158
-
2159
-	/**
2160
-	 * @return bool
2161
-	 */
2162
-	public static function enforceDefaultExpireDate() {
2163
-		$enforceDefaultExpireDate = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2164
-		return ($enforceDefaultExpireDate === "yes") ? true : false;
2165
-	}
2166
-
2167
-	/**
2168
-	 * @return int
2169
-	 */
2170
-	public static function getExpireInterval() {
2171
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2172
-	}
2173
-
2174
-	/**
2175
-	 * Checks whether the given path is reachable for the given owner
2176
-	 *
2177
-	 * @param string $path path relative to files
2178
-	 * @param string $ownerStorageId storage id of the owner
2179
-	 *
2180
-	 * @return boolean true if file is reachable, false otherwise
2181
-	 */
2182
-	private static function isFileReachable($path, $ownerStorageId) {
2183
-		// if outside the home storage, file is always considered reachable
2184
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2185
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2186
-		)) {
2187
-			return true;
2188
-		}
2189
-
2190
-		// if inside the home storage, the file has to be under "/files/"
2191
-		$path = ltrim($path, '/');
2192
-		if (substr($path, 0, 6) === 'files/') {
2193
-			return true;
2194
-		}
2195
-
2196
-		return false;
2197
-	}
2198
-
2199
-	/**
2200
-	 * @param IConfig $config
2201
-	 * @return bool
2202
-	 */
2203
-	public static function enforcePassword(IConfig $config) {
2204
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2205
-		return ($enforcePassword === "yes") ? true : false;
2206
-	}
2207
-
2208
-	/**
2209
-	 * Get all share entries, including non-unique group items
2210
-	 *
2211
-	 * @param string $owner
2212
-	 * @return array
2213
-	 */
2214
-	public static function getAllSharesForOwner($owner) {
2215
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2216
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2217
-		return $result->fetchAll();
2218
-	}
2219
-
2220
-	/**
2221
-	 * Get all share entries, including non-unique group items for a file
2222
-	 *
2223
-	 * @param int $id
2224
-	 * @return array
2225
-	 */
2226
-	public static function getAllSharesForFileId($id) {
2227
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2228
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2229
-		return $result->fetchAll();
2230
-	}
2231
-
2232
-	/**
2233
-	 * @param string $password
2234
-	 * @throws \Exception
2235
-	 */
2236
-	private static function verifyPassword($password) {
2237
-
2238
-		$accepted = true;
2239
-		$message = '';
2240
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2241
-			'password' => $password,
2242
-			'accepted' => &$accepted,
2243
-			'message' => &$message
2244
-		]);
2245
-
2246
-		if (!$accepted) {
2247
-			throw new \Exception($message);
2248
-		}
2249
-	}
731
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
732
+
733
+        if($result === false) {
734
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
735
+        }
736
+    }
737
+
738
+    /**
739
+     * validate expiration date if it meets all constraints
740
+     *
741
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
742
+     * @param string $shareTime timestamp when the file was shared
743
+     * @param string $itemType
744
+     * @param string $itemSource
745
+     * @return \DateTime validated date
746
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
747
+     */
748
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
749
+        $l = \OC::$server->getL10N('lib');
750
+        $date = new \DateTime($expireDate);
751
+        $today = new \DateTime('now');
752
+
753
+        // if the user doesn't provide a share time we need to get it from the database
754
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
755
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
756
+        if ($defaultExpireDateEnforced && $shareTime === null) {
757
+            $items = self::getItemShared($itemType, $itemSource);
758
+            $firstItem = reset($items);
759
+            $shareTime = (int)$firstItem['stime'];
760
+        }
761
+
762
+        if ($defaultExpireDateEnforced) {
763
+            // initialize max date with share time
764
+            $maxDate = new \DateTime();
765
+            $maxDate->setTimestamp($shareTime);
766
+            $maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
767
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
768
+            if ($date > $maxDate) {
769
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
770
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
771
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
772
+                throw new \Exception($warning_t);
773
+            }
774
+        }
775
+
776
+        if ($date < $today) {
777
+            $message = 'Cannot set expiration date. Expiration date is in the past';
778
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
779
+            \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
780
+            throw new \Exception($message_t);
781
+        }
782
+
783
+        return $date;
784
+    }
785
+
786
+    /**
787
+     * Retrieve the owner of a connection
788
+     *
789
+     * @param IDBConnection $connection
790
+     * @param int $shareId
791
+     * @throws \Exception
792
+     * @return string uid of share owner
793
+     */
794
+    private static function getShareOwner(IDBConnection $connection, $shareId) {
795
+        $qb = $connection->getQueryBuilder();
796
+
797
+        $qb->select('uid_owner')
798
+            ->from('share')
799
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
800
+            ->setParameter(':shareId', $shareId);
801
+        $dbResult = $qb->execute();
802
+        $result = $dbResult->fetch();
803
+        $dbResult->closeCursor();
804
+
805
+        if (empty($result)) {
806
+            throw new \Exception('Share not found');
807
+        }
808
+
809
+        return $result['uid_owner'];
810
+    }
811
+
812
+    /**
813
+     * Set password for a public link share
814
+     *
815
+     * @param IUserSession $userSession
816
+     * @param IDBConnection $connection
817
+     * @param IConfig $config
818
+     * @param int $shareId
819
+     * @param string $password
820
+     * @throws \Exception
821
+     * @return boolean
822
+     */
823
+    public static function setPassword(IUserSession $userSession,
824
+                                        IDBConnection $connection,
825
+                                        IConfig $config,
826
+                                        $shareId, $password) {
827
+        $user = $userSession->getUser();
828
+        if (is_null($user)) {
829
+            throw new \Exception("User not logged in");
830
+        }
831
+
832
+        $uid = self::getShareOwner($connection, $shareId);
833
+
834
+        if ($uid !== $user->getUID()) {
835
+            throw new \Exception('Cannot update share of a different user');
836
+        }
837
+
838
+        if ($password === '') {
839
+            $password = null;
840
+        }
841
+
842
+        //If passwords are enforced the password can't be null
843
+        if (self::enforcePassword($config) && is_null($password)) {
844
+            throw new \Exception('Cannot remove password');
845
+        }
846
+
847
+        self::verifyPassword($password);
848
+
849
+        $qb = $connection->getQueryBuilder();
850
+        $qb->update('share')
851
+            ->set('share_with', $qb->createParameter('pass'))
852
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
853
+            ->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
854
+            ->setParameter(':shareId', $shareId);
855
+
856
+        $qb->execute();
857
+
858
+        return true;
859
+    }
860
+
861
+    /**
862
+     * Checks whether a share has expired, calls unshareItem() if yes.
863
+     * @param array $item Share data (usually database row)
864
+     * @return boolean True if item was expired, false otherwise.
865
+     */
866
+    protected static function expireItem(array $item) {
867
+
868
+        $result = false;
869
+
870
+        // only use default expiration date for link shares
871
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
872
+
873
+            // calculate expiration date
874
+            if (!empty($item['expiration'])) {
875
+                $userDefinedExpire = new \DateTime($item['expiration']);
876
+                $expires = $userDefinedExpire->getTimestamp();
877
+            } else {
878
+                $expires = null;
879
+            }
880
+
881
+
882
+            // get default expiration settings
883
+            $defaultSettings = Helper::getDefaultExpireSetting();
884
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
885
+
886
+
887
+            if (is_int($expires)) {
888
+                $now = time();
889
+                if ($now > $expires) {
890
+                    self::unshareItem($item);
891
+                    $result = true;
892
+                }
893
+            }
894
+        }
895
+        return $result;
896
+    }
897
+
898
+    /**
899
+     * Unshares a share given a share data array
900
+     * @param array $item Share data (usually database row)
901
+     * @param int $newParent parent ID
902
+     * @return null
903
+     */
904
+    protected static function unshareItem(array $item, $newParent = null) {
905
+
906
+        $shareType = (int)$item['share_type'];
907
+        $shareWith = null;
908
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
909
+            $shareWith = $item['share_with'];
910
+        }
911
+
912
+        // Pass all the vars we have for now, they may be useful
913
+        $hookParams = array(
914
+            'id'            => $item['id'],
915
+            'itemType'      => $item['item_type'],
916
+            'itemSource'    => $item['item_source'],
917
+            'shareType'     => $shareType,
918
+            'shareWith'     => $shareWith,
919
+            'itemParent'    => $item['parent'],
920
+            'uidOwner'      => $item['uid_owner'],
921
+        );
922
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
923
+            $hookParams['fileSource'] = $item['file_source'];
924
+            $hookParams['fileTarget'] = $item['file_target'];
925
+        }
926
+
927
+        \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
928
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
929
+        $deletedShares[] = $hookParams;
930
+        $hookParams['deletedShares'] = $deletedShares;
931
+        \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
932
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
933
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
934
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
935
+        }
936
+    }
937
+
938
+    /**
939
+     * Get the backend class for the specified item type
940
+     * @param string $itemType
941
+     * @throws \Exception
942
+     * @return \OCP\Share_Backend
943
+     */
944
+    public static function getBackend($itemType) {
945
+        $l = \OC::$server->getL10N('lib');
946
+        if (isset(self::$backends[$itemType])) {
947
+            return self::$backends[$itemType];
948
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
949
+            $class = self::$backendTypes[$itemType]['class'];
950
+            if (class_exists($class)) {
951
+                self::$backends[$itemType] = new $class;
952
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
953
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
954
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
955
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
956
+                    throw new \Exception($message_t);
957
+                }
958
+                return self::$backends[$itemType];
959
+            } else {
960
+                $message = 'Sharing backend %s not found';
961
+                $message_t = $l->t('Sharing backend %s not found', array($class));
962
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
963
+                throw new \Exception($message_t);
964
+            }
965
+        }
966
+        $message = 'Sharing backend for %s not found';
967
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
968
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
969
+        throw new \Exception($message_t);
970
+    }
971
+
972
+    /**
973
+     * Check if resharing is allowed
974
+     * @return boolean true if allowed or false
975
+     *
976
+     * Resharing is allowed by default if not configured
977
+     */
978
+    public static function isResharingAllowed() {
979
+        if (!isset(self::$isResharingAllowed)) {
980
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
981
+                self::$isResharingAllowed = true;
982
+            } else {
983
+                self::$isResharingAllowed = false;
984
+            }
985
+        }
986
+        return self::$isResharingAllowed;
987
+    }
988
+
989
+    /**
990
+     * Get a list of collection item types for the specified item type
991
+     * @param string $itemType
992
+     * @return array
993
+     */
994
+    private static function getCollectionItemTypes($itemType) {
995
+        $collectionTypes = array($itemType);
996
+        foreach (self::$backendTypes as $type => $backend) {
997
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
998
+                $collectionTypes[] = $type;
999
+            }
1000
+        }
1001
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1002
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1003
+            unset($collectionTypes[0]);
1004
+        }
1005
+        // Return array if collections were found or the item type is a
1006
+        // collection itself - collections can be inside collections
1007
+        if (count($collectionTypes) > 0) {
1008
+            return $collectionTypes;
1009
+        }
1010
+        return false;
1011
+    }
1012
+
1013
+    /**
1014
+     * Get the owners of items shared with a user.
1015
+     *
1016
+     * @param string $user The user the items are shared with.
1017
+     * @param string $type The type of the items shared with the user.
1018
+     * @param boolean $includeCollections Include collection item types (optional)
1019
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1020
+     * @return array
1021
+     */
1022
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1023
+        // First, we find out if $type is part of a collection (and if that collection is part of
1024
+        // another one and so on).
1025
+        $collectionTypes = array();
1026
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1027
+            $collectionTypes[] = $type;
1028
+        }
1029
+
1030
+        // Of these collection types, along with our original $type, we make a
1031
+        // list of the ones for which a sharing backend has been registered.
1032
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1033
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1034
+        $allMaybeSharedItems = array();
1035
+        foreach ($collectionTypes as $collectionType) {
1036
+            if (isset(self::$backends[$collectionType])) {
1037
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1038
+                    $collectionType,
1039
+                    $user,
1040
+                    self::FORMAT_NONE
1041
+                );
1042
+            }
1043
+        }
1044
+
1045
+        $owners = array();
1046
+        if ($includeOwner) {
1047
+            $owners[] = $user;
1048
+        }
1049
+
1050
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
1051
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
1052
+        // and return them as elements of a list that look like "Tag (owner)".
1053
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1054
+            foreach ($maybeSharedItems as $sharedItem) {
1055
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1056
+                    $owners[] = $sharedItem['uid_owner'];
1057
+                }
1058
+            }
1059
+        }
1060
+
1061
+        return $owners;
1062
+    }
1063
+
1064
+    /**
1065
+     * Get shared items from the database
1066
+     * @param string $itemType
1067
+     * @param string $item Item source or target (optional)
1068
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1069
+     * @param string $shareWith User or group the item is being shared with
1070
+     * @param string $uidOwner User that is the owner of shared items (optional)
1071
+     * @param int $format Format to convert items to with formatItems() (optional)
1072
+     * @param mixed $parameters to pass to formatItems() (optional)
1073
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
1074
+     * @param boolean $includeCollections Include collection item types (optional)
1075
+     * @param boolean $itemShareWithBySource (optional)
1076
+     * @param boolean $checkExpireDate
1077
+     * @return array
1078
+     *
1079
+     * See public functions getItem(s)... for parameter usage
1080
+     *
1081
+     */
1082
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1083
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1084
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1085
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
1086
+            return array();
1087
+        }
1088
+        $backend = self::getBackend($itemType);
1089
+        $collectionTypes = false;
1090
+        // Get filesystem root to add it to the file target and remove from the
1091
+        // file source, match file_source with the file cache
1092
+        if ($itemType == 'file' || $itemType == 'folder') {
1093
+            if(!is_null($uidOwner)) {
1094
+                $root = \OC\Files\Filesystem::getRoot();
1095
+            } else {
1096
+                $root = '';
1097
+            }
1098
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1099
+            if (!isset($item)) {
1100
+                $where .= ' AND `file_target` IS NOT NULL ';
1101
+            }
1102
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1103
+            $fileDependent = true;
1104
+            $queryArgs = array();
1105
+        } else {
1106
+            $fileDependent = false;
1107
+            $root = '';
1108
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1109
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1110
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1111
+                if (!in_array($itemType, $collectionTypes)) {
1112
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1113
+                } else {
1114
+                    $itemTypes = $collectionTypes;
1115
+                }
1116
+                $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1117
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1118
+                $queryArgs = $itemTypes;
1119
+            } else {
1120
+                $where = ' WHERE `item_type` = ?';
1121
+                $queryArgs = array($itemType);
1122
+            }
1123
+        }
1124
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1125
+            $where .= ' AND `share_type` != ?';
1126
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1127
+        }
1128
+        if (isset($shareType)) {
1129
+            // Include all user and group items
1130
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1131
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1132
+                $queryArgs[] = self::SHARE_TYPE_USER;
1133
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1134
+                $queryArgs[] = $shareWith;
1135
+
1136
+                $user = \OC::$server->getUserManager()->get($shareWith);
1137
+                $groups = [];
1138
+                if ($user) {
1139
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1140
+                }
1141
+                if (!empty($groups)) {
1142
+                    $placeholders = join(',', array_fill(0, count($groups), '?'));
1143
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1144
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1145
+                    $queryArgs = array_merge($queryArgs, $groups);
1146
+                }
1147
+                $where .= ')';
1148
+                // Don't include own group shares
1149
+                $where .= ' AND `uid_owner` != ?';
1150
+                $queryArgs[] = $shareWith;
1151
+            } else {
1152
+                $where .= ' AND `share_type` = ?';
1153
+                $queryArgs[] = $shareType;
1154
+                if (isset($shareWith)) {
1155
+                    $where .= ' AND `share_with` = ?';
1156
+                    $queryArgs[] = $shareWith;
1157
+                }
1158
+            }
1159
+        }
1160
+        if (isset($uidOwner)) {
1161
+            $where .= ' AND `uid_owner` = ?';
1162
+            $queryArgs[] = $uidOwner;
1163
+            if (!isset($shareType)) {
1164
+                // Prevent unique user targets for group shares from being selected
1165
+                $where .= ' AND `share_type` != ?';
1166
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1167
+            }
1168
+            if ($fileDependent) {
1169
+                $column = 'file_source';
1170
+            } else {
1171
+                $column = 'item_source';
1172
+            }
1173
+        } else {
1174
+            if ($fileDependent) {
1175
+                $column = 'file_target';
1176
+            } else {
1177
+                $column = 'item_target';
1178
+            }
1179
+        }
1180
+        if (isset($item)) {
1181
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1182
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1183
+                $where .= ' AND (';
1184
+            } else {
1185
+                $where .= ' AND';
1186
+            }
1187
+            // If looking for own shared items, check item_source else check item_target
1188
+            if (isset($uidOwner) || $itemShareWithBySource) {
1189
+                // If item type is a file, file source needs to be checked in case the item was converted
1190
+                if ($fileDependent) {
1191
+                    $where .= ' `file_source` = ?';
1192
+                    $column = 'file_source';
1193
+                } else {
1194
+                    $where .= ' `item_source` = ?';
1195
+                    $column = 'item_source';
1196
+                }
1197
+            } else {
1198
+                if ($fileDependent) {
1199
+                    $where .= ' `file_target` = ?';
1200
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1201
+                } else {
1202
+                    $where .= ' `item_target` = ?';
1203
+                }
1204
+            }
1205
+            $queryArgs[] = $item;
1206
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1207
+                $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1208
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1209
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1210
+            }
1211
+        }
1212
+
1213
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1214
+            // Make sure the unique user target is returned if it exists,
1215
+            // unique targets should follow the group share in the database
1216
+            // If the limit is not 1, the filtering can be done later
1217
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1218
+        } else {
1219
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1220
+        }
1221
+
1222
+        if ($limit != -1 && !$includeCollections) {
1223
+            // The limit must be at least 3, because filtering needs to be done
1224
+            if ($limit < 3) {
1225
+                $queryLimit = 3;
1226
+            } else {
1227
+                $queryLimit = $limit;
1228
+            }
1229
+        } else {
1230
+            $queryLimit = null;
1231
+        }
1232
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1233
+        $root = strlen($root);
1234
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1235
+        $result = $query->execute($queryArgs);
1236
+        if ($result === false) {
1237
+            \OCP\Util::writeLog('OCP\Share',
1238
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1239
+                \OCP\Util::ERROR);
1240
+        }
1241
+        $items = array();
1242
+        $targets = array();
1243
+        $switchedItems = array();
1244
+        $mounts = array();
1245
+        while ($row = $result->fetchRow()) {
1246
+            self::transformDBResults($row);
1247
+            // Filter out duplicate group shares for users with unique targets
1248
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1249
+                continue;
1250
+            }
1251
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1252
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1253
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1254
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1255
+                // if the group share was unshared from the user we keep the permission, otherwise
1256
+                // we take the permission from the parent because this is always the up-to-date
1257
+                // permission for the group share
1258
+                if ($row['permissions'] > 0) {
1259
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1260
+                }
1261
+                // Remove the parent group share
1262
+                unset($items[$row['parent']]);
1263
+                if ($row['permissions'] == 0) {
1264
+                    continue;
1265
+                }
1266
+            } else if (!isset($uidOwner)) {
1267
+                // Check if the same target already exists
1268
+                if (isset($targets[$row['id']])) {
1269
+                    // Check if the same owner shared with the user twice
1270
+                    // through a group and user share - this is allowed
1271
+                    $id = $targets[$row['id']];
1272
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1273
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1274
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1275
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1276
+                            $items[$id]['share_with'] = $row['share_with'];
1277
+                        }
1278
+                        // Switch ids if sharing permission is granted on only
1279
+                        // one share to ensure correct parent is used if resharing
1280
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1281
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1282
+                            $items[$row['id']] = $items[$id];
1283
+                            $switchedItems[$id] = $row['id'];
1284
+                            unset($items[$id]);
1285
+                            $id = $row['id'];
1286
+                        }
1287
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1288
+
1289
+                    }
1290
+                    continue;
1291
+                } elseif (!empty($row['parent'])) {
1292
+                    $targets[$row['parent']] = $row['id'];
1293
+                }
1294
+            }
1295
+            // Remove root from file source paths if retrieving own shared items
1296
+            if (isset($uidOwner) && isset($row['path'])) {
1297
+                if (isset($row['parent'])) {
1298
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1299
+                    $parentResult = $query->execute(array($row['parent']));
1300
+                    if ($result === false) {
1301
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1302
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1303
+                            \OCP\Util::ERROR);
1304
+                    } else {
1305
+                        $parentRow = $parentResult->fetchRow();
1306
+                        $tmpPath = $parentRow['file_target'];
1307
+                        // find the right position where the row path continues from the target path
1308
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1309
+                        $subPath = substr($row['path'], $pos);
1310
+                        $splitPath = explode('/', $subPath);
1311
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1312
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1313
+                        }
1314
+                        $row['path'] = $tmpPath;
1315
+                    }
1316
+                } else {
1317
+                    if (!isset($mounts[$row['storage']])) {
1318
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1319
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1320
+                            $mounts[$row['storage']] = current($mountPoints);
1321
+                        }
1322
+                    }
1323
+                    if (!empty($mounts[$row['storage']])) {
1324
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1325
+                        $relPath = substr($path, $root); // path relative to data/user
1326
+                        $row['path'] = rtrim($relPath, '/');
1327
+                    }
1328
+                }
1329
+            }
1330
+
1331
+            if($checkExpireDate) {
1332
+                if (self::expireItem($row)) {
1333
+                    continue;
1334
+                }
1335
+            }
1336
+            // Check if resharing is allowed, if not remove share permission
1337
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1338
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1339
+            }
1340
+            // Add display names to result
1341
+            $row['share_with_displayname'] = $row['share_with'];
1342
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
1343
+                $row['share_type'] === self::SHARE_TYPE_USER) {
1344
+                $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
1345
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
1346
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
1347
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1348
+                foreach ($addressBookEntries as $entry) {
1349
+                    foreach ($entry['CLOUD'] as $cloudID) {
1350
+                        if ($cloudID === $row['share_with']) {
1351
+                            $row['share_with_displayname'] = $entry['FN'];
1352
+                        }
1353
+                    }
1354
+                }
1355
+            }
1356
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1357
+                $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
1358
+            }
1359
+
1360
+            if ($row['permissions'] > 0) {
1361
+                $items[$row['id']] = $row;
1362
+            }
1363
+
1364
+        }
1365
+
1366
+        // group items if we are looking for items shared with the current user
1367
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1368
+            $items = self::groupItems($items, $itemType);
1369
+        }
1370
+
1371
+        if (!empty($items)) {
1372
+            $collectionItems = array();
1373
+            foreach ($items as &$row) {
1374
+                // Return only the item instead of a 2-dimensional array
1375
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1376
+                    if ($format == self::FORMAT_NONE) {
1377
+                        return $row;
1378
+                    } else {
1379
+                        break;
1380
+                    }
1381
+                }
1382
+                // Check if this is a collection of the requested item type
1383
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1384
+                    if (($collectionBackend = self::getBackend($row['item_type']))
1385
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1386
+                        // Collections can be inside collections, check if the item is a collection
1387
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1388
+                            $collectionItems[] = $row;
1389
+                        } else {
1390
+                            $collection = array();
1391
+                            $collection['item_type'] = $row['item_type'];
1392
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1393
+                                $collection['path'] = basename($row['path']);
1394
+                            }
1395
+                            $row['collection'] = $collection;
1396
+                            // Fetch all of the children sources
1397
+                            $children = $collectionBackend->getChildren($row[$column]);
1398
+                            foreach ($children as $child) {
1399
+                                $childItem = $row;
1400
+                                $childItem['item_type'] = $itemType;
1401
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1402
+                                    $childItem['item_source'] = $child['source'];
1403
+                                    $childItem['item_target'] = $child['target'];
1404
+                                }
1405
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1406
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1407
+                                        $childItem['file_source'] = $child['source'];
1408
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
1409
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1410
+                                        $childItem['file_source'] = $meta['fileid'];
1411
+                                    }
1412
+                                    $childItem['file_target'] =
1413
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
1414
+                                }
1415
+                                if (isset($item)) {
1416
+                                    if ($childItem[$column] == $item) {
1417
+                                        // Return only the item instead of a 2-dimensional array
1418
+                                        if ($limit == 1) {
1419
+                                            if ($format == self::FORMAT_NONE) {
1420
+                                                return $childItem;
1421
+                                            } else {
1422
+                                                // Unset the items array and break out of both loops
1423
+                                                $items = array();
1424
+                                                $items[] = $childItem;
1425
+                                                break 2;
1426
+                                            }
1427
+                                        } else {
1428
+                                            $collectionItems[] = $childItem;
1429
+                                        }
1430
+                                    }
1431
+                                } else {
1432
+                                    $collectionItems[] = $childItem;
1433
+                                }
1434
+                            }
1435
+                        }
1436
+                    }
1437
+                    // Remove collection item
1438
+                    $toRemove = $row['id'];
1439
+                    if (array_key_exists($toRemove, $switchedItems)) {
1440
+                        $toRemove = $switchedItems[$toRemove];
1441
+                    }
1442
+                    unset($items[$toRemove]);
1443
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1444
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
1445
+                    // see github issue #10588 for more details
1446
+                    // Need to find a solution which works for all back-ends
1447
+                    $collectionBackend = self::getBackend($row['item_type']);
1448
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
1449
+                    foreach ($sharedParents as $parent) {
1450
+                        $collectionItems[] = $parent;
1451
+                    }
1452
+                }
1453
+            }
1454
+            if (!empty($collectionItems)) {
1455
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
1456
+                $items = array_merge($items, $collectionItems);
1457
+            }
1458
+
1459
+            // filter out invalid items, these can appear when subshare entries exist
1460
+            // for a group in which the requested user isn't a member any more
1461
+            $items = array_filter($items, function($item) {
1462
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1463
+            });
1464
+
1465
+            return self::formatResult($items, $column, $backend, $format, $parameters);
1466
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1467
+            // FIXME: Thats a dirty hack to improve file sharing performance,
1468
+            // see github issue #10588 for more details
1469
+            // Need to find a solution which works for all back-ends
1470
+            $collectionItems = array();
1471
+            $collectionBackend = self::getBackend('folder');
1472
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1473
+            foreach ($sharedParents as $parent) {
1474
+                $collectionItems[] = $parent;
1475
+            }
1476
+            if ($limit === 1) {
1477
+                return reset($collectionItems);
1478
+            }
1479
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1480
+        }
1481
+
1482
+        return array();
1483
+    }
1484
+
1485
+    /**
1486
+     * group items with link to the same source
1487
+     *
1488
+     * @param array $items
1489
+     * @param string $itemType
1490
+     * @return array of grouped items
1491
+     */
1492
+    protected static function groupItems($items, $itemType) {
1493
+
1494
+        $fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
1495
+
1496
+        $result = array();
1497
+
1498
+        foreach ($items as $item) {
1499
+            $grouped = false;
1500
+            foreach ($result as $key => $r) {
1501
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1502
+                // only group shares if they already point to the same target, otherwise the file where shared
1503
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1504
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1505
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1506
+                    // add the first item to the list of grouped shares
1507
+                    if (!isset($result[$key]['grouped'])) {
1508
+                        $result[$key]['grouped'][] = $result[$key];
1509
+                    }
1510
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1511
+                    $result[$key]['grouped'][] = $item;
1512
+                    $grouped = true;
1513
+                    break;
1514
+                }
1515
+            }
1516
+
1517
+            if (!$grouped) {
1518
+                $result[] = $item;
1519
+            }
1520
+
1521
+        }
1522
+
1523
+        return $result;
1524
+    }
1525
+
1526
+    /**
1527
+     * Put shared item into the database
1528
+     * @param string $itemType Item type
1529
+     * @param string $itemSource Item source
1530
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1531
+     * @param string $shareWith User or group the item is being shared with
1532
+     * @param string $uidOwner User that is the owner of shared item
1533
+     * @param int $permissions CRUDS permissions
1534
+     * @param boolean|array $parentFolder Parent folder target (optional)
1535
+     * @param string $token (optional)
1536
+     * @param string $itemSourceName name of the source item (optional)
1537
+     * @param \DateTime $expirationDate (optional)
1538
+     * @throws \Exception
1539
+     * @return mixed id of the new share or false
1540
+     */
1541
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1542
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1543
+
1544
+        $queriesToExecute = array();
1545
+        $suggestedItemTarget = null;
1546
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1547
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1548
+
1549
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1550
+        if(!empty($result)) {
1551
+            $parent = $result['parent'];
1552
+            $itemSource = $result['itemSource'];
1553
+            $fileSource = $result['fileSource'];
1554
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1555
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1556
+            $filePath = $result['filePath'];
1557
+        }
1558
+
1559
+        $isGroupShare = false;
1560
+        if ($shareType == self::SHARE_TYPE_GROUP) {
1561
+            $isGroupShare = true;
1562
+            if (isset($shareWith['users'])) {
1563
+                $users = $shareWith['users'];
1564
+            } else {
1565
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
1566
+                if ($group) {
1567
+                    $users = $group->searchUsers('', -1, 0);
1568
+                    $userIds = [];
1569
+                    foreach ($users as $user) {
1570
+                        $userIds[] = $user->getUID();
1571
+                    }
1572
+                    $users = $userIds;
1573
+                } else {
1574
+                    $users = [];
1575
+                }
1576
+            }
1577
+            // remove current user from list
1578
+            if (in_array(\OCP\User::getUser(), $users)) {
1579
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
1580
+            }
1581
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1582
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1583
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1584
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
1585
+
1586
+            // add group share to table and remember the id as parent
1587
+            $queriesToExecute['groupShare'] = array(
1588
+                'itemType'			=> $itemType,
1589
+                'itemSource'		=> $itemSource,
1590
+                'itemTarget'		=> $groupItemTarget,
1591
+                'shareType'			=> $shareType,
1592
+                'shareWith'			=> $shareWith['group'],
1593
+                'uidOwner'			=> $uidOwner,
1594
+                'permissions'		=> $permissions,
1595
+                'shareTime'			=> time(),
1596
+                'fileSource'		=> $fileSource,
1597
+                'fileTarget'		=> $groupFileTarget,
1598
+                'token'				=> $token,
1599
+                'parent'			=> $parent,
1600
+                'expiration'		=> $expirationDate,
1601
+            );
1602
+
1603
+        } else {
1604
+            $users = array($shareWith);
1605
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1606
+                $suggestedItemTarget);
1607
+        }
1608
+
1609
+        $run = true;
1610
+        $error = '';
1611
+        $preHookData = array(
1612
+            'itemType' => $itemType,
1613
+            'itemSource' => $itemSource,
1614
+            'shareType' => $shareType,
1615
+            'uidOwner' => $uidOwner,
1616
+            'permissions' => $permissions,
1617
+            'fileSource' => $fileSource,
1618
+            'expiration' => $expirationDate,
1619
+            'token' => $token,
1620
+            'run' => &$run,
1621
+            'error' => &$error
1622
+        );
1623
+
1624
+        $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1625
+        $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1626
+
1627
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
1628
+
1629
+        if ($run === false) {
1630
+            throw new \Exception($error);
1631
+        }
1632
+
1633
+        foreach ($users as $user) {
1634
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1635
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1636
+
1637
+            $userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
1638
+
1639
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1640
+                $fileTarget = $sourceExists['file_target'];
1641
+                $itemTarget = $sourceExists['item_target'];
1642
+
1643
+                // for group shares we don't need a additional entry if the target is the same
1644
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
1645
+                    continue;
1646
+                }
1647
+
1648
+            } elseif(!$sourceExists && !$isGroupShare)  {
1649
+
1650
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1651
+                    $uidOwner, $suggestedItemTarget, $parent);
1652
+                if (isset($fileSource)) {
1653
+                    if ($parentFolder) {
1654
+                        if ($parentFolder === true) {
1655
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1656
+                                $uidOwner, $suggestedFileTarget, $parent);
1657
+                            if ($fileTarget != $groupFileTarget) {
1658
+                                $parentFolders[$user]['folder'] = $fileTarget;
1659
+                            }
1660
+                        } else if (isset($parentFolder[$user])) {
1661
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
1662
+                            $parent = $parentFolder[$user]['id'];
1663
+                        }
1664
+                    } else {
1665
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1666
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1667
+                    }
1668
+                } else {
1669
+                    $fileTarget = null;
1670
+                }
1671
+
1672
+            } else {
1673
+
1674
+                // group share which doesn't exists until now, check if we need a unique target for this user
1675
+
1676
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1677
+                    $uidOwner, $suggestedItemTarget, $parent);
1678
+
1679
+                // do we also need a file target
1680
+                if (isset($fileSource)) {
1681
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1682
+                        $uidOwner, $suggestedFileTarget, $parent);
1683
+                } else {
1684
+                    $fileTarget = null;
1685
+                }
1686
+
1687
+                if (($itemTarget === $groupItemTarget) &&
1688
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1689
+                    continue;
1690
+                }
1691
+            }
1692
+
1693
+            $queriesToExecute[] = array(
1694
+                'itemType'			=> $itemType,
1695
+                'itemSource'		=> $itemSource,
1696
+                'itemTarget'		=> $itemTarget,
1697
+                'shareType'			=> $userShareType,
1698
+                'shareWith'			=> $user,
1699
+                'uidOwner'			=> $uidOwner,
1700
+                'permissions'		=> $permissions,
1701
+                'shareTime'			=> time(),
1702
+                'fileSource'		=> $fileSource,
1703
+                'fileTarget'		=> $fileTarget,
1704
+                'token'				=> $token,
1705
+                'parent'			=> $parent,
1706
+                'expiration'		=> $expirationDate,
1707
+            );
1708
+
1709
+        }
1710
+
1711
+        $id = false;
1712
+        if ($isGroupShare) {
1713
+            $id = self::insertShare($queriesToExecute['groupShare']);
1714
+            // Save this id, any extra rows for this group share will need to reference it
1715
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1716
+            unset($queriesToExecute['groupShare']);
1717
+        }
1718
+
1719
+        foreach ($queriesToExecute as $shareQuery) {
1720
+            $shareQuery['parent'] = $parent;
1721
+            $id = self::insertShare($shareQuery);
1722
+        }
1723
+
1724
+        $postHookData = array(
1725
+            'itemType' => $itemType,
1726
+            'itemSource' => $itemSource,
1727
+            'parent' => $parent,
1728
+            'shareType' => $shareType,
1729
+            'uidOwner' => $uidOwner,
1730
+            'permissions' => $permissions,
1731
+            'fileSource' => $fileSource,
1732
+            'id' => $parent,
1733
+            'token' => $token,
1734
+            'expirationDate' => $expirationDate,
1735
+        );
1736
+
1737
+        $postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1738
+        $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1739
+        $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
1740
+
1741
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
1742
+
1743
+
1744
+        return $id ? $id : false;
1745
+    }
1746
+
1747
+    /**
1748
+     * @param string $itemType
1749
+     * @param string $itemSource
1750
+     * @param int $shareType
1751
+     * @param string $shareWith
1752
+     * @param string $uidOwner
1753
+     * @param int $permissions
1754
+     * @param string|null $itemSourceName
1755
+     * @param null|\DateTime $expirationDate
1756
+     */
1757
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1758
+        $backend = self::getBackend($itemType);
1759
+
1760
+        $l = \OC::$server->getL10N('lib');
1761
+        $result = array();
1762
+
1763
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1764
+
1765
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1766
+        if ($checkReshare) {
1767
+            // Check if attempting to share back to owner
1768
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1769
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
1770
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1771
+
1772
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
1773
+                throw new \Exception($message_t);
1774
+            }
1775
+        }
1776
+
1777
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1778
+            // Check if share permissions is granted
1779
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1780
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1781
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1782
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1783
+
1784
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
1785
+                    throw new \Exception($message_t);
1786
+                } else {
1787
+                    // TODO Don't check if inside folder
1788
+                    $result['parent'] = $checkReshare['id'];
1789
+
1790
+                    $result['expirationDate'] = $expirationDate;
1791
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1792
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1793
+                        $result['expirationDate'] = $checkReshare['expiration'];
1794
+                    }
1795
+
1796
+                    // only suggest the same name as new target if it is a reshare of the
1797
+                    // same file/folder and not the reshare of a child
1798
+                    if ($checkReshare[$column] === $itemSource) {
1799
+                        $result['filePath'] = $checkReshare['file_target'];
1800
+                        $result['itemSource'] = $checkReshare['item_source'];
1801
+                        $result['fileSource'] = $checkReshare['file_source'];
1802
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1803
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1804
+                    } else {
1805
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1806
+                        $result['suggestedItemTarget'] = null;
1807
+                        $result['suggestedFileTarget'] = null;
1808
+                        $result['itemSource'] = $itemSource;
1809
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1810
+                    }
1811
+                }
1812
+            } else {
1813
+                $message = 'Sharing %s failed, because resharing is not allowed';
1814
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1815
+
1816
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
1817
+                throw new \Exception($message_t);
1818
+            }
1819
+        } else {
1820
+            $result['parent'] = null;
1821
+            $result['suggestedItemTarget'] = null;
1822
+            $result['suggestedFileTarget'] = null;
1823
+            $result['itemSource'] = $itemSource;
1824
+            $result['expirationDate'] = $expirationDate;
1825
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1826
+                $message = 'Sharing %s failed, because the sharing backend for '
1827
+                    .'%s could not find its source';
1828
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1829
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
1830
+                throw new \Exception($message_t);
1831
+            }
1832
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1833
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1834
+                if ($itemType == 'file' || $itemType == 'folder') {
1835
+                    $result['fileSource'] = $itemSource;
1836
+                } else {
1837
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1838
+                    $result['fileSource'] = $meta['fileid'];
1839
+                }
1840
+                if ($result['fileSource'] == -1) {
1841
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1842
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1843
+
1844
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1845
+                    throw new \Exception($message_t);
1846
+                }
1847
+            } else {
1848
+                $result['filePath'] = null;
1849
+                $result['fileSource'] = null;
1850
+            }
1851
+        }
1852
+
1853
+        return $result;
1854
+    }
1855
+
1856
+    /**
1857
+     *
1858
+     * @param array $shareData
1859
+     * @return mixed false in case of a failure or the id of the new share
1860
+     */
1861
+    private static function insertShare(array $shareData) {
1862
+
1863
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1864
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1865
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1866
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1867
+        $query->bindValue(1, $shareData['itemType']);
1868
+        $query->bindValue(2, $shareData['itemSource']);
1869
+        $query->bindValue(3, $shareData['itemTarget']);
1870
+        $query->bindValue(4, $shareData['shareType']);
1871
+        $query->bindValue(5, $shareData['shareWith']);
1872
+        $query->bindValue(6, $shareData['uidOwner']);
1873
+        $query->bindValue(7, $shareData['permissions']);
1874
+        $query->bindValue(8, $shareData['shareTime']);
1875
+        $query->bindValue(9, $shareData['fileSource']);
1876
+        $query->bindValue(10, $shareData['fileTarget']);
1877
+        $query->bindValue(11, $shareData['token']);
1878
+        $query->bindValue(12, $shareData['parent']);
1879
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1880
+        $result = $query->execute();
1881
+
1882
+        $id = false;
1883
+        if ($result) {
1884
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1885
+        }
1886
+
1887
+        return $id;
1888
+
1889
+    }
1890
+
1891
+    /**
1892
+     * In case a password protected link is not yet authenticated this function will return false
1893
+     *
1894
+     * @param array $linkItem
1895
+     * @return boolean
1896
+     */
1897
+    public static function checkPasswordProtectedShare(array $linkItem) {
1898
+        if (!isset($linkItem['share_with'])) {
1899
+            return true;
1900
+        }
1901
+        if (!isset($linkItem['share_type'])) {
1902
+            return true;
1903
+        }
1904
+        if (!isset($linkItem['id'])) {
1905
+            return true;
1906
+        }
1907
+
1908
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1909
+            return true;
1910
+        }
1911
+
1912
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
1913
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1914
+            return true;
1915
+        }
1916
+
1917
+        return false;
1918
+    }
1919
+
1920
+    /**
1921
+     * construct select statement
1922
+     * @param int $format
1923
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1924
+     * @param string $uidOwner
1925
+     * @return string select statement
1926
+     */
1927
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1928
+        $select = '*';
1929
+        if ($format == self::FORMAT_STATUSES) {
1930
+            if ($fileDependent) {
1931
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1932
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1933
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1934
+                    . '`uid_initiator`';
1935
+            } else {
1936
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1937
+            }
1938
+        } else {
1939
+            if (isset($uidOwner)) {
1940
+                if ($fileDependent) {
1941
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1942
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1943
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1944
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1945
+                } else {
1946
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1947
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1948
+                }
1949
+            } else {
1950
+                if ($fileDependent) {
1951
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1952
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1953
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1954
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1955
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1956
+                    } else {
1957
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1958
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1959
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1960
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1961
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1962
+                    }
1963
+                }
1964
+            }
1965
+        }
1966
+        return $select;
1967
+    }
1968
+
1969
+
1970
+    /**
1971
+     * transform db results
1972
+     * @param array $row result
1973
+     */
1974
+    private static function transformDBResults(&$row) {
1975
+        if (isset($row['id'])) {
1976
+            $row['id'] = (int) $row['id'];
1977
+        }
1978
+        if (isset($row['share_type'])) {
1979
+            $row['share_type'] = (int) $row['share_type'];
1980
+        }
1981
+        if (isset($row['parent'])) {
1982
+            $row['parent'] = (int) $row['parent'];
1983
+        }
1984
+        if (isset($row['file_parent'])) {
1985
+            $row['file_parent'] = (int) $row['file_parent'];
1986
+        }
1987
+        if (isset($row['file_source'])) {
1988
+            $row['file_source'] = (int) $row['file_source'];
1989
+        }
1990
+        if (isset($row['permissions'])) {
1991
+            $row['permissions'] = (int) $row['permissions'];
1992
+        }
1993
+        if (isset($row['storage'])) {
1994
+            $row['storage'] = (int) $row['storage'];
1995
+        }
1996
+        if (isset($row['stime'])) {
1997
+            $row['stime'] = (int) $row['stime'];
1998
+        }
1999
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2000
+            // discard expiration date for non-link shares, which might have been
2001
+            // set by ancient bugs
2002
+            $row['expiration'] = null;
2003
+        }
2004
+    }
2005
+
2006
+    /**
2007
+     * format result
2008
+     * @param array $items result
2009
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2010
+     * @param \OCP\Share_Backend $backend sharing backend
2011
+     * @param int $format
2012
+     * @param array $parameters additional format parameters
2013
+     * @return array format result
2014
+     */
2015
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2016
+        if ($format === self::FORMAT_NONE) {
2017
+            return $items;
2018
+        } else if ($format === self::FORMAT_STATUSES) {
2019
+            $statuses = array();
2020
+            foreach ($items as $item) {
2021
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2022
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2023
+                        continue;
2024
+                    }
2025
+                    $statuses[$item[$column]]['link'] = true;
2026
+                } else if (!isset($statuses[$item[$column]])) {
2027
+                    $statuses[$item[$column]]['link'] = false;
2028
+                }
2029
+                if (!empty($item['file_target'])) {
2030
+                    $statuses[$item[$column]]['path'] = $item['path'];
2031
+                }
2032
+            }
2033
+            return $statuses;
2034
+        } else {
2035
+            return $backend->formatItems($items, $format, $parameters);
2036
+        }
2037
+    }
2038
+
2039
+    /**
2040
+     * remove protocol from URL
2041
+     *
2042
+     * @param string $url
2043
+     * @return string
2044
+     */
2045
+    public static function removeProtocolFromUrl($url) {
2046
+        if (strpos($url, 'https://') === 0) {
2047
+            return substr($url, strlen('https://'));
2048
+        } else if (strpos($url, 'http://') === 0) {
2049
+            return substr($url, strlen('http://'));
2050
+        }
2051
+
2052
+        return $url;
2053
+    }
2054
+
2055
+    /**
2056
+     * try http post first with https and then with http as a fallback
2057
+     *
2058
+     * @param string $remoteDomain
2059
+     * @param string $urlSuffix
2060
+     * @param array $fields post parameters
2061
+     * @return array
2062
+     */
2063
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2064
+        $protocol = 'https://';
2065
+        $result = [
2066
+            'success' => false,
2067
+            'result' => '',
2068
+        ];
2069
+        $try = 0;
2070
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
2071
+        while ($result['success'] === false && $try < 2) {
2072
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2073
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2074
+            $result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2075
+            $try++;
2076
+            $protocol = 'http://';
2077
+        }
2078
+
2079
+        return $result;
2080
+    }
2081
+
2082
+    /**
2083
+     * send server-to-server share to remote server
2084
+     *
2085
+     * @param string $token
2086
+     * @param string $shareWith
2087
+     * @param string $name
2088
+     * @param int $remote_id
2089
+     * @param string $owner
2090
+     * @return bool
2091
+     */
2092
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2093
+
2094
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2095
+
2096
+        if ($user && $remote) {
2097
+            $url = $remote;
2098
+
2099
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2100
+
2101
+            $fields = array(
2102
+                'shareWith' => $user,
2103
+                'token' => $token,
2104
+                'name' => $name,
2105
+                'remoteId' => $remote_id,
2106
+                'owner' => $owner,
2107
+                'remote' => $local,
2108
+            );
2109
+
2110
+            $url = self::removeProtocolFromUrl($url);
2111
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2112
+            $status = json_decode($result['result'], true);
2113
+
2114
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2115
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2116
+                return true;
2117
+            }
2118
+
2119
+        }
2120
+
2121
+        return false;
2122
+    }
2123
+
2124
+    /**
2125
+     * send server-to-server unshare to remote server
2126
+     *
2127
+     * @param string $remote url
2128
+     * @param int $id share id
2129
+     * @param string $token
2130
+     * @return bool
2131
+     */
2132
+    private static function sendRemoteUnshare($remote, $id, $token) {
2133
+        $url = rtrim($remote, '/');
2134
+        $fields = array('token' => $token, 'format' => 'json');
2135
+        $url = self::removeProtocolFromUrl($url);
2136
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2137
+        $status = json_decode($result['result'], true);
2138
+
2139
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2140
+    }
2141
+
2142
+    /**
2143
+     * check if user can only share with group members
2144
+     * @return bool
2145
+     */
2146
+    public static function shareWithGroupMembersOnly() {
2147
+        $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2148
+        return ($value === 'yes') ? true : false;
2149
+    }
2150
+
2151
+    /**
2152
+     * @return bool
2153
+     */
2154
+    public static function isDefaultExpireDateEnabled() {
2155
+        $defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2156
+        return ($defaultExpireDateEnabled === "yes") ? true : false;
2157
+    }
2158
+
2159
+    /**
2160
+     * @return bool
2161
+     */
2162
+    public static function enforceDefaultExpireDate() {
2163
+        $enforceDefaultExpireDate = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2164
+        return ($enforceDefaultExpireDate === "yes") ? true : false;
2165
+    }
2166
+
2167
+    /**
2168
+     * @return int
2169
+     */
2170
+    public static function getExpireInterval() {
2171
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2172
+    }
2173
+
2174
+    /**
2175
+     * Checks whether the given path is reachable for the given owner
2176
+     *
2177
+     * @param string $path path relative to files
2178
+     * @param string $ownerStorageId storage id of the owner
2179
+     *
2180
+     * @return boolean true if file is reachable, false otherwise
2181
+     */
2182
+    private static function isFileReachable($path, $ownerStorageId) {
2183
+        // if outside the home storage, file is always considered reachable
2184
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2185
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2186
+        )) {
2187
+            return true;
2188
+        }
2189
+
2190
+        // if inside the home storage, the file has to be under "/files/"
2191
+        $path = ltrim($path, '/');
2192
+        if (substr($path, 0, 6) === 'files/') {
2193
+            return true;
2194
+        }
2195
+
2196
+        return false;
2197
+    }
2198
+
2199
+    /**
2200
+     * @param IConfig $config
2201
+     * @return bool
2202
+     */
2203
+    public static function enforcePassword(IConfig $config) {
2204
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2205
+        return ($enforcePassword === "yes") ? true : false;
2206
+    }
2207
+
2208
+    /**
2209
+     * Get all share entries, including non-unique group items
2210
+     *
2211
+     * @param string $owner
2212
+     * @return array
2213
+     */
2214
+    public static function getAllSharesForOwner($owner) {
2215
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2216
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2217
+        return $result->fetchAll();
2218
+    }
2219
+
2220
+    /**
2221
+     * Get all share entries, including non-unique group items for a file
2222
+     *
2223
+     * @param int $id
2224
+     * @return array
2225
+     */
2226
+    public static function getAllSharesForFileId($id) {
2227
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2228
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2229
+        return $result->fetchAll();
2230
+    }
2231
+
2232
+    /**
2233
+     * @param string $password
2234
+     * @throws \Exception
2235
+     */
2236
+    private static function verifyPassword($password) {
2237
+
2238
+        $accepted = true;
2239
+        $message = '';
2240
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2241
+            'password' => $password,
2242
+            'accepted' => &$accepted,
2243
+            'message' => &$message
2244
+        ]);
2245
+
2246
+        if (!$accepted) {
2247
+            throw new \Exception($message);
2248
+        }
2249
+    }
2250 2250
 }
Please login to merge, or discard this patch.
lib/private/legacy/util.php 1 patch
Indentation   +1455 added lines, -1455 removed lines patch added patch discarded remove patch
@@ -65,1463 +65,1463 @@
 block discarded – undo
65 65
 use OCP\IUser;
66 66
 
67 67
 class OC_Util {
68
-	public static $scripts = array();
69
-	public static $styles = array();
70
-	public static $headers = array();
71
-	private static $rootMounted = false;
72
-	private static $fsSetup = false;
73
-
74
-	/** @var array Local cache of version.php */
75
-	private static $versionCache = null;
76
-
77
-	protected static function getAppManager() {
78
-		return \OC::$server->getAppManager();
79
-	}
80
-
81
-	private static function initLocalStorageRootFS() {
82
-		// mount local file backend as root
83
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
84
-		//first set up the local "root" storage
85
-		\OC\Files\Filesystem::initMountManager();
86
-		if (!self::$rootMounted) {
87
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
88
-			self::$rootMounted = true;
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * mounting an object storage as the root fs will in essence remove the
94
-	 * necessity of a data folder being present.
95
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
96
-	 *
97
-	 * @param array $config containing 'class' and optional 'arguments'
98
-	 * @suppress PhanDeprecatedFunction
99
-	 */
100
-	private static function initObjectStoreRootFS($config) {
101
-		// check misconfiguration
102
-		if (empty($config['class'])) {
103
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
104
-		}
105
-		if (!isset($config['arguments'])) {
106
-			$config['arguments'] = array();
107
-		}
108
-
109
-		// instantiate object store implementation
110
-		$name = $config['class'];
111
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
112
-			$segments = explode('\\', $name);
113
-			OC_App::loadApp(strtolower($segments[1]));
114
-		}
115
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
116
-		// mount with plain / root object store implementation
117
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
118
-
119
-		// mount object storage as root
120
-		\OC\Files\Filesystem::initMountManager();
121
-		if (!self::$rootMounted) {
122
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
123
-			self::$rootMounted = true;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * mounting an object storage as the root fs will in essence remove the
129
-	 * necessity of a data folder being present.
130
-	 *
131
-	 * @param array $config containing 'class' and optional 'arguments'
132
-	 * @suppress PhanDeprecatedFunction
133
-	 */
134
-	private static function initObjectStoreMultibucketRootFS($config) {
135
-		// check misconfiguration
136
-		if (empty($config['class'])) {
137
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
138
-		}
139
-		if (!isset($config['arguments'])) {
140
-			$config['arguments'] = array();
141
-		}
142
-
143
-		// instantiate object store implementation
144
-		$name = $config['class'];
145
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
146
-			$segments = explode('\\', $name);
147
-			OC_App::loadApp(strtolower($segments[1]));
148
-		}
149
-
150
-		if (!isset($config['arguments']['bucket'])) {
151
-			$config['arguments']['bucket'] = '';
152
-		}
153
-		// put the root FS always in first bucket for multibucket configuration
154
-		$config['arguments']['bucket'] .= '0';
155
-
156
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
157
-		// mount with plain / root object store implementation
158
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
159
-
160
-		// mount object storage as root
161
-		\OC\Files\Filesystem::initMountManager();
162
-		if (!self::$rootMounted) {
163
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
164
-			self::$rootMounted = true;
165
-		}
166
-	}
167
-
168
-	/**
169
-	 * Can be set up
170
-	 *
171
-	 * @param string $user
172
-	 * @return boolean
173
-	 * @description configure the initial filesystem based on the configuration
174
-	 * @suppress PhanDeprecatedFunction
175
-	 * @suppress PhanAccessMethodInternal
176
-	 */
177
-	public static function setupFS($user = '') {
178
-		//setting up the filesystem twice can only lead to trouble
179
-		if (self::$fsSetup) {
180
-			return false;
181
-		}
182
-
183
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
184
-
185
-		// If we are not forced to load a specific user we load the one that is logged in
186
-		if ($user === null) {
187
-			$user = '';
188
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
189
-			$user = OC_User::getUser();
190
-		}
191
-
192
-		// load all filesystem apps before, so no setup-hook gets lost
193
-		OC_App::loadApps(array('filesystem'));
194
-
195
-		// the filesystem will finish when $user is not empty,
196
-		// mark fs setup here to avoid doing the setup from loading
197
-		// OC_Filesystem
198
-		if ($user != '') {
199
-			self::$fsSetup = true;
200
-		}
201
-
202
-		\OC\Files\Filesystem::initMountManager();
203
-
204
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207
-				/** @var \OC\Files\Storage\Common $storage */
208
-				$storage->setMountOptions($mount->getOptions());
209
-			}
210
-			return $storage;
211
-		});
212
-
213
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
-			if (!$mount->getOption('enable_sharing', true)) {
215
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
216
-					'storage' => $storage,
217
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
218
-				]);
219
-			}
220
-			return $storage;
221
-		});
222
-
223
-		// install storage availability wrapper, before most other wrappers
224
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227
-			}
228
-			return $storage;
229
-		});
230
-
231
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234
-			}
235
-			return $storage;
236
-		});
237
-
238
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
239
-			// set up quota for home storages, even for other users
240
-			// which can happen when using sharing
241
-
242
-			/**
243
-			 * @var \OC\Files\Storage\Storage $storage
244
-			 */
245
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
246
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
247
-			) {
248
-				/** @var \OC\Files\Storage\Home $storage */
249
-				if (is_object($storage->getUser())) {
250
-					$user = $storage->getUser()->getUID();
251
-					$quota = OC_Util::getUserQuota($user);
252
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
254
-					}
255
-				}
256
-			}
257
-
258
-			return $storage;
259
-		});
260
-
261
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
262
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
263
-
264
-		//check if we are using an object storage
265
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
266
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
267
-
268
-		// use the same order as in ObjectHomeMountProvider
269
-		if (isset($objectStoreMultibucket)) {
270
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
271
-		} elseif (isset($objectStore)) {
272
-			self::initObjectStoreRootFS($objectStore);
273
-		} else {
274
-			self::initLocalStorageRootFS();
275
-		}
276
-
277
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
278
-			\OC::$server->getEventLogger()->end('setup_fs');
279
-			return false;
280
-		}
281
-
282
-		//if we aren't logged in, there is no use to set up the filesystem
283
-		if ($user != "") {
284
-
285
-			$userDir = '/' . $user . '/files';
286
-
287
-			//jail the user into his "home" directory
288
-			\OC\Files\Filesystem::init($user, $userDir);
289
-
290
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
291
-		}
292
-		\OC::$server->getEventLogger()->end('setup_fs');
293
-		return true;
294
-	}
295
-
296
-	/**
297
-	 * check if a password is required for each public link
298
-	 *
299
-	 * @return boolean
300
-	 * @suppress PhanDeprecatedFunction
301
-	 */
302
-	public static function isPublicLinkPasswordRequired() {
303
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
304
-		return ($enforcePassword === 'yes') ? true : false;
305
-	}
306
-
307
-	/**
308
-	 * check if sharing is disabled for the current user
309
-	 * @param IConfig $config
310
-	 * @param IGroupManager $groupManager
311
-	 * @param IUser|null $user
312
-	 * @return bool
313
-	 */
314
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
315
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
316
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
317
-			$excludedGroups = json_decode($groupsList);
318
-			if (is_null($excludedGroups)) {
319
-				$excludedGroups = explode(',', $groupsList);
320
-				$newValue = json_encode($excludedGroups);
321
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
322
-			}
323
-			$usersGroups = $groupManager->getUserGroupIds($user);
324
-			if (!empty($usersGroups)) {
325
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
326
-				// if the user is only in groups which are disabled for sharing then
327
-				// sharing is also disabled for the user
328
-				if (empty($remainingGroups)) {
329
-					return true;
330
-				}
331
-			}
332
-		}
333
-		return false;
334
-	}
335
-
336
-	/**
337
-	 * check if share API enforces a default expire date
338
-	 *
339
-	 * @return boolean
340
-	 * @suppress PhanDeprecatedFunction
341
-	 */
342
-	public static function isDefaultExpireDateEnforced() {
343
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
344
-		$enforceDefaultExpireDate = false;
345
-		if ($isDefaultExpireDateEnabled === 'yes') {
346
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
347
-			$enforceDefaultExpireDate = ($value === 'yes') ? true : false;
348
-		}
349
-
350
-		return $enforceDefaultExpireDate;
351
-	}
352
-
353
-	/**
354
-	 * Get the quota of a user
355
-	 *
356
-	 * @param string $userId
357
-	 * @return float Quota bytes
358
-	 */
359
-	public static function getUserQuota($userId) {
360
-		$user = \OC::$server->getUserManager()->get($userId);
361
-		if (is_null($user)) {
362
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
363
-		}
364
-		$userQuota = $user->getQuota();
365
-		if($userQuota === 'none') {
366
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
367
-		}
368
-		return OC_Helper::computerFileSize($userQuota);
369
-	}
370
-
371
-	/**
372
-	 * copies the skeleton to the users /files
373
-	 *
374
-	 * @param String $userId
375
-	 * @param \OCP\Files\Folder $userDirectory
376
-	 * @throws \RuntimeException
377
-	 * @suppress PhanDeprecatedFunction
378
-	 */
379
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
380
-
381
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
382
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
383
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
384
-
385
-		if (!file_exists($skeletonDirectory)) {
386
-			$dialectStart = strpos($userLang, '_');
387
-			if ($dialectStart !== false) {
388
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
389
-			}
390
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
391
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
392
-			}
393
-			if (!file_exists($skeletonDirectory)) {
394
-				$skeletonDirectory = '';
395
-			}
396
-		}
397
-
398
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
399
-
400
-		if ($instanceId === null) {
401
-			throw new \RuntimeException('no instance id!');
402
-		}
403
-		$appdata = 'appdata_' . $instanceId;
404
-		if ($userId === $appdata) {
405
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
406
-		}
407
-
408
-		if (!empty($skeletonDirectory)) {
409
-			\OCP\Util::writeLog(
410
-				'files_skeleton',
411
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
412
-				\OCP\Util::DEBUG
413
-			);
414
-			self::copyr($skeletonDirectory, $userDirectory);
415
-			// update the file cache
416
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
417
-		}
418
-	}
419
-
420
-	/**
421
-	 * copies a directory recursively by using streams
422
-	 *
423
-	 * @param string $source
424
-	 * @param \OCP\Files\Folder $target
425
-	 * @return void
426
-	 */
427
-	public static function copyr($source, \OCP\Files\Folder $target) {
428
-		$logger = \OC::$server->getLogger();
429
-
430
-		// Verify if folder exists
431
-		$dir = opendir($source);
432
-		if($dir === false) {
433
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
434
-			return;
435
-		}
436
-
437
-		// Copy the files
438
-		while (false !== ($file = readdir($dir))) {
439
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
440
-				if (is_dir($source . '/' . $file)) {
441
-					$child = $target->newFolder($file);
442
-					self::copyr($source . '/' . $file, $child);
443
-				} else {
444
-					$child = $target->newFile($file);
445
-					$sourceStream = fopen($source . '/' . $file, 'r');
446
-					if($sourceStream === false) {
447
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
448
-						closedir($dir);
449
-						return;
450
-					}
451
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
452
-				}
453
-			}
454
-		}
455
-		closedir($dir);
456
-	}
457
-
458
-	/**
459
-	 * @return void
460
-	 * @suppress PhanUndeclaredMethod
461
-	 */
462
-	public static function tearDownFS() {
463
-		\OC\Files\Filesystem::tearDown();
464
-		\OC::$server->getRootFolder()->clearCache();
465
-		self::$fsSetup = false;
466
-		self::$rootMounted = false;
467
-	}
468
-
469
-	/**
470
-	 * get the current installed version of ownCloud
471
-	 *
472
-	 * @return array
473
-	 */
474
-	public static function getVersion() {
475
-		OC_Util::loadVersion();
476
-		return self::$versionCache['OC_Version'];
477
-	}
478
-
479
-	/**
480
-	 * get the current installed version string of ownCloud
481
-	 *
482
-	 * @return string
483
-	 */
484
-	public static function getVersionString() {
485
-		OC_Util::loadVersion();
486
-		return self::$versionCache['OC_VersionString'];
487
-	}
488
-
489
-	/**
490
-	 * @deprecated the value is of no use anymore
491
-	 * @return string
492
-	 */
493
-	public static function getEditionString() {
494
-		return '';
495
-	}
496
-
497
-	/**
498
-	 * @description get the update channel of the current installed of ownCloud.
499
-	 * @return string
500
-	 */
501
-	public static function getChannel() {
502
-		OC_Util::loadVersion();
503
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
504
-	}
505
-
506
-	/**
507
-	 * @description get the build number of the current installed of ownCloud.
508
-	 * @return string
509
-	 */
510
-	public static function getBuild() {
511
-		OC_Util::loadVersion();
512
-		return self::$versionCache['OC_Build'];
513
-	}
514
-
515
-	/**
516
-	 * @description load the version.php into the session as cache
517
-	 * @suppress PhanUndeclaredVariable
518
-	 */
519
-	private static function loadVersion() {
520
-		if (self::$versionCache !== null) {
521
-			return;
522
-		}
523
-
524
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
525
-		require OC::$SERVERROOT . '/version.php';
526
-		/** @var $timestamp int */
527
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
528
-		/** @var $OC_Version string */
529
-		self::$versionCache['OC_Version'] = $OC_Version;
530
-		/** @var $OC_VersionString string */
531
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
532
-		/** @var $OC_Build string */
533
-		self::$versionCache['OC_Build'] = $OC_Build;
534
-
535
-		/** @var $OC_Channel string */
536
-		self::$versionCache['OC_Channel'] = $OC_Channel;
537
-	}
538
-
539
-	/**
540
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
541
-	 *
542
-	 * @param string $application application to get the files from
543
-	 * @param string $directory directory within this application (css, js, vendor, etc)
544
-	 * @param string $file the file inside of the above folder
545
-	 * @return string the path
546
-	 */
547
-	private static function generatePath($application, $directory, $file) {
548
-		if (is_null($file)) {
549
-			$file = $application;
550
-			$application = "";
551
-		}
552
-		if (!empty($application)) {
553
-			return "$application/$directory/$file";
554
-		} else {
555
-			return "$directory/$file";
556
-		}
557
-	}
558
-
559
-	/**
560
-	 * add a javascript file
561
-	 *
562
-	 * @param string $application application id
563
-	 * @param string|null $file filename
564
-	 * @param bool $prepend prepend the Script to the beginning of the list
565
-	 * @return void
566
-	 */
567
-	public static function addScript($application, $file = null, $prepend = false) {
568
-		$path = OC_Util::generatePath($application, 'js', $file);
569
-
570
-		// core js files need separate handling
571
-		if ($application !== 'core' && $file !== null) {
572
-			self::addTranslations ( $application );
573
-		}
574
-		self::addExternalResource($application, $prepend, $path, "script");
575
-	}
576
-
577
-	/**
578
-	 * add a javascript file from the vendor sub folder
579
-	 *
580
-	 * @param string $application application id
581
-	 * @param string|null $file filename
582
-	 * @param bool $prepend prepend the Script to the beginning of the list
583
-	 * @return void
584
-	 */
585
-	public static function addVendorScript($application, $file = null, $prepend = false) {
586
-		$path = OC_Util::generatePath($application, 'vendor', $file);
587
-		self::addExternalResource($application, $prepend, $path, "script");
588
-	}
589
-
590
-	/**
591
-	 * add a translation JS file
592
-	 *
593
-	 * @param string $application application id
594
-	 * @param string|null $languageCode language code, defaults to the current language
595
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
596
-	 */
597
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
598
-		if (is_null($languageCode)) {
599
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
600
-		}
601
-		if (!empty($application)) {
602
-			$path = "$application/l10n/$languageCode";
603
-		} else {
604
-			$path = "l10n/$languageCode";
605
-		}
606
-		self::addExternalResource($application, $prepend, $path, "script");
607
-	}
608
-
609
-	/**
610
-	 * add a css file
611
-	 *
612
-	 * @param string $application application id
613
-	 * @param string|null $file filename
614
-	 * @param bool $prepend prepend the Style to the beginning of the list
615
-	 * @return void
616
-	 */
617
-	public static function addStyle($application, $file = null, $prepend = false) {
618
-		$path = OC_Util::generatePath($application, 'css', $file);
619
-		self::addExternalResource($application, $prepend, $path, "style");
620
-	}
621
-
622
-	/**
623
-	 * add a css file from the vendor sub folder
624
-	 *
625
-	 * @param string $application application id
626
-	 * @param string|null $file filename
627
-	 * @param bool $prepend prepend the Style to the beginning of the list
628
-	 * @return void
629
-	 */
630
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
631
-		$path = OC_Util::generatePath($application, 'vendor', $file);
632
-		self::addExternalResource($application, $prepend, $path, "style");
633
-	}
634
-
635
-	/**
636
-	 * add an external resource css/js file
637
-	 *
638
-	 * @param string $application application id
639
-	 * @param bool $prepend prepend the file to the beginning of the list
640
-	 * @param string $path
641
-	 * @param string $type (script or style)
642
-	 * @return void
643
-	 */
644
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
645
-
646
-		if ($type === "style") {
647
-			if (!in_array($path, self::$styles)) {
648
-				if ($prepend === true) {
649
-					array_unshift ( self::$styles, $path );
650
-				} else {
651
-					self::$styles[] = $path;
652
-				}
653
-			}
654
-		} elseif ($type === "script") {
655
-			if (!in_array($path, self::$scripts)) {
656
-				if ($prepend === true) {
657
-					array_unshift ( self::$scripts, $path );
658
-				} else {
659
-					self::$scripts [] = $path;
660
-				}
661
-			}
662
-		}
663
-	}
664
-
665
-	/**
666
-	 * Add a custom element to the header
667
-	 * If $text is null then the element will be written as empty element.
668
-	 * So use "" to get a closing tag.
669
-	 * @param string $tag tag name of the element
670
-	 * @param array $attributes array of attributes for the element
671
-	 * @param string $text the text content for the element
672
-	 */
673
-	public static function addHeader($tag, $attributes, $text=null) {
674
-		self::$headers[] = array(
675
-			'tag' => $tag,
676
-			'attributes' => $attributes,
677
-			'text' => $text
678
-		);
679
-	}
680
-
681
-	/**
682
-	 * formats a timestamp in the "right" way
683
-	 *
684
-	 * @param int $timestamp
685
-	 * @param bool $dateOnly option to omit time from the result
686
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
687
-	 * @return string timestamp
688
-	 *
689
-	 * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
690
-	 */
691
-	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
692
-		if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
693
-			$timeZone = new \DateTimeZone($timeZone);
694
-		}
695
-
696
-		/** @var \OC\DateTimeFormatter $formatter */
697
-		$formatter = \OC::$server->query('DateTimeFormatter');
698
-		if ($dateOnly) {
699
-			return $formatter->formatDate($timestamp, 'long', $timeZone);
700
-		}
701
-		return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
702
-	}
703
-
704
-	/**
705
-	 * check if the current server configuration is suitable for ownCloud
706
-	 *
707
-	 * @param \OC\SystemConfig $config
708
-	 * @return array arrays with error messages and hints
709
-	 */
710
-	public static function checkServer(\OC\SystemConfig $config) {
711
-		$l = \OC::$server->getL10N('lib');
712
-		$errors = array();
713
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
714
-
715
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
716
-			// this check needs to be done every time
717
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
718
-		}
719
-
720
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
721
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
722
-			return $errors;
723
-		}
724
-
725
-		$webServerRestart = false;
726
-		$setup = new \OC\Setup(
727
-			$config,
728
-			\OC::$server->getIniWrapper(),
729
-			\OC::$server->getL10N('lib'),
730
-			\OC::$server->query(\OCP\Defaults::class),
731
-			\OC::$server->getLogger(),
732
-			\OC::$server->getSecureRandom(),
733
-			\OC::$server->query(\OC\Installer::class)
734
-		);
735
-
736
-		$urlGenerator = \OC::$server->getURLGenerator();
737
-
738
-		$availableDatabases = $setup->getSupportedDatabases();
739
-		if (empty($availableDatabases)) {
740
-			$errors[] = array(
741
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
742
-				'hint' => '' //TODO: sane hint
743
-			);
744
-			$webServerRestart = true;
745
-		}
746
-
747
-		// Check if config folder is writable.
748
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
749
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
750
-				$errors[] = array(
751
-					'error' => $l->t('Cannot write into "config" directory'),
752
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
753
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
754
-				);
755
-			}
756
-		}
757
-
758
-		// Check if there is a writable install folder.
759
-		if ($config->getValue('appstoreenabled', true)) {
760
-			if (OC_App::getInstallPath() === null
761
-				|| !is_writable(OC_App::getInstallPath())
762
-				|| !is_readable(OC_App::getInstallPath())
763
-			) {
764
-				$errors[] = array(
765
-					'error' => $l->t('Cannot write into "apps" directory'),
766
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
767
-						. ' or disabling the appstore in the config file. See %s',
768
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
769
-				);
770
-			}
771
-		}
772
-		// Create root dir.
773
-		if ($config->getValue('installed', false)) {
774
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
775
-				$success = @mkdir($CONFIG_DATADIRECTORY);
776
-				if ($success) {
777
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
778
-				} else {
779
-					$errors[] = [
780
-						'error' => $l->t('Cannot create "data" directory'),
781
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
782
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
783
-					];
784
-				}
785
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
786
-				//common hint for all file permissions error messages
787
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
788
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
789
-				$errors[] = [
790
-					'error' => 'Your data directory is not writable',
791
-					'hint' => $permissionsHint
792
-				];
793
-			} else {
794
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
795
-			}
796
-		}
797
-
798
-		if (!OC_Util::isSetLocaleWorking()) {
799
-			$errors[] = array(
800
-				'error' => $l->t('Setting locale to %s failed',
801
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
802
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
803
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
804
-			);
805
-		}
806
-
807
-		// Contains the dependencies that should be checked against
808
-		// classes = class_exists
809
-		// functions = function_exists
810
-		// defined = defined
811
-		// ini = ini_get
812
-		// If the dependency is not found the missing module name is shown to the EndUser
813
-		// When adding new checks always verify that they pass on Travis as well
814
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
815
-		$dependencies = array(
816
-			'classes' => array(
817
-				'ZipArchive' => 'zip',
818
-				'DOMDocument' => 'dom',
819
-				'XMLWriter' => 'XMLWriter',
820
-				'XMLReader' => 'XMLReader',
821
-			),
822
-			'functions' => [
823
-				'xml_parser_create' => 'libxml',
824
-				'mb_strcut' => 'mb multibyte',
825
-				'ctype_digit' => 'ctype',
826
-				'json_encode' => 'JSON',
827
-				'gd_info' => 'GD',
828
-				'gzencode' => 'zlib',
829
-				'iconv' => 'iconv',
830
-				'simplexml_load_string' => 'SimpleXML',
831
-				'hash' => 'HASH Message Digest Framework',
832
-				'curl_init' => 'cURL',
833
-				'openssl_verify' => 'OpenSSL',
834
-			],
835
-			'defined' => array(
836
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
837
-			),
838
-			'ini' => [
839
-				'default_charset' => 'UTF-8',
840
-			],
841
-		);
842
-		$missingDependencies = array();
843
-		$invalidIniSettings = [];
844
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
845
-
846
-		/**
847
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
848
-		 *        and prevents installation. Once HHVM is more compatible with our
849
-		 *        approach to check for these values we should re-enable those
850
-		 *        checks.
851
-		 */
852
-		$iniWrapper = \OC::$server->getIniWrapper();
853
-		if (!self::runningOnHhvm()) {
854
-			foreach ($dependencies['classes'] as $class => $module) {
855
-				if (!class_exists($class)) {
856
-					$missingDependencies[] = $module;
857
-				}
858
-			}
859
-			foreach ($dependencies['functions'] as $function => $module) {
860
-				if (!function_exists($function)) {
861
-					$missingDependencies[] = $module;
862
-				}
863
-			}
864
-			foreach ($dependencies['defined'] as $defined => $module) {
865
-				if (!defined($defined)) {
866
-					$missingDependencies[] = $module;
867
-				}
868
-			}
869
-			foreach ($dependencies['ini'] as $setting => $expected) {
870
-				if (is_bool($expected)) {
871
-					if ($iniWrapper->getBool($setting) !== $expected) {
872
-						$invalidIniSettings[] = [$setting, $expected];
873
-					}
874
-				}
875
-				if (is_int($expected)) {
876
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
877
-						$invalidIniSettings[] = [$setting, $expected];
878
-					}
879
-				}
880
-				if (is_string($expected)) {
881
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
882
-						$invalidIniSettings[] = [$setting, $expected];
883
-					}
884
-				}
885
-			}
886
-		}
887
-
888
-		foreach($missingDependencies as $missingDependency) {
889
-			$errors[] = array(
890
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
891
-				'hint' => $moduleHint
892
-			);
893
-			$webServerRestart = true;
894
-		}
895
-		foreach($invalidIniSettings as $setting) {
896
-			if(is_bool($setting[1])) {
897
-				$setting[1] = ($setting[1]) ? 'on' : 'off';
898
-			}
899
-			$errors[] = [
900
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
901
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
902
-			];
903
-			$webServerRestart = true;
904
-		}
905
-
906
-		/**
907
-		 * The mbstring.func_overload check can only be performed if the mbstring
908
-		 * module is installed as it will return null if the checking setting is
909
-		 * not available and thus a check on the boolean value fails.
910
-		 *
911
-		 * TODO: Should probably be implemented in the above generic dependency
912
-		 *       check somehow in the long-term.
913
-		 */
914
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
915
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
916
-			$errors[] = array(
917
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
918
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
919
-			);
920
-		}
921
-
922
-		if(function_exists('xml_parser_create') &&
923
-			LIBXML_LOADED_VERSION < 20700 ) {
924
-			$version = LIBXML_LOADED_VERSION;
925
-			$major = floor($version/10000);
926
-			$version -= ($major * 10000);
927
-			$minor = floor($version/100);
928
-			$version -= ($minor * 100);
929
-			$patch = $version;
930
-			$errors[] = array(
931
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
932
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
933
-			);
934
-		}
935
-
936
-		if (!self::isAnnotationsWorking()) {
937
-			$errors[] = array(
938
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
939
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
940
-			);
941
-		}
942
-
943
-		if (!\OC::$CLI && $webServerRestart) {
944
-			$errors[] = array(
945
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
946
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
947
-			);
948
-		}
949
-
950
-		$errors = array_merge($errors, self::checkDatabaseVersion());
951
-
952
-		// Cache the result of this function
953
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
954
-
955
-		return $errors;
956
-	}
957
-
958
-	/**
959
-	 * Check the database version
960
-	 *
961
-	 * @return array errors array
962
-	 */
963
-	public static function checkDatabaseVersion() {
964
-		$l = \OC::$server->getL10N('lib');
965
-		$errors = array();
966
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
967
-		if ($dbType === 'pgsql') {
968
-			// check PostgreSQL version
969
-			try {
970
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
971
-				$data = $result->fetchRow();
972
-				if (isset($data['server_version'])) {
973
-					$version = $data['server_version'];
974
-					if (version_compare($version, '9.0.0', '<')) {
975
-						$errors[] = array(
976
-							'error' => $l->t('PostgreSQL >= 9 required'),
977
-							'hint' => $l->t('Please upgrade your database version')
978
-						);
979
-					}
980
-				}
981
-			} catch (\Doctrine\DBAL\DBALException $e) {
982
-				$logger = \OC::$server->getLogger();
983
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
984
-				$logger->logException($e);
985
-			}
986
-		}
987
-		return $errors;
988
-	}
989
-
990
-	/**
991
-	 * Check for correct file permissions of data directory
992
-	 *
993
-	 * @param string $dataDirectory
994
-	 * @return array arrays with error messages and hints
995
-	 */
996
-	public static function checkDataDirectoryPermissions($dataDirectory) {
997
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
998
-			return  [];
999
-		}
1000
-		$l = \OC::$server->getL10N('lib');
1001
-		$errors = [];
1002
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1003
-			. ' cannot be listed by other users.');
1004
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1005
-		if (substr($perms, -1) !== '0') {
1006
-			chmod($dataDirectory, 0770);
1007
-			clearstatcache();
1008
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1009
-			if ($perms[2] !== '0') {
1010
-				$errors[] = [
1011
-					'error' => $l->t('Your data directory is readable by other users'),
1012
-					'hint' => $permissionsModHint
1013
-				];
1014
-			}
1015
-		}
1016
-		return $errors;
1017
-	}
1018
-
1019
-	/**
1020
-	 * Check that the data directory exists and is valid by
1021
-	 * checking the existence of the ".ocdata" file.
1022
-	 *
1023
-	 * @param string $dataDirectory data directory path
1024
-	 * @return array errors found
1025
-	 */
1026
-	public static function checkDataDirectoryValidity($dataDirectory) {
1027
-		$l = \OC::$server->getL10N('lib');
1028
-		$errors = [];
1029
-		if ($dataDirectory[0] !== '/') {
1030
-			$errors[] = [
1031
-				'error' => $l->t('Your data directory must be an absolute path'),
1032
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1033
-			];
1034
-		}
1035
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1036
-			$errors[] = [
1037
-				'error' => $l->t('Your data directory is invalid'),
1038
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1039
-					' in the root of the data directory.')
1040
-			];
1041
-		}
1042
-		return $errors;
1043
-	}
1044
-
1045
-	/**
1046
-	 * Check if the user is logged in, redirects to home if not. With
1047
-	 * redirect URL parameter to the request URI.
1048
-	 *
1049
-	 * @return void
1050
-	 */
1051
-	public static function checkLoggedIn() {
1052
-		// Check if we are a user
1053
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1054
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1055
-						'core.login.showLoginForm',
1056
-						[
1057
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1058
-						]
1059
-					)
1060
-			);
1061
-			exit();
1062
-		}
1063
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1064
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1065
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1066
-			exit();
1067
-		}
1068
-	}
1069
-
1070
-	/**
1071
-	 * Check if the user is a admin, redirects to home if not
1072
-	 *
1073
-	 * @return void
1074
-	 */
1075
-	public static function checkAdminUser() {
1076
-		OC_Util::checkLoggedIn();
1077
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1078
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1079
-			exit();
1080
-		}
1081
-	}
1082
-
1083
-	/**
1084
-	 * Check if the user is a subadmin, redirects to home if not
1085
-	 *
1086
-	 * @return null|boolean $groups where the current user is subadmin
1087
-	 */
1088
-	public static function checkSubAdminUser() {
1089
-		OC_Util::checkLoggedIn();
1090
-		$userObject = \OC::$server->getUserSession()->getUser();
1091
-		$isSubAdmin = false;
1092
-		if($userObject !== null) {
1093
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1094
-		}
1095
-
1096
-		if (!$isSubAdmin) {
1097
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1098
-			exit();
1099
-		}
1100
-		return true;
1101
-	}
1102
-
1103
-	/**
1104
-	 * Returns the URL of the default page
1105
-	 * based on the system configuration and
1106
-	 * the apps visible for the current user
1107
-	 *
1108
-	 * @return string URL
1109
-	 * @suppress PhanDeprecatedFunction
1110
-	 */
1111
-	public static function getDefaultPageUrl() {
1112
-		$urlGenerator = \OC::$server->getURLGenerator();
1113
-		// Deny the redirect if the URL contains a @
1114
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1115
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1116
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1117
-		} else {
1118
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1119
-			if ($defaultPage) {
1120
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1121
-			} else {
1122
-				$appId = 'files';
1123
-				$config = \OC::$server->getConfig();
1124
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1125
-				// find the first app that is enabled for the current user
1126
-				foreach ($defaultApps as $defaultApp) {
1127
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1128
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1129
-						$appId = $defaultApp;
1130
-						break;
1131
-					}
1132
-				}
1133
-
1134
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1135
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1136
-				} else {
1137
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1138
-				}
1139
-			}
1140
-		}
1141
-		return $location;
1142
-	}
1143
-
1144
-	/**
1145
-	 * Redirect to the user default page
1146
-	 *
1147
-	 * @return void
1148
-	 */
1149
-	public static function redirectToDefaultPage() {
1150
-		$location = self::getDefaultPageUrl();
1151
-		header('Location: ' . $location);
1152
-		exit();
1153
-	}
1154
-
1155
-	/**
1156
-	 * get an id unique for this instance
1157
-	 *
1158
-	 * @return string
1159
-	 */
1160
-	public static function getInstanceId() {
1161
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1162
-		if (is_null($id)) {
1163
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1164
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1165
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1166
-		}
1167
-		return $id;
1168
-	}
1169
-
1170
-	/**
1171
-	 * Public function to sanitize HTML
1172
-	 *
1173
-	 * This function is used to sanitize HTML and should be applied on any
1174
-	 * string or array of strings before displaying it on a web page.
1175
-	 *
1176
-	 * @param string|array $value
1177
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1178
-	 */
1179
-	public static function sanitizeHTML($value) {
1180
-		if (is_array($value)) {
1181
-			$value = array_map(function($value) {
1182
-				return self::sanitizeHTML($value);
1183
-			}, $value);
1184
-		} else {
1185
-			// Specify encoding for PHP<5.4
1186
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1187
-		}
1188
-		return $value;
1189
-	}
1190
-
1191
-	/**
1192
-	 * Public function to encode url parameters
1193
-	 *
1194
-	 * This function is used to encode path to file before output.
1195
-	 * Encoding is done according to RFC 3986 with one exception:
1196
-	 * Character '/' is preserved as is.
1197
-	 *
1198
-	 * @param string $component part of URI to encode
1199
-	 * @return string
1200
-	 */
1201
-	public static function encodePath($component) {
1202
-		$encoded = rawurlencode($component);
1203
-		$encoded = str_replace('%2F', '/', $encoded);
1204
-		return $encoded;
1205
-	}
1206
-
1207
-
1208
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1209
-		// php dev server does not support htaccess
1210
-		if (php_sapi_name() === 'cli-server') {
1211
-			return false;
1212
-		}
1213
-
1214
-		// testdata
1215
-		$fileName = '/htaccesstest.txt';
1216
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1217
-
1218
-		// creating a test file
1219
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1220
-
1221
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1222
-			return false;
1223
-		}
1224
-
1225
-		$fp = @fopen($testFile, 'w');
1226
-		if (!$fp) {
1227
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1228
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1229
-		}
1230
-		fwrite($fp, $testContent);
1231
-		fclose($fp);
1232
-
1233
-		return $testContent;
1234
-	}
1235
-
1236
-	/**
1237
-	 * Check if the .htaccess file is working
1238
-	 * @param \OCP\IConfig $config
1239
-	 * @return bool
1240
-	 * @throws Exception
1241
-	 * @throws \OC\HintException If the test file can't get written.
1242
-	 */
1243
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1244
-
1245
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1246
-			return true;
1247
-		}
1248
-
1249
-		$testContent = $this->createHtaccessTestFile($config);
1250
-		if ($testContent === false) {
1251
-			return false;
1252
-		}
1253
-
1254
-		$fileName = '/htaccesstest.txt';
1255
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1256
-
1257
-		// accessing the file via http
1258
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1259
-		try {
1260
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1261
-		} catch (\Exception $e) {
1262
-			$content = false;
1263
-		}
1264
-
1265
-		// cleanup
1266
-		@unlink($testFile);
1267
-
1268
-		/*
68
+    public static $scripts = array();
69
+    public static $styles = array();
70
+    public static $headers = array();
71
+    private static $rootMounted = false;
72
+    private static $fsSetup = false;
73
+
74
+    /** @var array Local cache of version.php */
75
+    private static $versionCache = null;
76
+
77
+    protected static function getAppManager() {
78
+        return \OC::$server->getAppManager();
79
+    }
80
+
81
+    private static function initLocalStorageRootFS() {
82
+        // mount local file backend as root
83
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
84
+        //first set up the local "root" storage
85
+        \OC\Files\Filesystem::initMountManager();
86
+        if (!self::$rootMounted) {
87
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
88
+            self::$rootMounted = true;
89
+        }
90
+    }
91
+
92
+    /**
93
+     * mounting an object storage as the root fs will in essence remove the
94
+     * necessity of a data folder being present.
95
+     * TODO make home storage aware of this and use the object storage instead of local disk access
96
+     *
97
+     * @param array $config containing 'class' and optional 'arguments'
98
+     * @suppress PhanDeprecatedFunction
99
+     */
100
+    private static function initObjectStoreRootFS($config) {
101
+        // check misconfiguration
102
+        if (empty($config['class'])) {
103
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
104
+        }
105
+        if (!isset($config['arguments'])) {
106
+            $config['arguments'] = array();
107
+        }
108
+
109
+        // instantiate object store implementation
110
+        $name = $config['class'];
111
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
112
+            $segments = explode('\\', $name);
113
+            OC_App::loadApp(strtolower($segments[1]));
114
+        }
115
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
116
+        // mount with plain / root object store implementation
117
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
118
+
119
+        // mount object storage as root
120
+        \OC\Files\Filesystem::initMountManager();
121
+        if (!self::$rootMounted) {
122
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
123
+            self::$rootMounted = true;
124
+        }
125
+    }
126
+
127
+    /**
128
+     * mounting an object storage as the root fs will in essence remove the
129
+     * necessity of a data folder being present.
130
+     *
131
+     * @param array $config containing 'class' and optional 'arguments'
132
+     * @suppress PhanDeprecatedFunction
133
+     */
134
+    private static function initObjectStoreMultibucketRootFS($config) {
135
+        // check misconfiguration
136
+        if (empty($config['class'])) {
137
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
138
+        }
139
+        if (!isset($config['arguments'])) {
140
+            $config['arguments'] = array();
141
+        }
142
+
143
+        // instantiate object store implementation
144
+        $name = $config['class'];
145
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
146
+            $segments = explode('\\', $name);
147
+            OC_App::loadApp(strtolower($segments[1]));
148
+        }
149
+
150
+        if (!isset($config['arguments']['bucket'])) {
151
+            $config['arguments']['bucket'] = '';
152
+        }
153
+        // put the root FS always in first bucket for multibucket configuration
154
+        $config['arguments']['bucket'] .= '0';
155
+
156
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
157
+        // mount with plain / root object store implementation
158
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
159
+
160
+        // mount object storage as root
161
+        \OC\Files\Filesystem::initMountManager();
162
+        if (!self::$rootMounted) {
163
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
164
+            self::$rootMounted = true;
165
+        }
166
+    }
167
+
168
+    /**
169
+     * Can be set up
170
+     *
171
+     * @param string $user
172
+     * @return boolean
173
+     * @description configure the initial filesystem based on the configuration
174
+     * @suppress PhanDeprecatedFunction
175
+     * @suppress PhanAccessMethodInternal
176
+     */
177
+    public static function setupFS($user = '') {
178
+        //setting up the filesystem twice can only lead to trouble
179
+        if (self::$fsSetup) {
180
+            return false;
181
+        }
182
+
183
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
184
+
185
+        // If we are not forced to load a specific user we load the one that is logged in
186
+        if ($user === null) {
187
+            $user = '';
188
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
189
+            $user = OC_User::getUser();
190
+        }
191
+
192
+        // load all filesystem apps before, so no setup-hook gets lost
193
+        OC_App::loadApps(array('filesystem'));
194
+
195
+        // the filesystem will finish when $user is not empty,
196
+        // mark fs setup here to avoid doing the setup from loading
197
+        // OC_Filesystem
198
+        if ($user != '') {
199
+            self::$fsSetup = true;
200
+        }
201
+
202
+        \OC\Files\Filesystem::initMountManager();
203
+
204
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207
+                /** @var \OC\Files\Storage\Common $storage */
208
+                $storage->setMountOptions($mount->getOptions());
209
+            }
210
+            return $storage;
211
+        });
212
+
213
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
+            if (!$mount->getOption('enable_sharing', true)) {
215
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
216
+                    'storage' => $storage,
217
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
218
+                ]);
219
+            }
220
+            return $storage;
221
+        });
222
+
223
+        // install storage availability wrapper, before most other wrappers
224
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227
+            }
228
+            return $storage;
229
+        });
230
+
231
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234
+            }
235
+            return $storage;
236
+        });
237
+
238
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
239
+            // set up quota for home storages, even for other users
240
+            // which can happen when using sharing
241
+
242
+            /**
243
+             * @var \OC\Files\Storage\Storage $storage
244
+             */
245
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
246
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
247
+            ) {
248
+                /** @var \OC\Files\Storage\Home $storage */
249
+                if (is_object($storage->getUser())) {
250
+                    $user = $storage->getUser()->getUID();
251
+                    $quota = OC_Util::getUserQuota($user);
252
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
254
+                    }
255
+                }
256
+            }
257
+
258
+            return $storage;
259
+        });
260
+
261
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
262
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
263
+
264
+        //check if we are using an object storage
265
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
266
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
267
+
268
+        // use the same order as in ObjectHomeMountProvider
269
+        if (isset($objectStoreMultibucket)) {
270
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
271
+        } elseif (isset($objectStore)) {
272
+            self::initObjectStoreRootFS($objectStore);
273
+        } else {
274
+            self::initLocalStorageRootFS();
275
+        }
276
+
277
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
278
+            \OC::$server->getEventLogger()->end('setup_fs');
279
+            return false;
280
+        }
281
+
282
+        //if we aren't logged in, there is no use to set up the filesystem
283
+        if ($user != "") {
284
+
285
+            $userDir = '/' . $user . '/files';
286
+
287
+            //jail the user into his "home" directory
288
+            \OC\Files\Filesystem::init($user, $userDir);
289
+
290
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
291
+        }
292
+        \OC::$server->getEventLogger()->end('setup_fs');
293
+        return true;
294
+    }
295
+
296
+    /**
297
+     * check if a password is required for each public link
298
+     *
299
+     * @return boolean
300
+     * @suppress PhanDeprecatedFunction
301
+     */
302
+    public static function isPublicLinkPasswordRequired() {
303
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
304
+        return ($enforcePassword === 'yes') ? true : false;
305
+    }
306
+
307
+    /**
308
+     * check if sharing is disabled for the current user
309
+     * @param IConfig $config
310
+     * @param IGroupManager $groupManager
311
+     * @param IUser|null $user
312
+     * @return bool
313
+     */
314
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
315
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
316
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
317
+            $excludedGroups = json_decode($groupsList);
318
+            if (is_null($excludedGroups)) {
319
+                $excludedGroups = explode(',', $groupsList);
320
+                $newValue = json_encode($excludedGroups);
321
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
322
+            }
323
+            $usersGroups = $groupManager->getUserGroupIds($user);
324
+            if (!empty($usersGroups)) {
325
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
326
+                // if the user is only in groups which are disabled for sharing then
327
+                // sharing is also disabled for the user
328
+                if (empty($remainingGroups)) {
329
+                    return true;
330
+                }
331
+            }
332
+        }
333
+        return false;
334
+    }
335
+
336
+    /**
337
+     * check if share API enforces a default expire date
338
+     *
339
+     * @return boolean
340
+     * @suppress PhanDeprecatedFunction
341
+     */
342
+    public static function isDefaultExpireDateEnforced() {
343
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
344
+        $enforceDefaultExpireDate = false;
345
+        if ($isDefaultExpireDateEnabled === 'yes') {
346
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
347
+            $enforceDefaultExpireDate = ($value === 'yes') ? true : false;
348
+        }
349
+
350
+        return $enforceDefaultExpireDate;
351
+    }
352
+
353
+    /**
354
+     * Get the quota of a user
355
+     *
356
+     * @param string $userId
357
+     * @return float Quota bytes
358
+     */
359
+    public static function getUserQuota($userId) {
360
+        $user = \OC::$server->getUserManager()->get($userId);
361
+        if (is_null($user)) {
362
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
363
+        }
364
+        $userQuota = $user->getQuota();
365
+        if($userQuota === 'none') {
366
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
367
+        }
368
+        return OC_Helper::computerFileSize($userQuota);
369
+    }
370
+
371
+    /**
372
+     * copies the skeleton to the users /files
373
+     *
374
+     * @param String $userId
375
+     * @param \OCP\Files\Folder $userDirectory
376
+     * @throws \RuntimeException
377
+     * @suppress PhanDeprecatedFunction
378
+     */
379
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
380
+
381
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
382
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
383
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
384
+
385
+        if (!file_exists($skeletonDirectory)) {
386
+            $dialectStart = strpos($userLang, '_');
387
+            if ($dialectStart !== false) {
388
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
389
+            }
390
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
391
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
392
+            }
393
+            if (!file_exists($skeletonDirectory)) {
394
+                $skeletonDirectory = '';
395
+            }
396
+        }
397
+
398
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
399
+
400
+        if ($instanceId === null) {
401
+            throw new \RuntimeException('no instance id!');
402
+        }
403
+        $appdata = 'appdata_' . $instanceId;
404
+        if ($userId === $appdata) {
405
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
406
+        }
407
+
408
+        if (!empty($skeletonDirectory)) {
409
+            \OCP\Util::writeLog(
410
+                'files_skeleton',
411
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
412
+                \OCP\Util::DEBUG
413
+            );
414
+            self::copyr($skeletonDirectory, $userDirectory);
415
+            // update the file cache
416
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
417
+        }
418
+    }
419
+
420
+    /**
421
+     * copies a directory recursively by using streams
422
+     *
423
+     * @param string $source
424
+     * @param \OCP\Files\Folder $target
425
+     * @return void
426
+     */
427
+    public static function copyr($source, \OCP\Files\Folder $target) {
428
+        $logger = \OC::$server->getLogger();
429
+
430
+        // Verify if folder exists
431
+        $dir = opendir($source);
432
+        if($dir === false) {
433
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
434
+            return;
435
+        }
436
+
437
+        // Copy the files
438
+        while (false !== ($file = readdir($dir))) {
439
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
440
+                if (is_dir($source . '/' . $file)) {
441
+                    $child = $target->newFolder($file);
442
+                    self::copyr($source . '/' . $file, $child);
443
+                } else {
444
+                    $child = $target->newFile($file);
445
+                    $sourceStream = fopen($source . '/' . $file, 'r');
446
+                    if($sourceStream === false) {
447
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
448
+                        closedir($dir);
449
+                        return;
450
+                    }
451
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
452
+                }
453
+            }
454
+        }
455
+        closedir($dir);
456
+    }
457
+
458
+    /**
459
+     * @return void
460
+     * @suppress PhanUndeclaredMethod
461
+     */
462
+    public static function tearDownFS() {
463
+        \OC\Files\Filesystem::tearDown();
464
+        \OC::$server->getRootFolder()->clearCache();
465
+        self::$fsSetup = false;
466
+        self::$rootMounted = false;
467
+    }
468
+
469
+    /**
470
+     * get the current installed version of ownCloud
471
+     *
472
+     * @return array
473
+     */
474
+    public static function getVersion() {
475
+        OC_Util::loadVersion();
476
+        return self::$versionCache['OC_Version'];
477
+    }
478
+
479
+    /**
480
+     * get the current installed version string of ownCloud
481
+     *
482
+     * @return string
483
+     */
484
+    public static function getVersionString() {
485
+        OC_Util::loadVersion();
486
+        return self::$versionCache['OC_VersionString'];
487
+    }
488
+
489
+    /**
490
+     * @deprecated the value is of no use anymore
491
+     * @return string
492
+     */
493
+    public static function getEditionString() {
494
+        return '';
495
+    }
496
+
497
+    /**
498
+     * @description get the update channel of the current installed of ownCloud.
499
+     * @return string
500
+     */
501
+    public static function getChannel() {
502
+        OC_Util::loadVersion();
503
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
504
+    }
505
+
506
+    /**
507
+     * @description get the build number of the current installed of ownCloud.
508
+     * @return string
509
+     */
510
+    public static function getBuild() {
511
+        OC_Util::loadVersion();
512
+        return self::$versionCache['OC_Build'];
513
+    }
514
+
515
+    /**
516
+     * @description load the version.php into the session as cache
517
+     * @suppress PhanUndeclaredVariable
518
+     */
519
+    private static function loadVersion() {
520
+        if (self::$versionCache !== null) {
521
+            return;
522
+        }
523
+
524
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
525
+        require OC::$SERVERROOT . '/version.php';
526
+        /** @var $timestamp int */
527
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
528
+        /** @var $OC_Version string */
529
+        self::$versionCache['OC_Version'] = $OC_Version;
530
+        /** @var $OC_VersionString string */
531
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
532
+        /** @var $OC_Build string */
533
+        self::$versionCache['OC_Build'] = $OC_Build;
534
+
535
+        /** @var $OC_Channel string */
536
+        self::$versionCache['OC_Channel'] = $OC_Channel;
537
+    }
538
+
539
+    /**
540
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
541
+     *
542
+     * @param string $application application to get the files from
543
+     * @param string $directory directory within this application (css, js, vendor, etc)
544
+     * @param string $file the file inside of the above folder
545
+     * @return string the path
546
+     */
547
+    private static function generatePath($application, $directory, $file) {
548
+        if (is_null($file)) {
549
+            $file = $application;
550
+            $application = "";
551
+        }
552
+        if (!empty($application)) {
553
+            return "$application/$directory/$file";
554
+        } else {
555
+            return "$directory/$file";
556
+        }
557
+    }
558
+
559
+    /**
560
+     * add a javascript file
561
+     *
562
+     * @param string $application application id
563
+     * @param string|null $file filename
564
+     * @param bool $prepend prepend the Script to the beginning of the list
565
+     * @return void
566
+     */
567
+    public static function addScript($application, $file = null, $prepend = false) {
568
+        $path = OC_Util::generatePath($application, 'js', $file);
569
+
570
+        // core js files need separate handling
571
+        if ($application !== 'core' && $file !== null) {
572
+            self::addTranslations ( $application );
573
+        }
574
+        self::addExternalResource($application, $prepend, $path, "script");
575
+    }
576
+
577
+    /**
578
+     * add a javascript file from the vendor sub folder
579
+     *
580
+     * @param string $application application id
581
+     * @param string|null $file filename
582
+     * @param bool $prepend prepend the Script to the beginning of the list
583
+     * @return void
584
+     */
585
+    public static function addVendorScript($application, $file = null, $prepend = false) {
586
+        $path = OC_Util::generatePath($application, 'vendor', $file);
587
+        self::addExternalResource($application, $prepend, $path, "script");
588
+    }
589
+
590
+    /**
591
+     * add a translation JS file
592
+     *
593
+     * @param string $application application id
594
+     * @param string|null $languageCode language code, defaults to the current language
595
+     * @param bool|null $prepend prepend the Script to the beginning of the list
596
+     */
597
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
598
+        if (is_null($languageCode)) {
599
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
600
+        }
601
+        if (!empty($application)) {
602
+            $path = "$application/l10n/$languageCode";
603
+        } else {
604
+            $path = "l10n/$languageCode";
605
+        }
606
+        self::addExternalResource($application, $prepend, $path, "script");
607
+    }
608
+
609
+    /**
610
+     * add a css file
611
+     *
612
+     * @param string $application application id
613
+     * @param string|null $file filename
614
+     * @param bool $prepend prepend the Style to the beginning of the list
615
+     * @return void
616
+     */
617
+    public static function addStyle($application, $file = null, $prepend = false) {
618
+        $path = OC_Util::generatePath($application, 'css', $file);
619
+        self::addExternalResource($application, $prepend, $path, "style");
620
+    }
621
+
622
+    /**
623
+     * add a css file from the vendor sub folder
624
+     *
625
+     * @param string $application application id
626
+     * @param string|null $file filename
627
+     * @param bool $prepend prepend the Style to the beginning of the list
628
+     * @return void
629
+     */
630
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
631
+        $path = OC_Util::generatePath($application, 'vendor', $file);
632
+        self::addExternalResource($application, $prepend, $path, "style");
633
+    }
634
+
635
+    /**
636
+     * add an external resource css/js file
637
+     *
638
+     * @param string $application application id
639
+     * @param bool $prepend prepend the file to the beginning of the list
640
+     * @param string $path
641
+     * @param string $type (script or style)
642
+     * @return void
643
+     */
644
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
645
+
646
+        if ($type === "style") {
647
+            if (!in_array($path, self::$styles)) {
648
+                if ($prepend === true) {
649
+                    array_unshift ( self::$styles, $path );
650
+                } else {
651
+                    self::$styles[] = $path;
652
+                }
653
+            }
654
+        } elseif ($type === "script") {
655
+            if (!in_array($path, self::$scripts)) {
656
+                if ($prepend === true) {
657
+                    array_unshift ( self::$scripts, $path );
658
+                } else {
659
+                    self::$scripts [] = $path;
660
+                }
661
+            }
662
+        }
663
+    }
664
+
665
+    /**
666
+     * Add a custom element to the header
667
+     * If $text is null then the element will be written as empty element.
668
+     * So use "" to get a closing tag.
669
+     * @param string $tag tag name of the element
670
+     * @param array $attributes array of attributes for the element
671
+     * @param string $text the text content for the element
672
+     */
673
+    public static function addHeader($tag, $attributes, $text=null) {
674
+        self::$headers[] = array(
675
+            'tag' => $tag,
676
+            'attributes' => $attributes,
677
+            'text' => $text
678
+        );
679
+    }
680
+
681
+    /**
682
+     * formats a timestamp in the "right" way
683
+     *
684
+     * @param int $timestamp
685
+     * @param bool $dateOnly option to omit time from the result
686
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
687
+     * @return string timestamp
688
+     *
689
+     * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
690
+     */
691
+    public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
692
+        if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
693
+            $timeZone = new \DateTimeZone($timeZone);
694
+        }
695
+
696
+        /** @var \OC\DateTimeFormatter $formatter */
697
+        $formatter = \OC::$server->query('DateTimeFormatter');
698
+        if ($dateOnly) {
699
+            return $formatter->formatDate($timestamp, 'long', $timeZone);
700
+        }
701
+        return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
702
+    }
703
+
704
+    /**
705
+     * check if the current server configuration is suitable for ownCloud
706
+     *
707
+     * @param \OC\SystemConfig $config
708
+     * @return array arrays with error messages and hints
709
+     */
710
+    public static function checkServer(\OC\SystemConfig $config) {
711
+        $l = \OC::$server->getL10N('lib');
712
+        $errors = array();
713
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
714
+
715
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
716
+            // this check needs to be done every time
717
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
718
+        }
719
+
720
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
721
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
722
+            return $errors;
723
+        }
724
+
725
+        $webServerRestart = false;
726
+        $setup = new \OC\Setup(
727
+            $config,
728
+            \OC::$server->getIniWrapper(),
729
+            \OC::$server->getL10N('lib'),
730
+            \OC::$server->query(\OCP\Defaults::class),
731
+            \OC::$server->getLogger(),
732
+            \OC::$server->getSecureRandom(),
733
+            \OC::$server->query(\OC\Installer::class)
734
+        );
735
+
736
+        $urlGenerator = \OC::$server->getURLGenerator();
737
+
738
+        $availableDatabases = $setup->getSupportedDatabases();
739
+        if (empty($availableDatabases)) {
740
+            $errors[] = array(
741
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
742
+                'hint' => '' //TODO: sane hint
743
+            );
744
+            $webServerRestart = true;
745
+        }
746
+
747
+        // Check if config folder is writable.
748
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
749
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
750
+                $errors[] = array(
751
+                    'error' => $l->t('Cannot write into "config" directory'),
752
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
753
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
754
+                );
755
+            }
756
+        }
757
+
758
+        // Check if there is a writable install folder.
759
+        if ($config->getValue('appstoreenabled', true)) {
760
+            if (OC_App::getInstallPath() === null
761
+                || !is_writable(OC_App::getInstallPath())
762
+                || !is_readable(OC_App::getInstallPath())
763
+            ) {
764
+                $errors[] = array(
765
+                    'error' => $l->t('Cannot write into "apps" directory'),
766
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
767
+                        . ' or disabling the appstore in the config file. See %s',
768
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
769
+                );
770
+            }
771
+        }
772
+        // Create root dir.
773
+        if ($config->getValue('installed', false)) {
774
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
775
+                $success = @mkdir($CONFIG_DATADIRECTORY);
776
+                if ($success) {
777
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
778
+                } else {
779
+                    $errors[] = [
780
+                        'error' => $l->t('Cannot create "data" directory'),
781
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
782
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
783
+                    ];
784
+                }
785
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
786
+                //common hint for all file permissions error messages
787
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
788
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
789
+                $errors[] = [
790
+                    'error' => 'Your data directory is not writable',
791
+                    'hint' => $permissionsHint
792
+                ];
793
+            } else {
794
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
795
+            }
796
+        }
797
+
798
+        if (!OC_Util::isSetLocaleWorking()) {
799
+            $errors[] = array(
800
+                'error' => $l->t('Setting locale to %s failed',
801
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
802
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
803
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
804
+            );
805
+        }
806
+
807
+        // Contains the dependencies that should be checked against
808
+        // classes = class_exists
809
+        // functions = function_exists
810
+        // defined = defined
811
+        // ini = ini_get
812
+        // If the dependency is not found the missing module name is shown to the EndUser
813
+        // When adding new checks always verify that they pass on Travis as well
814
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
815
+        $dependencies = array(
816
+            'classes' => array(
817
+                'ZipArchive' => 'zip',
818
+                'DOMDocument' => 'dom',
819
+                'XMLWriter' => 'XMLWriter',
820
+                'XMLReader' => 'XMLReader',
821
+            ),
822
+            'functions' => [
823
+                'xml_parser_create' => 'libxml',
824
+                'mb_strcut' => 'mb multibyte',
825
+                'ctype_digit' => 'ctype',
826
+                'json_encode' => 'JSON',
827
+                'gd_info' => 'GD',
828
+                'gzencode' => 'zlib',
829
+                'iconv' => 'iconv',
830
+                'simplexml_load_string' => 'SimpleXML',
831
+                'hash' => 'HASH Message Digest Framework',
832
+                'curl_init' => 'cURL',
833
+                'openssl_verify' => 'OpenSSL',
834
+            ],
835
+            'defined' => array(
836
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
837
+            ),
838
+            'ini' => [
839
+                'default_charset' => 'UTF-8',
840
+            ],
841
+        );
842
+        $missingDependencies = array();
843
+        $invalidIniSettings = [];
844
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
845
+
846
+        /**
847
+         * FIXME: The dependency check does not work properly on HHVM on the moment
848
+         *        and prevents installation. Once HHVM is more compatible with our
849
+         *        approach to check for these values we should re-enable those
850
+         *        checks.
851
+         */
852
+        $iniWrapper = \OC::$server->getIniWrapper();
853
+        if (!self::runningOnHhvm()) {
854
+            foreach ($dependencies['classes'] as $class => $module) {
855
+                if (!class_exists($class)) {
856
+                    $missingDependencies[] = $module;
857
+                }
858
+            }
859
+            foreach ($dependencies['functions'] as $function => $module) {
860
+                if (!function_exists($function)) {
861
+                    $missingDependencies[] = $module;
862
+                }
863
+            }
864
+            foreach ($dependencies['defined'] as $defined => $module) {
865
+                if (!defined($defined)) {
866
+                    $missingDependencies[] = $module;
867
+                }
868
+            }
869
+            foreach ($dependencies['ini'] as $setting => $expected) {
870
+                if (is_bool($expected)) {
871
+                    if ($iniWrapper->getBool($setting) !== $expected) {
872
+                        $invalidIniSettings[] = [$setting, $expected];
873
+                    }
874
+                }
875
+                if (is_int($expected)) {
876
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
877
+                        $invalidIniSettings[] = [$setting, $expected];
878
+                    }
879
+                }
880
+                if (is_string($expected)) {
881
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
882
+                        $invalidIniSettings[] = [$setting, $expected];
883
+                    }
884
+                }
885
+            }
886
+        }
887
+
888
+        foreach($missingDependencies as $missingDependency) {
889
+            $errors[] = array(
890
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
891
+                'hint' => $moduleHint
892
+            );
893
+            $webServerRestart = true;
894
+        }
895
+        foreach($invalidIniSettings as $setting) {
896
+            if(is_bool($setting[1])) {
897
+                $setting[1] = ($setting[1]) ? 'on' : 'off';
898
+            }
899
+            $errors[] = [
900
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
901
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
902
+            ];
903
+            $webServerRestart = true;
904
+        }
905
+
906
+        /**
907
+         * The mbstring.func_overload check can only be performed if the mbstring
908
+         * module is installed as it will return null if the checking setting is
909
+         * not available and thus a check on the boolean value fails.
910
+         *
911
+         * TODO: Should probably be implemented in the above generic dependency
912
+         *       check somehow in the long-term.
913
+         */
914
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
915
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
916
+            $errors[] = array(
917
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
918
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
919
+            );
920
+        }
921
+
922
+        if(function_exists('xml_parser_create') &&
923
+            LIBXML_LOADED_VERSION < 20700 ) {
924
+            $version = LIBXML_LOADED_VERSION;
925
+            $major = floor($version/10000);
926
+            $version -= ($major * 10000);
927
+            $minor = floor($version/100);
928
+            $version -= ($minor * 100);
929
+            $patch = $version;
930
+            $errors[] = array(
931
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
932
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
933
+            );
934
+        }
935
+
936
+        if (!self::isAnnotationsWorking()) {
937
+            $errors[] = array(
938
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
939
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
940
+            );
941
+        }
942
+
943
+        if (!\OC::$CLI && $webServerRestart) {
944
+            $errors[] = array(
945
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
946
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
947
+            );
948
+        }
949
+
950
+        $errors = array_merge($errors, self::checkDatabaseVersion());
951
+
952
+        // Cache the result of this function
953
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
954
+
955
+        return $errors;
956
+    }
957
+
958
+    /**
959
+     * Check the database version
960
+     *
961
+     * @return array errors array
962
+     */
963
+    public static function checkDatabaseVersion() {
964
+        $l = \OC::$server->getL10N('lib');
965
+        $errors = array();
966
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
967
+        if ($dbType === 'pgsql') {
968
+            // check PostgreSQL version
969
+            try {
970
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
971
+                $data = $result->fetchRow();
972
+                if (isset($data['server_version'])) {
973
+                    $version = $data['server_version'];
974
+                    if (version_compare($version, '9.0.0', '<')) {
975
+                        $errors[] = array(
976
+                            'error' => $l->t('PostgreSQL >= 9 required'),
977
+                            'hint' => $l->t('Please upgrade your database version')
978
+                        );
979
+                    }
980
+                }
981
+            } catch (\Doctrine\DBAL\DBALException $e) {
982
+                $logger = \OC::$server->getLogger();
983
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
984
+                $logger->logException($e);
985
+            }
986
+        }
987
+        return $errors;
988
+    }
989
+
990
+    /**
991
+     * Check for correct file permissions of data directory
992
+     *
993
+     * @param string $dataDirectory
994
+     * @return array arrays with error messages and hints
995
+     */
996
+    public static function checkDataDirectoryPermissions($dataDirectory) {
997
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
998
+            return  [];
999
+        }
1000
+        $l = \OC::$server->getL10N('lib');
1001
+        $errors = [];
1002
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1003
+            . ' cannot be listed by other users.');
1004
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1005
+        if (substr($perms, -1) !== '0') {
1006
+            chmod($dataDirectory, 0770);
1007
+            clearstatcache();
1008
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1009
+            if ($perms[2] !== '0') {
1010
+                $errors[] = [
1011
+                    'error' => $l->t('Your data directory is readable by other users'),
1012
+                    'hint' => $permissionsModHint
1013
+                ];
1014
+            }
1015
+        }
1016
+        return $errors;
1017
+    }
1018
+
1019
+    /**
1020
+     * Check that the data directory exists and is valid by
1021
+     * checking the existence of the ".ocdata" file.
1022
+     *
1023
+     * @param string $dataDirectory data directory path
1024
+     * @return array errors found
1025
+     */
1026
+    public static function checkDataDirectoryValidity($dataDirectory) {
1027
+        $l = \OC::$server->getL10N('lib');
1028
+        $errors = [];
1029
+        if ($dataDirectory[0] !== '/') {
1030
+            $errors[] = [
1031
+                'error' => $l->t('Your data directory must be an absolute path'),
1032
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1033
+            ];
1034
+        }
1035
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1036
+            $errors[] = [
1037
+                'error' => $l->t('Your data directory is invalid'),
1038
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1039
+                    ' in the root of the data directory.')
1040
+            ];
1041
+        }
1042
+        return $errors;
1043
+    }
1044
+
1045
+    /**
1046
+     * Check if the user is logged in, redirects to home if not. With
1047
+     * redirect URL parameter to the request URI.
1048
+     *
1049
+     * @return void
1050
+     */
1051
+    public static function checkLoggedIn() {
1052
+        // Check if we are a user
1053
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1054
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1055
+                        'core.login.showLoginForm',
1056
+                        [
1057
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1058
+                        ]
1059
+                    )
1060
+            );
1061
+            exit();
1062
+        }
1063
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1064
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1065
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1066
+            exit();
1067
+        }
1068
+    }
1069
+
1070
+    /**
1071
+     * Check if the user is a admin, redirects to home if not
1072
+     *
1073
+     * @return void
1074
+     */
1075
+    public static function checkAdminUser() {
1076
+        OC_Util::checkLoggedIn();
1077
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1078
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1079
+            exit();
1080
+        }
1081
+    }
1082
+
1083
+    /**
1084
+     * Check if the user is a subadmin, redirects to home if not
1085
+     *
1086
+     * @return null|boolean $groups where the current user is subadmin
1087
+     */
1088
+    public static function checkSubAdminUser() {
1089
+        OC_Util::checkLoggedIn();
1090
+        $userObject = \OC::$server->getUserSession()->getUser();
1091
+        $isSubAdmin = false;
1092
+        if($userObject !== null) {
1093
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1094
+        }
1095
+
1096
+        if (!$isSubAdmin) {
1097
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1098
+            exit();
1099
+        }
1100
+        return true;
1101
+    }
1102
+
1103
+    /**
1104
+     * Returns the URL of the default page
1105
+     * based on the system configuration and
1106
+     * the apps visible for the current user
1107
+     *
1108
+     * @return string URL
1109
+     * @suppress PhanDeprecatedFunction
1110
+     */
1111
+    public static function getDefaultPageUrl() {
1112
+        $urlGenerator = \OC::$server->getURLGenerator();
1113
+        // Deny the redirect if the URL contains a @
1114
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1115
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1116
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1117
+        } else {
1118
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1119
+            if ($defaultPage) {
1120
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1121
+            } else {
1122
+                $appId = 'files';
1123
+                $config = \OC::$server->getConfig();
1124
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1125
+                // find the first app that is enabled for the current user
1126
+                foreach ($defaultApps as $defaultApp) {
1127
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1128
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1129
+                        $appId = $defaultApp;
1130
+                        break;
1131
+                    }
1132
+                }
1133
+
1134
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1135
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1136
+                } else {
1137
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1138
+                }
1139
+            }
1140
+        }
1141
+        return $location;
1142
+    }
1143
+
1144
+    /**
1145
+     * Redirect to the user default page
1146
+     *
1147
+     * @return void
1148
+     */
1149
+    public static function redirectToDefaultPage() {
1150
+        $location = self::getDefaultPageUrl();
1151
+        header('Location: ' . $location);
1152
+        exit();
1153
+    }
1154
+
1155
+    /**
1156
+     * get an id unique for this instance
1157
+     *
1158
+     * @return string
1159
+     */
1160
+    public static function getInstanceId() {
1161
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1162
+        if (is_null($id)) {
1163
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1164
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1165
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1166
+        }
1167
+        return $id;
1168
+    }
1169
+
1170
+    /**
1171
+     * Public function to sanitize HTML
1172
+     *
1173
+     * This function is used to sanitize HTML and should be applied on any
1174
+     * string or array of strings before displaying it on a web page.
1175
+     *
1176
+     * @param string|array $value
1177
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1178
+     */
1179
+    public static function sanitizeHTML($value) {
1180
+        if (is_array($value)) {
1181
+            $value = array_map(function($value) {
1182
+                return self::sanitizeHTML($value);
1183
+            }, $value);
1184
+        } else {
1185
+            // Specify encoding for PHP<5.4
1186
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1187
+        }
1188
+        return $value;
1189
+    }
1190
+
1191
+    /**
1192
+     * Public function to encode url parameters
1193
+     *
1194
+     * This function is used to encode path to file before output.
1195
+     * Encoding is done according to RFC 3986 with one exception:
1196
+     * Character '/' is preserved as is.
1197
+     *
1198
+     * @param string $component part of URI to encode
1199
+     * @return string
1200
+     */
1201
+    public static function encodePath($component) {
1202
+        $encoded = rawurlencode($component);
1203
+        $encoded = str_replace('%2F', '/', $encoded);
1204
+        return $encoded;
1205
+    }
1206
+
1207
+
1208
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1209
+        // php dev server does not support htaccess
1210
+        if (php_sapi_name() === 'cli-server') {
1211
+            return false;
1212
+        }
1213
+
1214
+        // testdata
1215
+        $fileName = '/htaccesstest.txt';
1216
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1217
+
1218
+        // creating a test file
1219
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1220
+
1221
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1222
+            return false;
1223
+        }
1224
+
1225
+        $fp = @fopen($testFile, 'w');
1226
+        if (!$fp) {
1227
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1228
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1229
+        }
1230
+        fwrite($fp, $testContent);
1231
+        fclose($fp);
1232
+
1233
+        return $testContent;
1234
+    }
1235
+
1236
+    /**
1237
+     * Check if the .htaccess file is working
1238
+     * @param \OCP\IConfig $config
1239
+     * @return bool
1240
+     * @throws Exception
1241
+     * @throws \OC\HintException If the test file can't get written.
1242
+     */
1243
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1244
+
1245
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1246
+            return true;
1247
+        }
1248
+
1249
+        $testContent = $this->createHtaccessTestFile($config);
1250
+        if ($testContent === false) {
1251
+            return false;
1252
+        }
1253
+
1254
+        $fileName = '/htaccesstest.txt';
1255
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1256
+
1257
+        // accessing the file via http
1258
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1259
+        try {
1260
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1261
+        } catch (\Exception $e) {
1262
+            $content = false;
1263
+        }
1264
+
1265
+        // cleanup
1266
+        @unlink($testFile);
1267
+
1268
+        /*
1269 1269
 		 * If the content is not equal to test content our .htaccess
1270 1270
 		 * is working as required
1271 1271
 		 */
1272
-		return $content !== $testContent;
1273
-	}
1274
-
1275
-	/**
1276
-	 * Check if the setlocal call does not work. This can happen if the right
1277
-	 * local packages are not available on the server.
1278
-	 *
1279
-	 * @return bool
1280
-	 */
1281
-	public static function isSetLocaleWorking() {
1282
-		\Patchwork\Utf8\Bootup::initLocale();
1283
-		if ('' === basename('§')) {
1284
-			return false;
1285
-		}
1286
-		return true;
1287
-	}
1288
-
1289
-	/**
1290
-	 * Check if it's possible to get the inline annotations
1291
-	 *
1292
-	 * @return bool
1293
-	 */
1294
-	public static function isAnnotationsWorking() {
1295
-		$reflection = new \ReflectionMethod(__METHOD__);
1296
-		$docs = $reflection->getDocComment();
1297
-
1298
-		return (is_string($docs) && strlen($docs) > 50);
1299
-	}
1300
-
1301
-	/**
1302
-	 * Check if the PHP module fileinfo is loaded.
1303
-	 *
1304
-	 * @return bool
1305
-	 */
1306
-	public static function fileInfoLoaded() {
1307
-		return function_exists('finfo_open');
1308
-	}
1309
-
1310
-	/**
1311
-	 * clear all levels of output buffering
1312
-	 *
1313
-	 * @return void
1314
-	 */
1315
-	public static function obEnd() {
1316
-		while (ob_get_level()) {
1317
-			ob_end_clean();
1318
-		}
1319
-	}
1320
-
1321
-	/**
1322
-	 * Checks whether the server is running on Mac OS X
1323
-	 *
1324
-	 * @return bool true if running on Mac OS X, false otherwise
1325
-	 */
1326
-	public static function runningOnMac() {
1327
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1328
-	}
1329
-
1330
-	/**
1331
-	 * Checks whether server is running on HHVM
1332
-	 *
1333
-	 * @return bool True if running on HHVM, false otherwise
1334
-	 */
1335
-	public static function runningOnHhvm() {
1336
-		return defined('HHVM_VERSION');
1337
-	}
1338
-
1339
-	/**
1340
-	 * Handles the case that there may not be a theme, then check if a "default"
1341
-	 * theme exists and take that one
1342
-	 *
1343
-	 * @return string the theme
1344
-	 */
1345
-	public static function getTheme() {
1346
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1347
-
1348
-		if ($theme === '') {
1349
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1350
-				$theme = 'default';
1351
-			}
1352
-		}
1353
-
1354
-		return $theme;
1355
-	}
1356
-
1357
-	/**
1358
-	 * Clear a single file from the opcode cache
1359
-	 * This is useful for writing to the config file
1360
-	 * in case the opcode cache does not re-validate files
1361
-	 * Returns true if successful, false if unsuccessful:
1362
-	 * caller should fall back on clearing the entire cache
1363
-	 * with clearOpcodeCache() if unsuccessful
1364
-	 *
1365
-	 * @param string $path the path of the file to clear from the cache
1366
-	 * @return bool true if underlying function returns true, otherwise false
1367
-	 */
1368
-	public static function deleteFromOpcodeCache($path) {
1369
-		$ret = false;
1370
-		if ($path) {
1371
-			// APC >= 3.1.1
1372
-			if (function_exists('apc_delete_file')) {
1373
-				$ret = @apc_delete_file($path);
1374
-			}
1375
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1376
-			if (function_exists('opcache_invalidate')) {
1377
-				$ret = opcache_invalidate($path);
1378
-			}
1379
-		}
1380
-		return $ret;
1381
-	}
1382
-
1383
-	/**
1384
-	 * Clear the opcode cache if one exists
1385
-	 * This is necessary for writing to the config file
1386
-	 * in case the opcode cache does not re-validate files
1387
-	 *
1388
-	 * @return void
1389
-	 * @suppress PhanDeprecatedFunction
1390
-	 * @suppress PhanUndeclaredConstant
1391
-	 */
1392
-	public static function clearOpcodeCache() {
1393
-		// APC
1394
-		if (function_exists('apc_clear_cache')) {
1395
-			apc_clear_cache();
1396
-		}
1397
-		// Zend Opcache
1398
-		if (function_exists('accelerator_reset')) {
1399
-			accelerator_reset();
1400
-		}
1401
-		// XCache
1402
-		if (function_exists('xcache_clear_cache')) {
1403
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1404
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1405
-			} else {
1406
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1407
-			}
1408
-		}
1409
-		// Opcache (PHP >= 5.5)
1410
-		if (function_exists('opcache_reset')) {
1411
-			opcache_reset();
1412
-		}
1413
-	}
1414
-
1415
-	/**
1416
-	 * Normalize a unicode string
1417
-	 *
1418
-	 * @param string $value a not normalized string
1419
-	 * @return bool|string
1420
-	 */
1421
-	public static function normalizeUnicode($value) {
1422
-		if(Normalizer::isNormalized($value)) {
1423
-			return $value;
1424
-		}
1425
-
1426
-		$normalizedValue = Normalizer::normalize($value);
1427
-		if ($normalizedValue === null || $normalizedValue === false) {
1428
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1429
-			return $value;
1430
-		}
1431
-
1432
-		return $normalizedValue;
1433
-	}
1434
-
1435
-	/**
1436
-	 * A human readable string is generated based on version and build number
1437
-	 *
1438
-	 * @return string
1439
-	 */
1440
-	public static function getHumanVersion() {
1441
-		$version = OC_Util::getVersionString();
1442
-		$build = OC_Util::getBuild();
1443
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1444
-			$version .= ' Build:' . $build;
1445
-		}
1446
-		return $version;
1447
-	}
1448
-
1449
-	/**
1450
-	 * Returns whether the given file name is valid
1451
-	 *
1452
-	 * @param string $file file name to check
1453
-	 * @return bool true if the file name is valid, false otherwise
1454
-	 * @deprecated use \OC\Files\View::verifyPath()
1455
-	 */
1456
-	public static function isValidFileName($file) {
1457
-		$trimmed = trim($file);
1458
-		if ($trimmed === '') {
1459
-			return false;
1460
-		}
1461
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1462
-			return false;
1463
-		}
1464
-
1465
-		// detect part files
1466
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1467
-			return false;
1468
-		}
1469
-
1470
-		foreach (str_split($trimmed) as $char) {
1471
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1472
-				return false;
1473
-			}
1474
-		}
1475
-		return true;
1476
-	}
1477
-
1478
-	/**
1479
-	 * Check whether the instance needs to perform an upgrade,
1480
-	 * either when the core version is higher or any app requires
1481
-	 * an upgrade.
1482
-	 *
1483
-	 * @param \OC\SystemConfig $config
1484
-	 * @return bool whether the core or any app needs an upgrade
1485
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1486
-	 */
1487
-	public static function needUpgrade(\OC\SystemConfig $config) {
1488
-		if ($config->getValue('installed', false)) {
1489
-			$installedVersion = $config->getValue('version', '0.0.0');
1490
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1491
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1492
-			if ($versionDiff > 0) {
1493
-				return true;
1494
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1495
-				// downgrade with debug
1496
-				$installedMajor = explode('.', $installedVersion);
1497
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1498
-				$currentMajor = explode('.', $currentVersion);
1499
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1500
-				if ($installedMajor === $currentMajor) {
1501
-					// Same major, allow downgrade for developers
1502
-					return true;
1503
-				} else {
1504
-					// downgrade attempt, throw exception
1505
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1506
-				}
1507
-			} else if ($versionDiff < 0) {
1508
-				// downgrade attempt, throw exception
1509
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1510
-			}
1511
-
1512
-			// also check for upgrades for apps (independently from the user)
1513
-			$apps = \OC_App::getEnabledApps(false, true);
1514
-			$shouldUpgrade = false;
1515
-			foreach ($apps as $app) {
1516
-				if (\OC_App::shouldUpgrade($app)) {
1517
-					$shouldUpgrade = true;
1518
-					break;
1519
-				}
1520
-			}
1521
-			return $shouldUpgrade;
1522
-		} else {
1523
-			return false;
1524
-		}
1525
-	}
1272
+        return $content !== $testContent;
1273
+    }
1274
+
1275
+    /**
1276
+     * Check if the setlocal call does not work. This can happen if the right
1277
+     * local packages are not available on the server.
1278
+     *
1279
+     * @return bool
1280
+     */
1281
+    public static function isSetLocaleWorking() {
1282
+        \Patchwork\Utf8\Bootup::initLocale();
1283
+        if ('' === basename('§')) {
1284
+            return false;
1285
+        }
1286
+        return true;
1287
+    }
1288
+
1289
+    /**
1290
+     * Check if it's possible to get the inline annotations
1291
+     *
1292
+     * @return bool
1293
+     */
1294
+    public static function isAnnotationsWorking() {
1295
+        $reflection = new \ReflectionMethod(__METHOD__);
1296
+        $docs = $reflection->getDocComment();
1297
+
1298
+        return (is_string($docs) && strlen($docs) > 50);
1299
+    }
1300
+
1301
+    /**
1302
+     * Check if the PHP module fileinfo is loaded.
1303
+     *
1304
+     * @return bool
1305
+     */
1306
+    public static function fileInfoLoaded() {
1307
+        return function_exists('finfo_open');
1308
+    }
1309
+
1310
+    /**
1311
+     * clear all levels of output buffering
1312
+     *
1313
+     * @return void
1314
+     */
1315
+    public static function obEnd() {
1316
+        while (ob_get_level()) {
1317
+            ob_end_clean();
1318
+        }
1319
+    }
1320
+
1321
+    /**
1322
+     * Checks whether the server is running on Mac OS X
1323
+     *
1324
+     * @return bool true if running on Mac OS X, false otherwise
1325
+     */
1326
+    public static function runningOnMac() {
1327
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1328
+    }
1329
+
1330
+    /**
1331
+     * Checks whether server is running on HHVM
1332
+     *
1333
+     * @return bool True if running on HHVM, false otherwise
1334
+     */
1335
+    public static function runningOnHhvm() {
1336
+        return defined('HHVM_VERSION');
1337
+    }
1338
+
1339
+    /**
1340
+     * Handles the case that there may not be a theme, then check if a "default"
1341
+     * theme exists and take that one
1342
+     *
1343
+     * @return string the theme
1344
+     */
1345
+    public static function getTheme() {
1346
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1347
+
1348
+        if ($theme === '') {
1349
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1350
+                $theme = 'default';
1351
+            }
1352
+        }
1353
+
1354
+        return $theme;
1355
+    }
1356
+
1357
+    /**
1358
+     * Clear a single file from the opcode cache
1359
+     * This is useful for writing to the config file
1360
+     * in case the opcode cache does not re-validate files
1361
+     * Returns true if successful, false if unsuccessful:
1362
+     * caller should fall back on clearing the entire cache
1363
+     * with clearOpcodeCache() if unsuccessful
1364
+     *
1365
+     * @param string $path the path of the file to clear from the cache
1366
+     * @return bool true if underlying function returns true, otherwise false
1367
+     */
1368
+    public static function deleteFromOpcodeCache($path) {
1369
+        $ret = false;
1370
+        if ($path) {
1371
+            // APC >= 3.1.1
1372
+            if (function_exists('apc_delete_file')) {
1373
+                $ret = @apc_delete_file($path);
1374
+            }
1375
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1376
+            if (function_exists('opcache_invalidate')) {
1377
+                $ret = opcache_invalidate($path);
1378
+            }
1379
+        }
1380
+        return $ret;
1381
+    }
1382
+
1383
+    /**
1384
+     * Clear the opcode cache if one exists
1385
+     * This is necessary for writing to the config file
1386
+     * in case the opcode cache does not re-validate files
1387
+     *
1388
+     * @return void
1389
+     * @suppress PhanDeprecatedFunction
1390
+     * @suppress PhanUndeclaredConstant
1391
+     */
1392
+    public static function clearOpcodeCache() {
1393
+        // APC
1394
+        if (function_exists('apc_clear_cache')) {
1395
+            apc_clear_cache();
1396
+        }
1397
+        // Zend Opcache
1398
+        if (function_exists('accelerator_reset')) {
1399
+            accelerator_reset();
1400
+        }
1401
+        // XCache
1402
+        if (function_exists('xcache_clear_cache')) {
1403
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1404
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1405
+            } else {
1406
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1407
+            }
1408
+        }
1409
+        // Opcache (PHP >= 5.5)
1410
+        if (function_exists('opcache_reset')) {
1411
+            opcache_reset();
1412
+        }
1413
+    }
1414
+
1415
+    /**
1416
+     * Normalize a unicode string
1417
+     *
1418
+     * @param string $value a not normalized string
1419
+     * @return bool|string
1420
+     */
1421
+    public static function normalizeUnicode($value) {
1422
+        if(Normalizer::isNormalized($value)) {
1423
+            return $value;
1424
+        }
1425
+
1426
+        $normalizedValue = Normalizer::normalize($value);
1427
+        if ($normalizedValue === null || $normalizedValue === false) {
1428
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1429
+            return $value;
1430
+        }
1431
+
1432
+        return $normalizedValue;
1433
+    }
1434
+
1435
+    /**
1436
+     * A human readable string is generated based on version and build number
1437
+     *
1438
+     * @return string
1439
+     */
1440
+    public static function getHumanVersion() {
1441
+        $version = OC_Util::getVersionString();
1442
+        $build = OC_Util::getBuild();
1443
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1444
+            $version .= ' Build:' . $build;
1445
+        }
1446
+        return $version;
1447
+    }
1448
+
1449
+    /**
1450
+     * Returns whether the given file name is valid
1451
+     *
1452
+     * @param string $file file name to check
1453
+     * @return bool true if the file name is valid, false otherwise
1454
+     * @deprecated use \OC\Files\View::verifyPath()
1455
+     */
1456
+    public static function isValidFileName($file) {
1457
+        $trimmed = trim($file);
1458
+        if ($trimmed === '') {
1459
+            return false;
1460
+        }
1461
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1462
+            return false;
1463
+        }
1464
+
1465
+        // detect part files
1466
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1467
+            return false;
1468
+        }
1469
+
1470
+        foreach (str_split($trimmed) as $char) {
1471
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1472
+                return false;
1473
+            }
1474
+        }
1475
+        return true;
1476
+    }
1477
+
1478
+    /**
1479
+     * Check whether the instance needs to perform an upgrade,
1480
+     * either when the core version is higher or any app requires
1481
+     * an upgrade.
1482
+     *
1483
+     * @param \OC\SystemConfig $config
1484
+     * @return bool whether the core or any app needs an upgrade
1485
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1486
+     */
1487
+    public static function needUpgrade(\OC\SystemConfig $config) {
1488
+        if ($config->getValue('installed', false)) {
1489
+            $installedVersion = $config->getValue('version', '0.0.0');
1490
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1491
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1492
+            if ($versionDiff > 0) {
1493
+                return true;
1494
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1495
+                // downgrade with debug
1496
+                $installedMajor = explode('.', $installedVersion);
1497
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1498
+                $currentMajor = explode('.', $currentVersion);
1499
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1500
+                if ($installedMajor === $currentMajor) {
1501
+                    // Same major, allow downgrade for developers
1502
+                    return true;
1503
+                } else {
1504
+                    // downgrade attempt, throw exception
1505
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1506
+                }
1507
+            } else if ($versionDiff < 0) {
1508
+                // downgrade attempt, throw exception
1509
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1510
+            }
1511
+
1512
+            // also check for upgrades for apps (independently from the user)
1513
+            $apps = \OC_App::getEnabledApps(false, true);
1514
+            $shouldUpgrade = false;
1515
+            foreach ($apps as $app) {
1516
+                if (\OC_App::shouldUpgrade($app)) {
1517
+                    $shouldUpgrade = true;
1518
+                    break;
1519
+                }
1520
+            }
1521
+            return $shouldUpgrade;
1522
+        } else {
1523
+            return false;
1524
+        }
1525
+    }
1526 1526
 
1527 1527
 }
Please login to merge, or discard this patch.
lib/private/legacy/app.php 1 patch
Indentation   +1180 added lines, -1180 removed lines patch added patch discarded remove patch
@@ -63,1184 +63,1184 @@
 block discarded – undo
63 63
  * upgrading and removing apps.
64 64
  */
65 65
 class OC_App {
66
-	static private $appVersion = [];
67
-	static private $adminForms = array();
68
-	static private $personalForms = array();
69
-	static private $appInfo = array();
70
-	static private $appTypes = array();
71
-	static private $loadedApps = array();
72
-	static private $altLogin = array();
73
-	static private $alreadyRegistered = [];
74
-	const officialApp = 200;
75
-
76
-	/**
77
-	 * clean the appId
78
-	 *
79
-	 * @param string|boolean $app AppId that needs to be cleaned
80
-	 * @return string
81
-	 */
82
-	public static function cleanAppId($app) {
83
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
84
-	}
85
-
86
-	/**
87
-	 * Check if an app is loaded
88
-	 *
89
-	 * @param string $app
90
-	 * @return bool
91
-	 */
92
-	public static function isAppLoaded($app) {
93
-		return in_array($app, self::$loadedApps, true);
94
-	}
95
-
96
-	/**
97
-	 * loads all apps
98
-	 *
99
-	 * @param string[] | string | null $types
100
-	 * @return bool
101
-	 *
102
-	 * This function walks through the ownCloud directory and loads all apps
103
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
104
-	 * exists.
105
-	 *
106
-	 * if $types is set, only apps of those types will be loaded
107
-	 */
108
-	public static function loadApps($types = null) {
109
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
110
-			return false;
111
-		}
112
-		// Load the enabled apps here
113
-		$apps = self::getEnabledApps();
114
-
115
-		// Add each apps' folder as allowed class path
116
-		foreach($apps as $app) {
117
-			$path = self::getAppPath($app);
118
-			if($path !== false) {
119
-				self::registerAutoloading($app, $path);
120
-			}
121
-		}
122
-
123
-		// prevent app.php from printing output
124
-		ob_start();
125
-		foreach ($apps as $app) {
126
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
127
-				self::loadApp($app);
128
-			}
129
-		}
130
-		ob_end_clean();
131
-
132
-		return true;
133
-	}
134
-
135
-	/**
136
-	 * load a single app
137
-	 *
138
-	 * @param string $app
139
-	 */
140
-	public static function loadApp($app) {
141
-		self::$loadedApps[] = $app;
142
-		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
144
-			return;
145
-		}
146
-
147
-		// in case someone calls loadApp() directly
148
-		self::registerAutoloading($app, $appPath);
149
-
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
-			self::requireAppFile($app);
153
-			if (self::isType($app, array('authentication'))) {
154
-				// since authentication apps affect the "is app enabled for group" check,
155
-				// the enabled apps cache needs to be cleared to make sure that the
156
-				// next time getEnableApps() is called it will also include apps that were
157
-				// enabled for groups
158
-				self::$enabledAppsCache = array();
159
-			}
160
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
161
-		}
162
-
163
-		$info = self::getAppInfo($app);
164
-		if (!empty($info['activity']['filters'])) {
165
-			foreach ($info['activity']['filters'] as $filter) {
166
-				\OC::$server->getActivityManager()->registerFilter($filter);
167
-			}
168
-		}
169
-		if (!empty($info['activity']['settings'])) {
170
-			foreach ($info['activity']['settings'] as $setting) {
171
-				\OC::$server->getActivityManager()->registerSetting($setting);
172
-			}
173
-		}
174
-		if (!empty($info['activity']['providers'])) {
175
-			foreach ($info['activity']['providers'] as $provider) {
176
-				\OC::$server->getActivityManager()->registerProvider($provider);
177
-			}
178
-		}
179
-		if (!empty($info['collaboration']['plugins'])) {
180
-			// deal with one or many plugin entries
181
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
182
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
183
-			foreach ($plugins as $plugin) {
184
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
185
-					$pluginInfo = [
186
-						'shareType' => $plugin['@attributes']['share-type'],
187
-						'class' => $plugin['@value'],
188
-					];
189
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
190
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
191
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
192
-				}
193
-			}
194
-		}
195
-	}
196
-
197
-	/**
198
-	 * @internal
199
-	 * @param string $app
200
-	 * @param string $path
201
-	 */
202
-	public static function registerAutoloading($app, $path) {
203
-		$key = $app . '-' . $path;
204
-		if(isset(self::$alreadyRegistered[$key])) {
205
-			return;
206
-		}
207
-
208
-		self::$alreadyRegistered[$key] = true;
209
-
210
-		// Register on PSR-4 composer autoloader
211
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
212
-		\OC::$server->registerNamespace($app, $appNamespace);
213
-
214
-		if (file_exists($path . '/composer/autoload.php')) {
215
-			require_once $path . '/composer/autoload.php';
216
-		} else {
217
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
218
-			// Register on legacy autoloader
219
-			\OC::$loader->addValidRoot($path);
220
-		}
221
-
222
-		// Register Test namespace only when testing
223
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
224
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
225
-		}
226
-	}
227
-
228
-	/**
229
-	 * Load app.php from the given app
230
-	 *
231
-	 * @param string $app app name
232
-	 */
233
-	private static function requireAppFile($app) {
234
-		try {
235
-			// encapsulated here to avoid variable scope conflicts
236
-			require_once $app . '/appinfo/app.php';
237
-		} catch (Error $ex) {
238
-			\OC::$server->getLogger()->logException($ex);
239
-			if (!\OC::$server->getAppManager()->isShipped($app)) {
240
-				// Only disable apps which are not shipped
241
-				self::disable($app);
242
-			}
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * check if an app is of a specific type
248
-	 *
249
-	 * @param string $app
250
-	 * @param string|array $types
251
-	 * @return bool
252
-	 */
253
-	public static function isType($app, $types) {
254
-		if (is_string($types)) {
255
-			$types = array($types);
256
-		}
257
-		$appTypes = self::getAppTypes($app);
258
-		foreach ($types as $type) {
259
-			if (array_search($type, $appTypes) !== false) {
260
-				return true;
261
-			}
262
-		}
263
-		return false;
264
-	}
265
-
266
-	/**
267
-	 * get the types of an app
268
-	 *
269
-	 * @param string $app
270
-	 * @return array
271
-	 */
272
-	private static function getAppTypes($app) {
273
-		//load the cache
274
-		if (count(self::$appTypes) == 0) {
275
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
276
-		}
277
-
278
-		if (isset(self::$appTypes[$app])) {
279
-			return explode(',', self::$appTypes[$app]);
280
-		} else {
281
-			return array();
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * read app types from info.xml and cache them in the database
287
-	 */
288
-	public static function setAppTypes($app) {
289
-		$appData = self::getAppInfo($app);
290
-		if(!is_array($appData)) {
291
-			return;
292
-		}
293
-
294
-		if (isset($appData['types'])) {
295
-			$appTypes = implode(',', $appData['types']);
296
-		} else {
297
-			$appTypes = '';
298
-			$appData['types'] = [];
299
-		}
300
-
301
-		\OC::$server->getConfig()->setAppValue($app, 'types', $appTypes);
302
-
303
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
304
-			$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes');
305
-			if ($enabled !== 'yes' && $enabled !== 'no') {
306
-				\OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes');
307
-			}
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * get all enabled apps
313
-	 */
314
-	protected static $enabledAppsCache = array();
315
-
316
-	/**
317
-	 * Returns apps enabled for the current user.
318
-	 *
319
-	 * @param bool $forceRefresh whether to refresh the cache
320
-	 * @param bool $all whether to return apps for all users, not only the
321
-	 * currently logged in one
322
-	 * @return string[]
323
-	 */
324
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
325
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
326
-			return array();
327
-		}
328
-		// in incognito mode or when logged out, $user will be false,
329
-		// which is also the case during an upgrade
330
-		$appManager = \OC::$server->getAppManager();
331
-		if ($all) {
332
-			$user = null;
333
-		} else {
334
-			$user = \OC::$server->getUserSession()->getUser();
335
-		}
336
-
337
-		if (is_null($user)) {
338
-			$apps = $appManager->getInstalledApps();
339
-		} else {
340
-			$apps = $appManager->getEnabledAppsForUser($user);
341
-		}
342
-		$apps = array_filter($apps, function ($app) {
343
-			return $app !== 'files';//we add this manually
344
-		});
345
-		sort($apps);
346
-		array_unshift($apps, 'files');
347
-		return $apps;
348
-	}
349
-
350
-	/**
351
-	 * checks whether or not an app is enabled
352
-	 *
353
-	 * @param string $app app
354
-	 * @return bool
355
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
356
-	 *
357
-	 * This function checks whether or not an app is enabled.
358
-	 */
359
-	public static function isEnabled($app) {
360
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
361
-	}
362
-
363
-	/**
364
-	 * enables an app
365
-	 *
366
-	 * @param string $appId
367
-	 * @param array $groups (optional) when set, only these groups will have access to the app
368
-	 * @throws \Exception
369
-	 * @return void
370
-	 *
371
-	 * This function set an app as enabled in appconfig.
372
-	 */
373
-	public function enable($appId,
374
-						   $groups = null) {
375
-		self::$enabledAppsCache = []; // flush
376
-
377
-		// Check if app is already downloaded
378
-		$installer = \OC::$server->query(Installer::class);
379
-		$isDownloaded = $installer->isDownloaded($appId);
380
-
381
-		if(!$isDownloaded) {
382
-			$installer->downloadApp($appId);
383
-		}
384
-
385
-		$installer->installApp($appId);
386
-
387
-		$appManager = \OC::$server->getAppManager();
388
-		if (!is_null($groups)) {
389
-			$groupManager = \OC::$server->getGroupManager();
390
-			$groupsList = [];
391
-			foreach ($groups as $group) {
392
-				$groupItem = $groupManager->get($group);
393
-				if ($groupItem instanceof \OCP\IGroup) {
394
-					$groupsList[] = $groupManager->get($group);
395
-				}
396
-			}
397
-			$appManager->enableAppForGroups($appId, $groupsList);
398
-		} else {
399
-			$appManager->enableApp($appId);
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @param string $app
405
-	 * @return bool
406
-	 */
407
-	public static function removeApp($app) {
408
-		if (\OC::$server->getAppManager()->isShipped($app)) {
409
-			return false;
410
-		}
411
-
412
-		$installer = \OC::$server->query(Installer::class);
413
-		return $installer->removeApp($app);
414
-	}
415
-
416
-	/**
417
-	 * This function set an app as disabled in appconfig.
418
-	 *
419
-	 * @param string $app app
420
-	 * @throws Exception
421
-	 */
422
-	public static function disable($app) {
423
-		// flush
424
-		self::$enabledAppsCache = array();
425
-
426
-		// run uninstall steps
427
-		$appData = OC_App::getAppInfo($app);
428
-		if (!is_null($appData)) {
429
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
430
-		}
431
-
432
-		// emit disable hook - needed anymore ?
433
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
434
-
435
-		// finally disable it
436
-		$appManager = \OC::$server->getAppManager();
437
-		$appManager->disableApp($app);
438
-	}
439
-
440
-	// This is private as well. It simply works, so don't ask for more details
441
-	private static function proceedNavigation($list) {
442
-		usort($list, function($a, $b) {
443
-			if (isset($a['order']) && isset($b['order'])) {
444
-				return ($a['order'] < $b['order']) ? -1 : 1;
445
-			} else if (isset($a['order']) || isset($b['order'])) {
446
-				return isset($a['order']) ? -1 : 1;
447
-			} else {
448
-				return ($a['name'] < $b['name']) ? -1 : 1;
449
-			}
450
-		});
451
-
452
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
453
-		foreach ($list as $index => &$navEntry) {
454
-			if ($navEntry['id'] == $activeApp) {
455
-				$navEntry['active'] = true;
456
-			} else {
457
-				$navEntry['active'] = false;
458
-			}
459
-		}
460
-		unset($navEntry);
461
-
462
-		return $list;
463
-	}
464
-
465
-	/**
466
-	 * Get the path where to install apps
467
-	 *
468
-	 * @return string|false
469
-	 */
470
-	public static function getInstallPath() {
471
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
472
-			return false;
473
-		}
474
-
475
-		foreach (OC::$APPSROOTS as $dir) {
476
-			if (isset($dir['writable']) && $dir['writable'] === true) {
477
-				return $dir['path'];
478
-			}
479
-		}
480
-
481
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
482
-		return null;
483
-	}
484
-
485
-
486
-	/**
487
-	 * search for an app in all app-directories
488
-	 *
489
-	 * @param string $appId
490
-	 * @return false|string
491
-	 */
492
-	public static function findAppInDirectories($appId) {
493
-		$sanitizedAppId = self::cleanAppId($appId);
494
-		if($sanitizedAppId !== $appId) {
495
-			return false;
496
-		}
497
-		static $app_dir = array();
498
-
499
-		if (isset($app_dir[$appId])) {
500
-			return $app_dir[$appId];
501
-		}
502
-
503
-		$possibleApps = array();
504
-		foreach (OC::$APPSROOTS as $dir) {
505
-			if (file_exists($dir['path'] . '/' . $appId)) {
506
-				$possibleApps[] = $dir;
507
-			}
508
-		}
509
-
510
-		if (empty($possibleApps)) {
511
-			return false;
512
-		} elseif (count($possibleApps) === 1) {
513
-			$dir = array_shift($possibleApps);
514
-			$app_dir[$appId] = $dir;
515
-			return $dir;
516
-		} else {
517
-			$versionToLoad = array();
518
-			foreach ($possibleApps as $possibleApp) {
519
-				$version = self::getAppVersionByPath($possibleApp['path']);
520
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
521
-					$versionToLoad = array(
522
-						'dir' => $possibleApp,
523
-						'version' => $version,
524
-					);
525
-				}
526
-			}
527
-			$app_dir[$appId] = $versionToLoad['dir'];
528
-			return $versionToLoad['dir'];
529
-			//TODO - write test
530
-		}
531
-	}
532
-
533
-	/**
534
-	 * Get the directory for the given app.
535
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
536
-	 *
537
-	 * @param string $appId
538
-	 * @return string|false
539
-	 */
540
-	public static function getAppPath($appId) {
541
-		if ($appId === null || trim($appId) === '') {
542
-			return false;
543
-		}
544
-
545
-		if (($dir = self::findAppInDirectories($appId)) != false) {
546
-			return $dir['path'] . '/' . $appId;
547
-		}
548
-		return false;
549
-	}
550
-
551
-	/**
552
-	 * Get the path for the given app on the access
553
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
554
-	 *
555
-	 * @param string $appId
556
-	 * @return string|false
557
-	 */
558
-	public static function getAppWebPath($appId) {
559
-		if (($dir = self::findAppInDirectories($appId)) != false) {
560
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
561
-		}
562
-		return false;
563
-	}
564
-
565
-	/**
566
-	 * get the last version of the app from appinfo/info.xml
567
-	 *
568
-	 * @param string $appId
569
-	 * @param bool $useCache
570
-	 * @return string
571
-	 */
572
-	public static function getAppVersion($appId, $useCache = true) {
573
-		if($useCache && isset(self::$appVersion[$appId])) {
574
-			return self::$appVersion[$appId];
575
-		}
576
-
577
-		$file = self::getAppPath($appId);
578
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
579
-		return self::$appVersion[$appId];
580
-	}
581
-
582
-	/**
583
-	 * get app's version based on it's path
584
-	 *
585
-	 * @param string $path
586
-	 * @return string
587
-	 */
588
-	public static function getAppVersionByPath($path) {
589
-		$infoFile = $path . '/appinfo/info.xml';
590
-		$appData = self::getAppInfo($infoFile, true);
591
-		return isset($appData['version']) ? $appData['version'] : '';
592
-	}
593
-
594
-
595
-	/**
596
-	 * Read all app metadata from the info.xml file
597
-	 *
598
-	 * @param string $appId id of the app or the path of the info.xml file
599
-	 * @param bool $path
600
-	 * @param string $lang
601
-	 * @return array|null
602
-	 * @note all data is read from info.xml, not just pre-defined fields
603
-	 */
604
-	public static function getAppInfo($appId, $path = false, $lang = null) {
605
-		if ($path) {
606
-			$file = $appId;
607
-		} else {
608
-			if ($lang === null && isset(self::$appInfo[$appId])) {
609
-				return self::$appInfo[$appId];
610
-			}
611
-			$appPath = self::getAppPath($appId);
612
-			if($appPath === false) {
613
-				return null;
614
-			}
615
-			$file = $appPath . '/appinfo/info.xml';
616
-		}
617
-
618
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
619
-		$data = $parser->parse($file);
620
-
621
-		if (is_array($data)) {
622
-			$data = OC_App::parseAppInfo($data, $lang);
623
-		}
624
-		if(isset($data['ocsid'])) {
625
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
626
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
627
-				$data['ocsid'] = $storedId;
628
-			}
629
-		}
630
-
631
-		if ($lang === null) {
632
-			self::$appInfo[$appId] = $data;
633
-		}
634
-
635
-		return $data;
636
-	}
637
-
638
-	/**
639
-	 * Returns the navigation
640
-	 *
641
-	 * @return array
642
-	 *
643
-	 * This function returns an array containing all entries added. The
644
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
645
-	 * given for each app the following keys exist:
646
-	 *   - active: boolean, signals if the user is on this navigation entry
647
-	 */
648
-	public static function getNavigation() {
649
-		$entries = OC::$server->getNavigationManager()->getAll();
650
-		return self::proceedNavigation($entries);
651
-	}
652
-
653
-	/**
654
-	 * Returns the Settings Navigation
655
-	 *
656
-	 * @return string[]
657
-	 *
658
-	 * This function returns an array containing all settings pages added. The
659
-	 * entries are sorted by the key 'order' ascending.
660
-	 */
661
-	public static function getSettingsNavigation() {
662
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
663
-		return self::proceedNavigation($entries);
664
-	}
665
-
666
-	/**
667
-	 * get the id of loaded app
668
-	 *
669
-	 * @return string
670
-	 */
671
-	public static function getCurrentApp() {
672
-		$request = \OC::$server->getRequest();
673
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
674
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
675
-		if (empty($topFolder)) {
676
-			$path_info = $request->getPathInfo();
677
-			if ($path_info) {
678
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
679
-			}
680
-		}
681
-		if ($topFolder == 'apps') {
682
-			$length = strlen($topFolder);
683
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
684
-		} else {
685
-			return $topFolder;
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * @param string $type
691
-	 * @return array
692
-	 */
693
-	public static function getForms($type) {
694
-		$forms = array();
695
-		switch ($type) {
696
-			case 'admin':
697
-				$source = self::$adminForms;
698
-				break;
699
-			case 'personal':
700
-				$source = self::$personalForms;
701
-				break;
702
-			default:
703
-				return array();
704
-		}
705
-		foreach ($source as $form) {
706
-			$forms[] = include $form;
707
-		}
708
-		return $forms;
709
-	}
710
-
711
-	/**
712
-	 * register an admin form to be shown
713
-	 *
714
-	 * @param string $app
715
-	 * @param string $page
716
-	 */
717
-	public static function registerAdmin($app, $page) {
718
-		self::$adminForms[] = $app . '/' . $page . '.php';
719
-	}
720
-
721
-	/**
722
-	 * register a personal form to be shown
723
-	 * @param string $app
724
-	 * @param string $page
725
-	 */
726
-	public static function registerPersonal($app, $page) {
727
-		self::$personalForms[] = $app . '/' . $page . '.php';
728
-	}
729
-
730
-	/**
731
-	 * @param array $entry
732
-	 */
733
-	public static function registerLogIn(array $entry) {
734
-		self::$altLogin[] = $entry;
735
-	}
736
-
737
-	/**
738
-	 * @return array
739
-	 */
740
-	public static function getAlternativeLogIns() {
741
-		return self::$altLogin;
742
-	}
743
-
744
-	/**
745
-	 * get a list of all apps in the apps folder
746
-	 *
747
-	 * @return array an array of app names (string IDs)
748
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
749
-	 */
750
-	public static function getAllApps() {
751
-
752
-		$apps = array();
753
-
754
-		foreach (OC::$APPSROOTS as $apps_dir) {
755
-			if (!is_readable($apps_dir['path'])) {
756
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
757
-				continue;
758
-			}
759
-			$dh = opendir($apps_dir['path']);
760
-
761
-			if (is_resource($dh)) {
762
-				while (($file = readdir($dh)) !== false) {
763
-
764
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
765
-
766
-						$apps[] = $file;
767
-					}
768
-				}
769
-			}
770
-		}
771
-
772
-		$apps = array_unique($apps);
773
-
774
-		return $apps;
775
-	}
776
-
777
-	/**
778
-	 * List all apps, this is used in apps.php
779
-	 *
780
-	 * @return array
781
-	 */
782
-	public function listAllApps() {
783
-		$installedApps = OC_App::getAllApps();
784
-
785
-		$appManager = \OC::$server->getAppManager();
786
-		//we don't want to show configuration for these
787
-		$blacklist = $appManager->getAlwaysEnabledApps();
788
-		$appList = array();
789
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
790
-		$urlGenerator = \OC::$server->getURLGenerator();
791
-
792
-		foreach ($installedApps as $app) {
793
-			if (array_search($app, $blacklist) === false) {
794
-
795
-				$info = OC_App::getAppInfo($app, false, $langCode);
796
-				if (!is_array($info)) {
797
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
798
-					continue;
799
-				}
800
-
801
-				if (!isset($info['name'])) {
802
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
803
-					continue;
804
-				}
805
-
806
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
807
-				$info['groups'] = null;
808
-				if ($enabled === 'yes') {
809
-					$active = true;
810
-				} else if ($enabled === 'no') {
811
-					$active = false;
812
-				} else {
813
-					$active = true;
814
-					$info['groups'] = $enabled;
815
-				}
816
-
817
-				$info['active'] = $active;
818
-
819
-				if ($appManager->isShipped($app)) {
820
-					$info['internal'] = true;
821
-					$info['level'] = self::officialApp;
822
-					$info['removable'] = false;
823
-				} else {
824
-					$info['internal'] = false;
825
-					$info['removable'] = true;
826
-				}
827
-
828
-				$appPath = self::getAppPath($app);
829
-				if($appPath !== false) {
830
-					$appIcon = $appPath . '/img/' . $app . '.svg';
831
-					if (file_exists($appIcon)) {
832
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
833
-						$info['previewAsIcon'] = true;
834
-					} else {
835
-						$appIcon = $appPath . '/img/app.svg';
836
-						if (file_exists($appIcon)) {
837
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838
-							$info['previewAsIcon'] = true;
839
-						}
840
-					}
841
-				}
842
-				// fix documentation
843
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
844
-					foreach ($info['documentation'] as $key => $url) {
845
-						// If it is not an absolute URL we assume it is a key
846
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
847
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
848
-							$url = $urlGenerator->linkToDocs($url);
849
-						}
850
-
851
-						$info['documentation'][$key] = $url;
852
-					}
853
-				}
854
-
855
-				$info['version'] = OC_App::getAppVersion($app);
856
-				$appList[] = $info;
857
-			}
858
-		}
859
-
860
-		return $appList;
861
-	}
862
-
863
-	public static function shouldUpgrade($app) {
864
-		$versions = self::getAppVersions();
865
-		$currentVersion = OC_App::getAppVersion($app);
866
-		if ($currentVersion && isset($versions[$app])) {
867
-			$installedVersion = $versions[$app];
868
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
869
-				return true;
870
-			}
871
-		}
872
-		return false;
873
-	}
874
-
875
-	/**
876
-	 * Adjust the number of version parts of $version1 to match
877
-	 * the number of version parts of $version2.
878
-	 *
879
-	 * @param string $version1 version to adjust
880
-	 * @param string $version2 version to take the number of parts from
881
-	 * @return string shortened $version1
882
-	 */
883
-	private static function adjustVersionParts($version1, $version2) {
884
-		$version1 = explode('.', $version1);
885
-		$version2 = explode('.', $version2);
886
-		// reduce $version1 to match the number of parts in $version2
887
-		while (count($version1) > count($version2)) {
888
-			array_pop($version1);
889
-		}
890
-		// if $version1 does not have enough parts, add some
891
-		while (count($version1) < count($version2)) {
892
-			$version1[] = '0';
893
-		}
894
-		return implode('.', $version1);
895
-	}
896
-
897
-	/**
898
-	 * Check whether the current ownCloud version matches the given
899
-	 * application's version requirements.
900
-	 *
901
-	 * The comparison is made based on the number of parts that the
902
-	 * app info version has. For example for ownCloud 6.0.3 if the
903
-	 * app info version is expecting version 6.0, the comparison is
904
-	 * made on the first two parts of the ownCloud version.
905
-	 * This means that it's possible to specify "requiremin" => 6
906
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
907
-	 *
908
-	 * @param string $ocVersion ownCloud version to check against
909
-	 * @param array $appInfo app info (from xml)
910
-	 *
911
-	 * @return boolean true if compatible, otherwise false
912
-	 */
913
-	public static function isAppCompatible($ocVersion, $appInfo) {
914
-		$requireMin = '';
915
-		$requireMax = '';
916
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
917
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
918
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
919
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
920
-		} else if (isset($appInfo['requiremin'])) {
921
-			$requireMin = $appInfo['requiremin'];
922
-		} else if (isset($appInfo['require'])) {
923
-			$requireMin = $appInfo['require'];
924
-		}
925
-
926
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
927
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
928
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
929
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
930
-		} else if (isset($appInfo['requiremax'])) {
931
-			$requireMax = $appInfo['requiremax'];
932
-		}
933
-
934
-		if (is_array($ocVersion)) {
935
-			$ocVersion = implode('.', $ocVersion);
936
-		}
937
-
938
-		if (!empty($requireMin)
939
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
940
-		) {
941
-
942
-			return false;
943
-		}
944
-
945
-		if (!empty($requireMax)
946
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
947
-		) {
948
-			return false;
949
-		}
950
-
951
-		return true;
952
-	}
953
-
954
-	/**
955
-	 * get the installed version of all apps
956
-	 */
957
-	public static function getAppVersions() {
958
-		static $versions;
959
-
960
-		if(!$versions) {
961
-			$appConfig = \OC::$server->getAppConfig();
962
-			$versions = $appConfig->getValues(false, 'installed_version');
963
-		}
964
-		return $versions;
965
-	}
966
-
967
-	/**
968
-	 * @param string $app
969
-	 * @param \OCP\IConfig $config
970
-	 * @param \OCP\IL10N $l
971
-	 * @return bool
972
-	 *
973
-	 * @throws Exception if app is not compatible with this version of ownCloud
974
-	 * @throws Exception if no app-name was specified
975
-	 */
976
-	public function installApp($app,
977
-							   \OCP\IConfig $config,
978
-							   \OCP\IL10N $l) {
979
-		if ($app !== false) {
980
-			// check if the app is compatible with this version of ownCloud
981
-			$info = self::getAppInfo($app);
982
-			if(!is_array($info)) {
983
-				throw new \Exception(
984
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
985
-						[$info['name']]
986
-					)
987
-				);
988
-			}
989
-
990
-			$version = \OCP\Util::getVersion();
991
-			if (!self::isAppCompatible($version, $info)) {
992
-				throw new \Exception(
993
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
994
-						array($info['name'])
995
-					)
996
-				);
997
-			}
998
-
999
-			// check for required dependencies
1000
-			self::checkAppDependencies($config, $l, $info);
1001
-
1002
-			$config->setAppValue($app, 'enabled', 'yes');
1003
-			if (isset($appData['id'])) {
1004
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1005
-			}
1006
-
1007
-			if(isset($info['settings']) && is_array($info['settings'])) {
1008
-				$appPath = self::getAppPath($app);
1009
-				self::registerAutoloading($app, $appPath);
1010
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1011
-			}
1012
-
1013
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1014
-		} else {
1015
-			if(empty($appName) ) {
1016
-				throw new \Exception($l->t("No app name specified"));
1017
-			} else {
1018
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1019
-			}
1020
-		}
1021
-
1022
-		return $app;
1023
-	}
1024
-
1025
-	/**
1026
-	 * update the database for the app and call the update script
1027
-	 *
1028
-	 * @param string $appId
1029
-	 * @return bool
1030
-	 */
1031
-	public static function updateApp($appId) {
1032
-		$appPath = self::getAppPath($appId);
1033
-		if($appPath === false) {
1034
-			return false;
1035
-		}
1036
-		self::registerAutoloading($appId, $appPath);
1037
-
1038
-		$appData = self::getAppInfo($appId);
1039
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1040
-
1041
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1042
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1043
-		} else {
1044
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1045
-			$ms->migrate();
1046
-		}
1047
-
1048
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1049
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1050
-		unset(self::$appVersion[$appId]);
1051
-
1052
-		// run upgrade code
1053
-		if (file_exists($appPath . '/appinfo/update.php')) {
1054
-			self::loadApp($appId);
1055
-			include $appPath . '/appinfo/update.php';
1056
-		}
1057
-		self::setupBackgroundJobs($appData['background-jobs']);
1058
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1059
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1060
-		}
1061
-
1062
-		//set remote/public handlers
1063
-		if (array_key_exists('ocsid', $appData)) {
1064
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1065
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1066
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1067
-		}
1068
-		foreach ($appData['remote'] as $name => $path) {
1069
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1070
-		}
1071
-		foreach ($appData['public'] as $name => $path) {
1072
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1073
-		}
1074
-
1075
-		self::setAppTypes($appId);
1076
-
1077
-		$version = \OC_App::getAppVersion($appId);
1078
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1079
-
1080
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1081
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1082
-		));
1083
-
1084
-		return true;
1085
-	}
1086
-
1087
-	/**
1088
-	 * @param string $appId
1089
-	 * @param string[] $steps
1090
-	 * @throws \OC\NeedsUpdateException
1091
-	 */
1092
-	public static function executeRepairSteps($appId, array $steps) {
1093
-		if (empty($steps)) {
1094
-			return;
1095
-		}
1096
-		// load the app
1097
-		self::loadApp($appId);
1098
-
1099
-		$dispatcher = OC::$server->getEventDispatcher();
1100
-
1101
-		// load the steps
1102
-		$r = new Repair([], $dispatcher);
1103
-		foreach ($steps as $step) {
1104
-			try {
1105
-				$r->addStep($step);
1106
-			} catch (Exception $ex) {
1107
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1108
-				\OC::$server->getLogger()->logException($ex);
1109
-			}
1110
-		}
1111
-		// run the steps
1112
-		$r->run();
1113
-	}
1114
-
1115
-	public static function setupBackgroundJobs(array $jobs) {
1116
-		$queue = \OC::$server->getJobList();
1117
-		foreach ($jobs as $job) {
1118
-			$queue->add($job);
1119
-		}
1120
-	}
1121
-
1122
-	/**
1123
-	 * @param string $appId
1124
-	 * @param string[] $steps
1125
-	 */
1126
-	private static function setupLiveMigrations($appId, array $steps) {
1127
-		$queue = \OC::$server->getJobList();
1128
-		foreach ($steps as $step) {
1129
-			$queue->add('OC\Migration\BackgroundRepair', [
1130
-				'app' => $appId,
1131
-				'step' => $step]);
1132
-		}
1133
-	}
1134
-
1135
-	/**
1136
-	 * @param string $appId
1137
-	 * @return \OC\Files\View|false
1138
-	 */
1139
-	public static function getStorage($appId) {
1140
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1141
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1142
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1143
-				if (!$view->file_exists($appId)) {
1144
-					$view->mkdir($appId);
1145
-				}
1146
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1147
-			} else {
1148
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1149
-				return false;
1150
-			}
1151
-		} else {
1152
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1153
-			return false;
1154
-		}
1155
-	}
1156
-
1157
-	protected static function findBestL10NOption($options, $lang) {
1158
-		$fallback = $similarLangFallback = $englishFallback = false;
1159
-
1160
-		$lang = strtolower($lang);
1161
-		$similarLang = $lang;
1162
-		if (strpos($similarLang, '_')) {
1163
-			// For "de_DE" we want to find "de" and the other way around
1164
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1165
-		}
1166
-
1167
-		foreach ($options as $option) {
1168
-			if (is_array($option)) {
1169
-				if ($fallback === false) {
1170
-					$fallback = $option['@value'];
1171
-				}
1172
-
1173
-				if (!isset($option['@attributes']['lang'])) {
1174
-					continue;
1175
-				}
1176
-
1177
-				$attributeLang = strtolower($option['@attributes']['lang']);
1178
-				if ($attributeLang === $lang) {
1179
-					return $option['@value'];
1180
-				}
1181
-
1182
-				if ($attributeLang === $similarLang) {
1183
-					$similarLangFallback = $option['@value'];
1184
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1185
-					if ($similarLangFallback === false) {
1186
-						$similarLangFallback =  $option['@value'];
1187
-					}
1188
-				}
1189
-			} else {
1190
-				$englishFallback = $option;
1191
-			}
1192
-		}
1193
-
1194
-		if ($similarLangFallback !== false) {
1195
-			return $similarLangFallback;
1196
-		} else if ($englishFallback !== false) {
1197
-			return $englishFallback;
1198
-		}
1199
-		return (string) $fallback;
1200
-	}
1201
-
1202
-	/**
1203
-	 * parses the app data array and enhanced the 'description' value
1204
-	 *
1205
-	 * @param array $data the app data
1206
-	 * @param string $lang
1207
-	 * @return array improved app data
1208
-	 */
1209
-	public static function parseAppInfo(array $data, $lang = null) {
1210
-
1211
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1212
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1213
-		}
1214
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1215
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1216
-		}
1217
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1218
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1219
-		} else if (isset($data['description']) && is_string($data['description'])) {
1220
-			$data['description'] = trim($data['description']);
1221
-		} else  {
1222
-			$data['description'] = '';
1223
-		}
1224
-
1225
-		return $data;
1226
-	}
1227
-
1228
-	/**
1229
-	 * @param \OCP\IConfig $config
1230
-	 * @param \OCP\IL10N $l
1231
-	 * @param array $info
1232
-	 * @throws \Exception
1233
-	 */
1234
-	public static function checkAppDependencies($config, $l, $info) {
1235
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1236
-		$missing = $dependencyAnalyzer->analyze($info);
1237
-		if (!empty($missing)) {
1238
-			$missingMsg = implode(PHP_EOL, $missing);
1239
-			throw new \Exception(
1240
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1241
-					[$info['name'], $missingMsg]
1242
-				)
1243
-			);
1244
-		}
1245
-	}
66
+    static private $appVersion = [];
67
+    static private $adminForms = array();
68
+    static private $personalForms = array();
69
+    static private $appInfo = array();
70
+    static private $appTypes = array();
71
+    static private $loadedApps = array();
72
+    static private $altLogin = array();
73
+    static private $alreadyRegistered = [];
74
+    const officialApp = 200;
75
+
76
+    /**
77
+     * clean the appId
78
+     *
79
+     * @param string|boolean $app AppId that needs to be cleaned
80
+     * @return string
81
+     */
82
+    public static function cleanAppId($app) {
83
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
84
+    }
85
+
86
+    /**
87
+     * Check if an app is loaded
88
+     *
89
+     * @param string $app
90
+     * @return bool
91
+     */
92
+    public static function isAppLoaded($app) {
93
+        return in_array($app, self::$loadedApps, true);
94
+    }
95
+
96
+    /**
97
+     * loads all apps
98
+     *
99
+     * @param string[] | string | null $types
100
+     * @return bool
101
+     *
102
+     * This function walks through the ownCloud directory and loads all apps
103
+     * it can find. A directory contains an app if the file /appinfo/info.xml
104
+     * exists.
105
+     *
106
+     * if $types is set, only apps of those types will be loaded
107
+     */
108
+    public static function loadApps($types = null) {
109
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
110
+            return false;
111
+        }
112
+        // Load the enabled apps here
113
+        $apps = self::getEnabledApps();
114
+
115
+        // Add each apps' folder as allowed class path
116
+        foreach($apps as $app) {
117
+            $path = self::getAppPath($app);
118
+            if($path !== false) {
119
+                self::registerAutoloading($app, $path);
120
+            }
121
+        }
122
+
123
+        // prevent app.php from printing output
124
+        ob_start();
125
+        foreach ($apps as $app) {
126
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
127
+                self::loadApp($app);
128
+            }
129
+        }
130
+        ob_end_clean();
131
+
132
+        return true;
133
+    }
134
+
135
+    /**
136
+     * load a single app
137
+     *
138
+     * @param string $app
139
+     */
140
+    public static function loadApp($app) {
141
+        self::$loadedApps[] = $app;
142
+        $appPath = self::getAppPath($app);
143
+        if($appPath === false) {
144
+            return;
145
+        }
146
+
147
+        // in case someone calls loadApp() directly
148
+        self::registerAutoloading($app, $appPath);
149
+
150
+        if (is_file($appPath . '/appinfo/app.php')) {
151
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
+            self::requireAppFile($app);
153
+            if (self::isType($app, array('authentication'))) {
154
+                // since authentication apps affect the "is app enabled for group" check,
155
+                // the enabled apps cache needs to be cleared to make sure that the
156
+                // next time getEnableApps() is called it will also include apps that were
157
+                // enabled for groups
158
+                self::$enabledAppsCache = array();
159
+            }
160
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
161
+        }
162
+
163
+        $info = self::getAppInfo($app);
164
+        if (!empty($info['activity']['filters'])) {
165
+            foreach ($info['activity']['filters'] as $filter) {
166
+                \OC::$server->getActivityManager()->registerFilter($filter);
167
+            }
168
+        }
169
+        if (!empty($info['activity']['settings'])) {
170
+            foreach ($info['activity']['settings'] as $setting) {
171
+                \OC::$server->getActivityManager()->registerSetting($setting);
172
+            }
173
+        }
174
+        if (!empty($info['activity']['providers'])) {
175
+            foreach ($info['activity']['providers'] as $provider) {
176
+                \OC::$server->getActivityManager()->registerProvider($provider);
177
+            }
178
+        }
179
+        if (!empty($info['collaboration']['plugins'])) {
180
+            // deal with one or many plugin entries
181
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
182
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
183
+            foreach ($plugins as $plugin) {
184
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
185
+                    $pluginInfo = [
186
+                        'shareType' => $plugin['@attributes']['share-type'],
187
+                        'class' => $plugin['@value'],
188
+                    ];
189
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
190
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
191
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
192
+                }
193
+            }
194
+        }
195
+    }
196
+
197
+    /**
198
+     * @internal
199
+     * @param string $app
200
+     * @param string $path
201
+     */
202
+    public static function registerAutoloading($app, $path) {
203
+        $key = $app . '-' . $path;
204
+        if(isset(self::$alreadyRegistered[$key])) {
205
+            return;
206
+        }
207
+
208
+        self::$alreadyRegistered[$key] = true;
209
+
210
+        // Register on PSR-4 composer autoloader
211
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
212
+        \OC::$server->registerNamespace($app, $appNamespace);
213
+
214
+        if (file_exists($path . '/composer/autoload.php')) {
215
+            require_once $path . '/composer/autoload.php';
216
+        } else {
217
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
218
+            // Register on legacy autoloader
219
+            \OC::$loader->addValidRoot($path);
220
+        }
221
+
222
+        // Register Test namespace only when testing
223
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
224
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
225
+        }
226
+    }
227
+
228
+    /**
229
+     * Load app.php from the given app
230
+     *
231
+     * @param string $app app name
232
+     */
233
+    private static function requireAppFile($app) {
234
+        try {
235
+            // encapsulated here to avoid variable scope conflicts
236
+            require_once $app . '/appinfo/app.php';
237
+        } catch (Error $ex) {
238
+            \OC::$server->getLogger()->logException($ex);
239
+            if (!\OC::$server->getAppManager()->isShipped($app)) {
240
+                // Only disable apps which are not shipped
241
+                self::disable($app);
242
+            }
243
+        }
244
+    }
245
+
246
+    /**
247
+     * check if an app is of a specific type
248
+     *
249
+     * @param string $app
250
+     * @param string|array $types
251
+     * @return bool
252
+     */
253
+    public static function isType($app, $types) {
254
+        if (is_string($types)) {
255
+            $types = array($types);
256
+        }
257
+        $appTypes = self::getAppTypes($app);
258
+        foreach ($types as $type) {
259
+            if (array_search($type, $appTypes) !== false) {
260
+                return true;
261
+            }
262
+        }
263
+        return false;
264
+    }
265
+
266
+    /**
267
+     * get the types of an app
268
+     *
269
+     * @param string $app
270
+     * @return array
271
+     */
272
+    private static function getAppTypes($app) {
273
+        //load the cache
274
+        if (count(self::$appTypes) == 0) {
275
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
276
+        }
277
+
278
+        if (isset(self::$appTypes[$app])) {
279
+            return explode(',', self::$appTypes[$app]);
280
+        } else {
281
+            return array();
282
+        }
283
+    }
284
+
285
+    /**
286
+     * read app types from info.xml and cache them in the database
287
+     */
288
+    public static function setAppTypes($app) {
289
+        $appData = self::getAppInfo($app);
290
+        if(!is_array($appData)) {
291
+            return;
292
+        }
293
+
294
+        if (isset($appData['types'])) {
295
+            $appTypes = implode(',', $appData['types']);
296
+        } else {
297
+            $appTypes = '';
298
+            $appData['types'] = [];
299
+        }
300
+
301
+        \OC::$server->getConfig()->setAppValue($app, 'types', $appTypes);
302
+
303
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
304
+            $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes');
305
+            if ($enabled !== 'yes' && $enabled !== 'no') {
306
+                \OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes');
307
+            }
308
+        }
309
+    }
310
+
311
+    /**
312
+     * get all enabled apps
313
+     */
314
+    protected static $enabledAppsCache = array();
315
+
316
+    /**
317
+     * Returns apps enabled for the current user.
318
+     *
319
+     * @param bool $forceRefresh whether to refresh the cache
320
+     * @param bool $all whether to return apps for all users, not only the
321
+     * currently logged in one
322
+     * @return string[]
323
+     */
324
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
325
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
326
+            return array();
327
+        }
328
+        // in incognito mode or when logged out, $user will be false,
329
+        // which is also the case during an upgrade
330
+        $appManager = \OC::$server->getAppManager();
331
+        if ($all) {
332
+            $user = null;
333
+        } else {
334
+            $user = \OC::$server->getUserSession()->getUser();
335
+        }
336
+
337
+        if (is_null($user)) {
338
+            $apps = $appManager->getInstalledApps();
339
+        } else {
340
+            $apps = $appManager->getEnabledAppsForUser($user);
341
+        }
342
+        $apps = array_filter($apps, function ($app) {
343
+            return $app !== 'files';//we add this manually
344
+        });
345
+        sort($apps);
346
+        array_unshift($apps, 'files');
347
+        return $apps;
348
+    }
349
+
350
+    /**
351
+     * checks whether or not an app is enabled
352
+     *
353
+     * @param string $app app
354
+     * @return bool
355
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
356
+     *
357
+     * This function checks whether or not an app is enabled.
358
+     */
359
+    public static function isEnabled($app) {
360
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
361
+    }
362
+
363
+    /**
364
+     * enables an app
365
+     *
366
+     * @param string $appId
367
+     * @param array $groups (optional) when set, only these groups will have access to the app
368
+     * @throws \Exception
369
+     * @return void
370
+     *
371
+     * This function set an app as enabled in appconfig.
372
+     */
373
+    public function enable($appId,
374
+                            $groups = null) {
375
+        self::$enabledAppsCache = []; // flush
376
+
377
+        // Check if app is already downloaded
378
+        $installer = \OC::$server->query(Installer::class);
379
+        $isDownloaded = $installer->isDownloaded($appId);
380
+
381
+        if(!$isDownloaded) {
382
+            $installer->downloadApp($appId);
383
+        }
384
+
385
+        $installer->installApp($appId);
386
+
387
+        $appManager = \OC::$server->getAppManager();
388
+        if (!is_null($groups)) {
389
+            $groupManager = \OC::$server->getGroupManager();
390
+            $groupsList = [];
391
+            foreach ($groups as $group) {
392
+                $groupItem = $groupManager->get($group);
393
+                if ($groupItem instanceof \OCP\IGroup) {
394
+                    $groupsList[] = $groupManager->get($group);
395
+                }
396
+            }
397
+            $appManager->enableAppForGroups($appId, $groupsList);
398
+        } else {
399
+            $appManager->enableApp($appId);
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @param string $app
405
+     * @return bool
406
+     */
407
+    public static function removeApp($app) {
408
+        if (\OC::$server->getAppManager()->isShipped($app)) {
409
+            return false;
410
+        }
411
+
412
+        $installer = \OC::$server->query(Installer::class);
413
+        return $installer->removeApp($app);
414
+    }
415
+
416
+    /**
417
+     * This function set an app as disabled in appconfig.
418
+     *
419
+     * @param string $app app
420
+     * @throws Exception
421
+     */
422
+    public static function disable($app) {
423
+        // flush
424
+        self::$enabledAppsCache = array();
425
+
426
+        // run uninstall steps
427
+        $appData = OC_App::getAppInfo($app);
428
+        if (!is_null($appData)) {
429
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
430
+        }
431
+
432
+        // emit disable hook - needed anymore ?
433
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
434
+
435
+        // finally disable it
436
+        $appManager = \OC::$server->getAppManager();
437
+        $appManager->disableApp($app);
438
+    }
439
+
440
+    // This is private as well. It simply works, so don't ask for more details
441
+    private static function proceedNavigation($list) {
442
+        usort($list, function($a, $b) {
443
+            if (isset($a['order']) && isset($b['order'])) {
444
+                return ($a['order'] < $b['order']) ? -1 : 1;
445
+            } else if (isset($a['order']) || isset($b['order'])) {
446
+                return isset($a['order']) ? -1 : 1;
447
+            } else {
448
+                return ($a['name'] < $b['name']) ? -1 : 1;
449
+            }
450
+        });
451
+
452
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
453
+        foreach ($list as $index => &$navEntry) {
454
+            if ($navEntry['id'] == $activeApp) {
455
+                $navEntry['active'] = true;
456
+            } else {
457
+                $navEntry['active'] = false;
458
+            }
459
+        }
460
+        unset($navEntry);
461
+
462
+        return $list;
463
+    }
464
+
465
+    /**
466
+     * Get the path where to install apps
467
+     *
468
+     * @return string|false
469
+     */
470
+    public static function getInstallPath() {
471
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
472
+            return false;
473
+        }
474
+
475
+        foreach (OC::$APPSROOTS as $dir) {
476
+            if (isset($dir['writable']) && $dir['writable'] === true) {
477
+                return $dir['path'];
478
+            }
479
+        }
480
+
481
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
482
+        return null;
483
+    }
484
+
485
+
486
+    /**
487
+     * search for an app in all app-directories
488
+     *
489
+     * @param string $appId
490
+     * @return false|string
491
+     */
492
+    public static function findAppInDirectories($appId) {
493
+        $sanitizedAppId = self::cleanAppId($appId);
494
+        if($sanitizedAppId !== $appId) {
495
+            return false;
496
+        }
497
+        static $app_dir = array();
498
+
499
+        if (isset($app_dir[$appId])) {
500
+            return $app_dir[$appId];
501
+        }
502
+
503
+        $possibleApps = array();
504
+        foreach (OC::$APPSROOTS as $dir) {
505
+            if (file_exists($dir['path'] . '/' . $appId)) {
506
+                $possibleApps[] = $dir;
507
+            }
508
+        }
509
+
510
+        if (empty($possibleApps)) {
511
+            return false;
512
+        } elseif (count($possibleApps) === 1) {
513
+            $dir = array_shift($possibleApps);
514
+            $app_dir[$appId] = $dir;
515
+            return $dir;
516
+        } else {
517
+            $versionToLoad = array();
518
+            foreach ($possibleApps as $possibleApp) {
519
+                $version = self::getAppVersionByPath($possibleApp['path']);
520
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
521
+                    $versionToLoad = array(
522
+                        'dir' => $possibleApp,
523
+                        'version' => $version,
524
+                    );
525
+                }
526
+            }
527
+            $app_dir[$appId] = $versionToLoad['dir'];
528
+            return $versionToLoad['dir'];
529
+            //TODO - write test
530
+        }
531
+    }
532
+
533
+    /**
534
+     * Get the directory for the given app.
535
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
536
+     *
537
+     * @param string $appId
538
+     * @return string|false
539
+     */
540
+    public static function getAppPath($appId) {
541
+        if ($appId === null || trim($appId) === '') {
542
+            return false;
543
+        }
544
+
545
+        if (($dir = self::findAppInDirectories($appId)) != false) {
546
+            return $dir['path'] . '/' . $appId;
547
+        }
548
+        return false;
549
+    }
550
+
551
+    /**
552
+     * Get the path for the given app on the access
553
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
554
+     *
555
+     * @param string $appId
556
+     * @return string|false
557
+     */
558
+    public static function getAppWebPath($appId) {
559
+        if (($dir = self::findAppInDirectories($appId)) != false) {
560
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
561
+        }
562
+        return false;
563
+    }
564
+
565
+    /**
566
+     * get the last version of the app from appinfo/info.xml
567
+     *
568
+     * @param string $appId
569
+     * @param bool $useCache
570
+     * @return string
571
+     */
572
+    public static function getAppVersion($appId, $useCache = true) {
573
+        if($useCache && isset(self::$appVersion[$appId])) {
574
+            return self::$appVersion[$appId];
575
+        }
576
+
577
+        $file = self::getAppPath($appId);
578
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
579
+        return self::$appVersion[$appId];
580
+    }
581
+
582
+    /**
583
+     * get app's version based on it's path
584
+     *
585
+     * @param string $path
586
+     * @return string
587
+     */
588
+    public static function getAppVersionByPath($path) {
589
+        $infoFile = $path . '/appinfo/info.xml';
590
+        $appData = self::getAppInfo($infoFile, true);
591
+        return isset($appData['version']) ? $appData['version'] : '';
592
+    }
593
+
594
+
595
+    /**
596
+     * Read all app metadata from the info.xml file
597
+     *
598
+     * @param string $appId id of the app or the path of the info.xml file
599
+     * @param bool $path
600
+     * @param string $lang
601
+     * @return array|null
602
+     * @note all data is read from info.xml, not just pre-defined fields
603
+     */
604
+    public static function getAppInfo($appId, $path = false, $lang = null) {
605
+        if ($path) {
606
+            $file = $appId;
607
+        } else {
608
+            if ($lang === null && isset(self::$appInfo[$appId])) {
609
+                return self::$appInfo[$appId];
610
+            }
611
+            $appPath = self::getAppPath($appId);
612
+            if($appPath === false) {
613
+                return null;
614
+            }
615
+            $file = $appPath . '/appinfo/info.xml';
616
+        }
617
+
618
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
619
+        $data = $parser->parse($file);
620
+
621
+        if (is_array($data)) {
622
+            $data = OC_App::parseAppInfo($data, $lang);
623
+        }
624
+        if(isset($data['ocsid'])) {
625
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
626
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
627
+                $data['ocsid'] = $storedId;
628
+            }
629
+        }
630
+
631
+        if ($lang === null) {
632
+            self::$appInfo[$appId] = $data;
633
+        }
634
+
635
+        return $data;
636
+    }
637
+
638
+    /**
639
+     * Returns the navigation
640
+     *
641
+     * @return array
642
+     *
643
+     * This function returns an array containing all entries added. The
644
+     * entries are sorted by the key 'order' ascending. Additional to the keys
645
+     * given for each app the following keys exist:
646
+     *   - active: boolean, signals if the user is on this navigation entry
647
+     */
648
+    public static function getNavigation() {
649
+        $entries = OC::$server->getNavigationManager()->getAll();
650
+        return self::proceedNavigation($entries);
651
+    }
652
+
653
+    /**
654
+     * Returns the Settings Navigation
655
+     *
656
+     * @return string[]
657
+     *
658
+     * This function returns an array containing all settings pages added. The
659
+     * entries are sorted by the key 'order' ascending.
660
+     */
661
+    public static function getSettingsNavigation() {
662
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
663
+        return self::proceedNavigation($entries);
664
+    }
665
+
666
+    /**
667
+     * get the id of loaded app
668
+     *
669
+     * @return string
670
+     */
671
+    public static function getCurrentApp() {
672
+        $request = \OC::$server->getRequest();
673
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
674
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
675
+        if (empty($topFolder)) {
676
+            $path_info = $request->getPathInfo();
677
+            if ($path_info) {
678
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
679
+            }
680
+        }
681
+        if ($topFolder == 'apps') {
682
+            $length = strlen($topFolder);
683
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
684
+        } else {
685
+            return $topFolder;
686
+        }
687
+    }
688
+
689
+    /**
690
+     * @param string $type
691
+     * @return array
692
+     */
693
+    public static function getForms($type) {
694
+        $forms = array();
695
+        switch ($type) {
696
+            case 'admin':
697
+                $source = self::$adminForms;
698
+                break;
699
+            case 'personal':
700
+                $source = self::$personalForms;
701
+                break;
702
+            default:
703
+                return array();
704
+        }
705
+        foreach ($source as $form) {
706
+            $forms[] = include $form;
707
+        }
708
+        return $forms;
709
+    }
710
+
711
+    /**
712
+     * register an admin form to be shown
713
+     *
714
+     * @param string $app
715
+     * @param string $page
716
+     */
717
+    public static function registerAdmin($app, $page) {
718
+        self::$adminForms[] = $app . '/' . $page . '.php';
719
+    }
720
+
721
+    /**
722
+     * register a personal form to be shown
723
+     * @param string $app
724
+     * @param string $page
725
+     */
726
+    public static function registerPersonal($app, $page) {
727
+        self::$personalForms[] = $app . '/' . $page . '.php';
728
+    }
729
+
730
+    /**
731
+     * @param array $entry
732
+     */
733
+    public static function registerLogIn(array $entry) {
734
+        self::$altLogin[] = $entry;
735
+    }
736
+
737
+    /**
738
+     * @return array
739
+     */
740
+    public static function getAlternativeLogIns() {
741
+        return self::$altLogin;
742
+    }
743
+
744
+    /**
745
+     * get a list of all apps in the apps folder
746
+     *
747
+     * @return array an array of app names (string IDs)
748
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
749
+     */
750
+    public static function getAllApps() {
751
+
752
+        $apps = array();
753
+
754
+        foreach (OC::$APPSROOTS as $apps_dir) {
755
+            if (!is_readable($apps_dir['path'])) {
756
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
757
+                continue;
758
+            }
759
+            $dh = opendir($apps_dir['path']);
760
+
761
+            if (is_resource($dh)) {
762
+                while (($file = readdir($dh)) !== false) {
763
+
764
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
765
+
766
+                        $apps[] = $file;
767
+                    }
768
+                }
769
+            }
770
+        }
771
+
772
+        $apps = array_unique($apps);
773
+
774
+        return $apps;
775
+    }
776
+
777
+    /**
778
+     * List all apps, this is used in apps.php
779
+     *
780
+     * @return array
781
+     */
782
+    public function listAllApps() {
783
+        $installedApps = OC_App::getAllApps();
784
+
785
+        $appManager = \OC::$server->getAppManager();
786
+        //we don't want to show configuration for these
787
+        $blacklist = $appManager->getAlwaysEnabledApps();
788
+        $appList = array();
789
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
790
+        $urlGenerator = \OC::$server->getURLGenerator();
791
+
792
+        foreach ($installedApps as $app) {
793
+            if (array_search($app, $blacklist) === false) {
794
+
795
+                $info = OC_App::getAppInfo($app, false, $langCode);
796
+                if (!is_array($info)) {
797
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
798
+                    continue;
799
+                }
800
+
801
+                if (!isset($info['name'])) {
802
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
803
+                    continue;
804
+                }
805
+
806
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
807
+                $info['groups'] = null;
808
+                if ($enabled === 'yes') {
809
+                    $active = true;
810
+                } else if ($enabled === 'no') {
811
+                    $active = false;
812
+                } else {
813
+                    $active = true;
814
+                    $info['groups'] = $enabled;
815
+                }
816
+
817
+                $info['active'] = $active;
818
+
819
+                if ($appManager->isShipped($app)) {
820
+                    $info['internal'] = true;
821
+                    $info['level'] = self::officialApp;
822
+                    $info['removable'] = false;
823
+                } else {
824
+                    $info['internal'] = false;
825
+                    $info['removable'] = true;
826
+                }
827
+
828
+                $appPath = self::getAppPath($app);
829
+                if($appPath !== false) {
830
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
831
+                    if (file_exists($appIcon)) {
832
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
833
+                        $info['previewAsIcon'] = true;
834
+                    } else {
835
+                        $appIcon = $appPath . '/img/app.svg';
836
+                        if (file_exists($appIcon)) {
837
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838
+                            $info['previewAsIcon'] = true;
839
+                        }
840
+                    }
841
+                }
842
+                // fix documentation
843
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
844
+                    foreach ($info['documentation'] as $key => $url) {
845
+                        // If it is not an absolute URL we assume it is a key
846
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
847
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
848
+                            $url = $urlGenerator->linkToDocs($url);
849
+                        }
850
+
851
+                        $info['documentation'][$key] = $url;
852
+                    }
853
+                }
854
+
855
+                $info['version'] = OC_App::getAppVersion($app);
856
+                $appList[] = $info;
857
+            }
858
+        }
859
+
860
+        return $appList;
861
+    }
862
+
863
+    public static function shouldUpgrade($app) {
864
+        $versions = self::getAppVersions();
865
+        $currentVersion = OC_App::getAppVersion($app);
866
+        if ($currentVersion && isset($versions[$app])) {
867
+            $installedVersion = $versions[$app];
868
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
869
+                return true;
870
+            }
871
+        }
872
+        return false;
873
+    }
874
+
875
+    /**
876
+     * Adjust the number of version parts of $version1 to match
877
+     * the number of version parts of $version2.
878
+     *
879
+     * @param string $version1 version to adjust
880
+     * @param string $version2 version to take the number of parts from
881
+     * @return string shortened $version1
882
+     */
883
+    private static function adjustVersionParts($version1, $version2) {
884
+        $version1 = explode('.', $version1);
885
+        $version2 = explode('.', $version2);
886
+        // reduce $version1 to match the number of parts in $version2
887
+        while (count($version1) > count($version2)) {
888
+            array_pop($version1);
889
+        }
890
+        // if $version1 does not have enough parts, add some
891
+        while (count($version1) < count($version2)) {
892
+            $version1[] = '0';
893
+        }
894
+        return implode('.', $version1);
895
+    }
896
+
897
+    /**
898
+     * Check whether the current ownCloud version matches the given
899
+     * application's version requirements.
900
+     *
901
+     * The comparison is made based on the number of parts that the
902
+     * app info version has. For example for ownCloud 6.0.3 if the
903
+     * app info version is expecting version 6.0, the comparison is
904
+     * made on the first two parts of the ownCloud version.
905
+     * This means that it's possible to specify "requiremin" => 6
906
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
907
+     *
908
+     * @param string $ocVersion ownCloud version to check against
909
+     * @param array $appInfo app info (from xml)
910
+     *
911
+     * @return boolean true if compatible, otherwise false
912
+     */
913
+    public static function isAppCompatible($ocVersion, $appInfo) {
914
+        $requireMin = '';
915
+        $requireMax = '';
916
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
917
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
918
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
919
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
920
+        } else if (isset($appInfo['requiremin'])) {
921
+            $requireMin = $appInfo['requiremin'];
922
+        } else if (isset($appInfo['require'])) {
923
+            $requireMin = $appInfo['require'];
924
+        }
925
+
926
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
927
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
928
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
929
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
930
+        } else if (isset($appInfo['requiremax'])) {
931
+            $requireMax = $appInfo['requiremax'];
932
+        }
933
+
934
+        if (is_array($ocVersion)) {
935
+            $ocVersion = implode('.', $ocVersion);
936
+        }
937
+
938
+        if (!empty($requireMin)
939
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
940
+        ) {
941
+
942
+            return false;
943
+        }
944
+
945
+        if (!empty($requireMax)
946
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
947
+        ) {
948
+            return false;
949
+        }
950
+
951
+        return true;
952
+    }
953
+
954
+    /**
955
+     * get the installed version of all apps
956
+     */
957
+    public static function getAppVersions() {
958
+        static $versions;
959
+
960
+        if(!$versions) {
961
+            $appConfig = \OC::$server->getAppConfig();
962
+            $versions = $appConfig->getValues(false, 'installed_version');
963
+        }
964
+        return $versions;
965
+    }
966
+
967
+    /**
968
+     * @param string $app
969
+     * @param \OCP\IConfig $config
970
+     * @param \OCP\IL10N $l
971
+     * @return bool
972
+     *
973
+     * @throws Exception if app is not compatible with this version of ownCloud
974
+     * @throws Exception if no app-name was specified
975
+     */
976
+    public function installApp($app,
977
+                                \OCP\IConfig $config,
978
+                                \OCP\IL10N $l) {
979
+        if ($app !== false) {
980
+            // check if the app is compatible with this version of ownCloud
981
+            $info = self::getAppInfo($app);
982
+            if(!is_array($info)) {
983
+                throw new \Exception(
984
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
985
+                        [$info['name']]
986
+                    )
987
+                );
988
+            }
989
+
990
+            $version = \OCP\Util::getVersion();
991
+            if (!self::isAppCompatible($version, $info)) {
992
+                throw new \Exception(
993
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
994
+                        array($info['name'])
995
+                    )
996
+                );
997
+            }
998
+
999
+            // check for required dependencies
1000
+            self::checkAppDependencies($config, $l, $info);
1001
+
1002
+            $config->setAppValue($app, 'enabled', 'yes');
1003
+            if (isset($appData['id'])) {
1004
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1005
+            }
1006
+
1007
+            if(isset($info['settings']) && is_array($info['settings'])) {
1008
+                $appPath = self::getAppPath($app);
1009
+                self::registerAutoloading($app, $appPath);
1010
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1011
+            }
1012
+
1013
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1014
+        } else {
1015
+            if(empty($appName) ) {
1016
+                throw new \Exception($l->t("No app name specified"));
1017
+            } else {
1018
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1019
+            }
1020
+        }
1021
+
1022
+        return $app;
1023
+    }
1024
+
1025
+    /**
1026
+     * update the database for the app and call the update script
1027
+     *
1028
+     * @param string $appId
1029
+     * @return bool
1030
+     */
1031
+    public static function updateApp($appId) {
1032
+        $appPath = self::getAppPath($appId);
1033
+        if($appPath === false) {
1034
+            return false;
1035
+        }
1036
+        self::registerAutoloading($appId, $appPath);
1037
+
1038
+        $appData = self::getAppInfo($appId);
1039
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1040
+
1041
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1042
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1043
+        } else {
1044
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1045
+            $ms->migrate();
1046
+        }
1047
+
1048
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1049
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1050
+        unset(self::$appVersion[$appId]);
1051
+
1052
+        // run upgrade code
1053
+        if (file_exists($appPath . '/appinfo/update.php')) {
1054
+            self::loadApp($appId);
1055
+            include $appPath . '/appinfo/update.php';
1056
+        }
1057
+        self::setupBackgroundJobs($appData['background-jobs']);
1058
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1059
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1060
+        }
1061
+
1062
+        //set remote/public handlers
1063
+        if (array_key_exists('ocsid', $appData)) {
1064
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1065
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1066
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1067
+        }
1068
+        foreach ($appData['remote'] as $name => $path) {
1069
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1070
+        }
1071
+        foreach ($appData['public'] as $name => $path) {
1072
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1073
+        }
1074
+
1075
+        self::setAppTypes($appId);
1076
+
1077
+        $version = \OC_App::getAppVersion($appId);
1078
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1079
+
1080
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1081
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1082
+        ));
1083
+
1084
+        return true;
1085
+    }
1086
+
1087
+    /**
1088
+     * @param string $appId
1089
+     * @param string[] $steps
1090
+     * @throws \OC\NeedsUpdateException
1091
+     */
1092
+    public static function executeRepairSteps($appId, array $steps) {
1093
+        if (empty($steps)) {
1094
+            return;
1095
+        }
1096
+        // load the app
1097
+        self::loadApp($appId);
1098
+
1099
+        $dispatcher = OC::$server->getEventDispatcher();
1100
+
1101
+        // load the steps
1102
+        $r = new Repair([], $dispatcher);
1103
+        foreach ($steps as $step) {
1104
+            try {
1105
+                $r->addStep($step);
1106
+            } catch (Exception $ex) {
1107
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1108
+                \OC::$server->getLogger()->logException($ex);
1109
+            }
1110
+        }
1111
+        // run the steps
1112
+        $r->run();
1113
+    }
1114
+
1115
+    public static function setupBackgroundJobs(array $jobs) {
1116
+        $queue = \OC::$server->getJobList();
1117
+        foreach ($jobs as $job) {
1118
+            $queue->add($job);
1119
+        }
1120
+    }
1121
+
1122
+    /**
1123
+     * @param string $appId
1124
+     * @param string[] $steps
1125
+     */
1126
+    private static function setupLiveMigrations($appId, array $steps) {
1127
+        $queue = \OC::$server->getJobList();
1128
+        foreach ($steps as $step) {
1129
+            $queue->add('OC\Migration\BackgroundRepair', [
1130
+                'app' => $appId,
1131
+                'step' => $step]);
1132
+        }
1133
+    }
1134
+
1135
+    /**
1136
+     * @param string $appId
1137
+     * @return \OC\Files\View|false
1138
+     */
1139
+    public static function getStorage($appId) {
1140
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1141
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1142
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1143
+                if (!$view->file_exists($appId)) {
1144
+                    $view->mkdir($appId);
1145
+                }
1146
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1147
+            } else {
1148
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1149
+                return false;
1150
+            }
1151
+        } else {
1152
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1153
+            return false;
1154
+        }
1155
+    }
1156
+
1157
+    protected static function findBestL10NOption($options, $lang) {
1158
+        $fallback = $similarLangFallback = $englishFallback = false;
1159
+
1160
+        $lang = strtolower($lang);
1161
+        $similarLang = $lang;
1162
+        if (strpos($similarLang, '_')) {
1163
+            // For "de_DE" we want to find "de" and the other way around
1164
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1165
+        }
1166
+
1167
+        foreach ($options as $option) {
1168
+            if (is_array($option)) {
1169
+                if ($fallback === false) {
1170
+                    $fallback = $option['@value'];
1171
+                }
1172
+
1173
+                if (!isset($option['@attributes']['lang'])) {
1174
+                    continue;
1175
+                }
1176
+
1177
+                $attributeLang = strtolower($option['@attributes']['lang']);
1178
+                if ($attributeLang === $lang) {
1179
+                    return $option['@value'];
1180
+                }
1181
+
1182
+                if ($attributeLang === $similarLang) {
1183
+                    $similarLangFallback = $option['@value'];
1184
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1185
+                    if ($similarLangFallback === false) {
1186
+                        $similarLangFallback =  $option['@value'];
1187
+                    }
1188
+                }
1189
+            } else {
1190
+                $englishFallback = $option;
1191
+            }
1192
+        }
1193
+
1194
+        if ($similarLangFallback !== false) {
1195
+            return $similarLangFallback;
1196
+        } else if ($englishFallback !== false) {
1197
+            return $englishFallback;
1198
+        }
1199
+        return (string) $fallback;
1200
+    }
1201
+
1202
+    /**
1203
+     * parses the app data array and enhanced the 'description' value
1204
+     *
1205
+     * @param array $data the app data
1206
+     * @param string $lang
1207
+     * @return array improved app data
1208
+     */
1209
+    public static function parseAppInfo(array $data, $lang = null) {
1210
+
1211
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1212
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1213
+        }
1214
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1215
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1216
+        }
1217
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1218
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1219
+        } else if (isset($data['description']) && is_string($data['description'])) {
1220
+            $data['description'] = trim($data['description']);
1221
+        } else  {
1222
+            $data['description'] = '';
1223
+        }
1224
+
1225
+        return $data;
1226
+    }
1227
+
1228
+    /**
1229
+     * @param \OCP\IConfig $config
1230
+     * @param \OCP\IL10N $l
1231
+     * @param array $info
1232
+     * @throws \Exception
1233
+     */
1234
+    public static function checkAppDependencies($config, $l, $info) {
1235
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1236
+        $missing = $dependencyAnalyzer->analyze($info);
1237
+        if (!empty($missing)) {
1238
+            $missingMsg = implode(PHP_EOL, $missing);
1239
+            throw new \Exception(
1240
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1241
+                    [$info['name'], $missingMsg]
1242
+                )
1243
+            );
1244
+        }
1245
+    }
1246 1246
 }
Please login to merge, or discard this patch.
lib/private/App/AppManager.php 1 patch
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -44,367 +44,367 @@
 block discarded – undo
44 44
 
45 45
 class AppManager implements IAppManager {
46 46
 
47
-	/**
48
-	 * Apps with these types can not be enabled for certain groups only
49
-	 * @var string[]
50
-	 */
51
-	protected $protectedAppTypes = [
52
-		'filesystem',
53
-		'prelogin',
54
-		'authentication',
55
-		'logging',
56
-		'prevent_group_restriction',
57
-	];
58
-
59
-	/** @var IUserSession */
60
-	private $userSession;
61
-
62
-	/** @var AppConfig */
63
-	private $appConfig;
64
-
65
-	/** @var IGroupManager */
66
-	private $groupManager;
67
-
68
-	/** @var ICacheFactory */
69
-	private $memCacheFactory;
70
-
71
-	/** @var EventDispatcherInterface */
72
-	private $dispatcher;
73
-
74
-	/** @var string[] $appId => $enabled */
75
-	private $installedAppsCache;
76
-
77
-	/** @var string[] */
78
-	private $shippedApps;
79
-
80
-	/** @var string[] */
81
-	private $alwaysEnabled;
82
-
83
-	/**
84
-	 * @param IUserSession $userSession
85
-	 * @param AppConfig $appConfig
86
-	 * @param IGroupManager $groupManager
87
-	 * @param ICacheFactory $memCacheFactory
88
-	 * @param EventDispatcherInterface $dispatcher
89
-	 */
90
-	public function __construct(IUserSession $userSession,
91
-								AppConfig $appConfig,
92
-								IGroupManager $groupManager,
93
-								ICacheFactory $memCacheFactory,
94
-								EventDispatcherInterface $dispatcher) {
95
-		$this->userSession = $userSession;
96
-		$this->appConfig = $appConfig;
97
-		$this->groupManager = $groupManager;
98
-		$this->memCacheFactory = $memCacheFactory;
99
-		$this->dispatcher = $dispatcher;
100
-	}
101
-
102
-	/**
103
-	 * @return string[] $appId => $enabled
104
-	 */
105
-	private function getInstalledAppsValues() {
106
-		if (!$this->installedAppsCache) {
107
-			$values = $this->appConfig->getValues(false, 'enabled');
108
-
109
-			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
110
-			foreach($alwaysEnabledApps as $appId) {
111
-				$values[$appId] = 'yes';
112
-			}
113
-
114
-			$this->installedAppsCache = array_filter($values, function ($value) {
115
-				return $value !== 'no';
116
-			});
117
-			ksort($this->installedAppsCache);
118
-		}
119
-		return $this->installedAppsCache;
120
-	}
121
-
122
-	/**
123
-	 * List all installed apps
124
-	 *
125
-	 * @return string[]
126
-	 */
127
-	public function getInstalledApps() {
128
-		return array_keys($this->getInstalledAppsValues());
129
-	}
130
-
131
-	/**
132
-	 * List all apps enabled for a user
133
-	 *
134
-	 * @param \OCP\IUser $user
135
-	 * @return string[]
136
-	 */
137
-	public function getEnabledAppsForUser(IUser $user) {
138
-		$apps = $this->getInstalledAppsValues();
139
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
140
-			return $this->checkAppForUser($enabled, $user);
141
-		});
142
-		return array_keys($appsForUser);
143
-	}
144
-
145
-	/**
146
-	 * Check if an app is enabled for user
147
-	 *
148
-	 * @param string $appId
149
-	 * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
150
-	 * @return bool
151
-	 */
152
-	public function isEnabledForUser($appId, $user = null) {
153
-		if ($this->isAlwaysEnabled($appId)) {
154
-			return true;
155
-		}
156
-		if ($user === null) {
157
-			$user = $this->userSession->getUser();
158
-		}
159
-		$installedApps = $this->getInstalledAppsValues();
160
-		if (isset($installedApps[$appId])) {
161
-			return $this->checkAppForUser($installedApps[$appId], $user);
162
-		} else {
163
-			return false;
164
-		}
165
-	}
166
-
167
-	/**
168
-	 * @param string $enabled
169
-	 * @param IUser $user
170
-	 * @return bool
171
-	 */
172
-	private function checkAppForUser($enabled, $user) {
173
-		if ($enabled === 'yes') {
174
-			return true;
175
-		} elseif ($user === null) {
176
-			return false;
177
-		} else {
178
-			if(empty($enabled)){
179
-				return false;
180
-			}
181
-
182
-			$groupIds = json_decode($enabled);
183
-
184
-			if (!is_array($groupIds)) {
185
-				$jsonError = json_last_error();
186
-				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
187
-				return false;
188
-			}
189
-
190
-			$userGroups = $this->groupManager->getUserGroupIds($user);
191
-			foreach ($userGroups as $groupId) {
192
-				if (in_array($groupId, $groupIds, true)) {
193
-					return true;
194
-				}
195
-			}
196
-			return false;
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * Check if an app is installed in the instance
202
-	 *
203
-	 * @param string $appId
204
-	 * @return bool
205
-	 */
206
-	public function isInstalled($appId) {
207
-		$installedApps = $this->getInstalledAppsValues();
208
-		return isset($installedApps[$appId]);
209
-	}
210
-
211
-	/**
212
-	 * Enable an app for every user
213
-	 *
214
-	 * @param string $appId
215
-	 * @throws AppPathNotFoundException
216
-	 */
217
-	public function enableApp($appId) {
218
-		// Check if app exists
219
-		$this->getAppPath($appId);
220
-
221
-		$this->installedAppsCache[$appId] = 'yes';
222
-		$this->appConfig->setValue($appId, 'enabled', 'yes');
223
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
224
-			ManagerEvent::EVENT_APP_ENABLE, $appId
225
-		));
226
-		$this->clearAppsCache();
227
-	}
228
-
229
-	/**
230
-	 * Whether a list of types contains a protected app type
231
-	 *
232
-	 * @param string[] $types
233
-	 * @return bool
234
-	 */
235
-	public function hasProtectedAppType($types) {
236
-		if (empty($types)) {
237
-			return false;
238
-		}
239
-
240
-		$protectedTypes = array_intersect($this->protectedAppTypes, $types);
241
-		return !empty($protectedTypes);
242
-	}
243
-
244
-	/**
245
-	 * Enable an app only for specific groups
246
-	 *
247
-	 * @param string $appId
248
-	 * @param \OCP\IGroup[] $groups
249
-	 * @throws \Exception if app can't be enabled for groups
250
-	 */
251
-	public function enableAppForGroups($appId, $groups) {
252
-		$info = $this->getAppInfo($appId);
253
-		if (!empty($info['types'])) {
254
-			$protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
255
-			if (!empty($protectedTypes)) {
256
-				throw new \Exception("$appId can't be enabled for groups.");
257
-			}
258
-		}
259
-
260
-		$groupIds = array_map(function ($group) {
261
-			/** @var \OCP\IGroup $group */
262
-			return $group->getGID();
263
-		}, $groups);
264
-		$this->installedAppsCache[$appId] = json_encode($groupIds);
265
-		$this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
266
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
267
-			ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
268
-		));
269
-		$this->clearAppsCache();
270
-	}
271
-
272
-	/**
273
-	 * Disable an app for every user
274
-	 *
275
-	 * @param string $appId
276
-	 * @throws \Exception if app can't be disabled
277
-	 */
278
-	public function disableApp($appId) {
279
-		if ($this->isAlwaysEnabled($appId)) {
280
-			throw new \Exception("$appId can't be disabled.");
281
-		}
282
-		unset($this->installedAppsCache[$appId]);
283
-		$this->appConfig->setValue($appId, 'enabled', 'no');
284
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
285
-			ManagerEvent::EVENT_APP_DISABLE, $appId
286
-		));
287
-		$this->clearAppsCache();
288
-	}
289
-
290
-	/**
291
-	 * Get the directory for the given app.
292
-	 *
293
-	 * @param string $appId
294
-	 * @return string
295
-	 * @throws AppPathNotFoundException if app folder can't be found
296
-	 */
297
-	public function getAppPath($appId) {
298
-		$appPath = \OC_App::getAppPath($appId);
299
-		if($appPath === false) {
300
-			throw new AppPathNotFoundException('Could not find path for ' . $appId);
301
-		}
302
-		return $appPath;
303
-	}
304
-
305
-	/**
306
-	 * Clear the cached list of apps when enabling/disabling an app
307
-	 */
308
-	public function clearAppsCache() {
309
-		$settingsMemCache = $this->memCacheFactory->createDistributed('settings');
310
-		$settingsMemCache->clear('listApps');
311
-	}
312
-
313
-	/**
314
-	 * Returns a list of apps that need upgrade
315
-	 *
316
-	 * @param string $version Nextcloud version as array of version components
317
-	 * @return array list of app info from apps that need an upgrade
318
-	 *
319
-	 * @internal
320
-	 */
321
-	public function getAppsNeedingUpgrade($version) {
322
-		$appsToUpgrade = [];
323
-		$apps = $this->getInstalledApps();
324
-		foreach ($apps as $appId) {
325
-			$appInfo = $this->getAppInfo($appId);
326
-			$appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
327
-			if ($appDbVersion
328
-				&& isset($appInfo['version'])
329
-				&& version_compare($appInfo['version'], $appDbVersion, '>')
330
-				&& \OC_App::isAppCompatible($version, $appInfo)
331
-			) {
332
-				$appsToUpgrade[] = $appInfo;
333
-			}
334
-		}
335
-
336
-		return $appsToUpgrade;
337
-	}
338
-
339
-	/**
340
-	 * Returns the app information from "appinfo/info.xml".
341
-	 *
342
-	 * @param string $appId app id
343
-	 *
344
-	 * @return array app info
345
-	 *
346
-	 * @internal
347
-	 */
348
-	public function getAppInfo($appId) {
349
-		$appInfo = \OC_App::getAppInfo($appId);
350
-		if (!isset($appInfo['version'])) {
351
-			// read version from separate file
352
-			$appInfo['version'] = \OC_App::getAppVersion($appId);
353
-		}
354
-		return $appInfo;
355
-	}
356
-
357
-	/**
358
-	 * Returns a list of apps incompatible with the given version
359
-	 *
360
-	 * @param string $version Nextcloud version as array of version components
361
-	 *
362
-	 * @return array list of app info from incompatible apps
363
-	 *
364
-	 * @internal
365
-	 */
366
-	public function getIncompatibleApps($version) {
367
-		$apps = $this->getInstalledApps();
368
-		$incompatibleApps = array();
369
-		foreach ($apps as $appId) {
370
-			$info = $this->getAppInfo($appId);
371
-			if (!\OC_App::isAppCompatible($version, $info)) {
372
-				$incompatibleApps[] = $info;
373
-			}
374
-		}
375
-		return $incompatibleApps;
376
-	}
377
-
378
-	/**
379
-	 * @inheritdoc
380
-	 */
381
-	public function isShipped($appId) {
382
-		$this->loadShippedJson();
383
-		return in_array($appId, $this->shippedApps, true);
384
-	}
385
-
386
-	private function isAlwaysEnabled($appId) {
387
-		$alwaysEnabled = $this->getAlwaysEnabledApps();
388
-		return in_array($appId, $alwaysEnabled, true);
389
-	}
390
-
391
-	private function loadShippedJson() {
392
-		if ($this->shippedApps === null) {
393
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
394
-			if (!file_exists($shippedJson)) {
395
-				throw new \Exception("File not found: $shippedJson");
396
-			}
397
-			$content = json_decode(file_get_contents($shippedJson), true);
398
-			$this->shippedApps = $content['shippedApps'];
399
-			$this->alwaysEnabled = $content['alwaysEnabled'];
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @inheritdoc
405
-	 */
406
-	public function getAlwaysEnabledApps() {
407
-		$this->loadShippedJson();
408
-		return $this->alwaysEnabled;
409
-	}
47
+    /**
48
+     * Apps with these types can not be enabled for certain groups only
49
+     * @var string[]
50
+     */
51
+    protected $protectedAppTypes = [
52
+        'filesystem',
53
+        'prelogin',
54
+        'authentication',
55
+        'logging',
56
+        'prevent_group_restriction',
57
+    ];
58
+
59
+    /** @var IUserSession */
60
+    private $userSession;
61
+
62
+    /** @var AppConfig */
63
+    private $appConfig;
64
+
65
+    /** @var IGroupManager */
66
+    private $groupManager;
67
+
68
+    /** @var ICacheFactory */
69
+    private $memCacheFactory;
70
+
71
+    /** @var EventDispatcherInterface */
72
+    private $dispatcher;
73
+
74
+    /** @var string[] $appId => $enabled */
75
+    private $installedAppsCache;
76
+
77
+    /** @var string[] */
78
+    private $shippedApps;
79
+
80
+    /** @var string[] */
81
+    private $alwaysEnabled;
82
+
83
+    /**
84
+     * @param IUserSession $userSession
85
+     * @param AppConfig $appConfig
86
+     * @param IGroupManager $groupManager
87
+     * @param ICacheFactory $memCacheFactory
88
+     * @param EventDispatcherInterface $dispatcher
89
+     */
90
+    public function __construct(IUserSession $userSession,
91
+                                AppConfig $appConfig,
92
+                                IGroupManager $groupManager,
93
+                                ICacheFactory $memCacheFactory,
94
+                                EventDispatcherInterface $dispatcher) {
95
+        $this->userSession = $userSession;
96
+        $this->appConfig = $appConfig;
97
+        $this->groupManager = $groupManager;
98
+        $this->memCacheFactory = $memCacheFactory;
99
+        $this->dispatcher = $dispatcher;
100
+    }
101
+
102
+    /**
103
+     * @return string[] $appId => $enabled
104
+     */
105
+    private function getInstalledAppsValues() {
106
+        if (!$this->installedAppsCache) {
107
+            $values = $this->appConfig->getValues(false, 'enabled');
108
+
109
+            $alwaysEnabledApps = $this->getAlwaysEnabledApps();
110
+            foreach($alwaysEnabledApps as $appId) {
111
+                $values[$appId] = 'yes';
112
+            }
113
+
114
+            $this->installedAppsCache = array_filter($values, function ($value) {
115
+                return $value !== 'no';
116
+            });
117
+            ksort($this->installedAppsCache);
118
+        }
119
+        return $this->installedAppsCache;
120
+    }
121
+
122
+    /**
123
+     * List all installed apps
124
+     *
125
+     * @return string[]
126
+     */
127
+    public function getInstalledApps() {
128
+        return array_keys($this->getInstalledAppsValues());
129
+    }
130
+
131
+    /**
132
+     * List all apps enabled for a user
133
+     *
134
+     * @param \OCP\IUser $user
135
+     * @return string[]
136
+     */
137
+    public function getEnabledAppsForUser(IUser $user) {
138
+        $apps = $this->getInstalledAppsValues();
139
+        $appsForUser = array_filter($apps, function ($enabled) use ($user) {
140
+            return $this->checkAppForUser($enabled, $user);
141
+        });
142
+        return array_keys($appsForUser);
143
+    }
144
+
145
+    /**
146
+     * Check if an app is enabled for user
147
+     *
148
+     * @param string $appId
149
+     * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
150
+     * @return bool
151
+     */
152
+    public function isEnabledForUser($appId, $user = null) {
153
+        if ($this->isAlwaysEnabled($appId)) {
154
+            return true;
155
+        }
156
+        if ($user === null) {
157
+            $user = $this->userSession->getUser();
158
+        }
159
+        $installedApps = $this->getInstalledAppsValues();
160
+        if (isset($installedApps[$appId])) {
161
+            return $this->checkAppForUser($installedApps[$appId], $user);
162
+        } else {
163
+            return false;
164
+        }
165
+    }
166
+
167
+    /**
168
+     * @param string $enabled
169
+     * @param IUser $user
170
+     * @return bool
171
+     */
172
+    private function checkAppForUser($enabled, $user) {
173
+        if ($enabled === 'yes') {
174
+            return true;
175
+        } elseif ($user === null) {
176
+            return false;
177
+        } else {
178
+            if(empty($enabled)){
179
+                return false;
180
+            }
181
+
182
+            $groupIds = json_decode($enabled);
183
+
184
+            if (!is_array($groupIds)) {
185
+                $jsonError = json_last_error();
186
+                \OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
187
+                return false;
188
+            }
189
+
190
+            $userGroups = $this->groupManager->getUserGroupIds($user);
191
+            foreach ($userGroups as $groupId) {
192
+                if (in_array($groupId, $groupIds, true)) {
193
+                    return true;
194
+                }
195
+            }
196
+            return false;
197
+        }
198
+    }
199
+
200
+    /**
201
+     * Check if an app is installed in the instance
202
+     *
203
+     * @param string $appId
204
+     * @return bool
205
+     */
206
+    public function isInstalled($appId) {
207
+        $installedApps = $this->getInstalledAppsValues();
208
+        return isset($installedApps[$appId]);
209
+    }
210
+
211
+    /**
212
+     * Enable an app for every user
213
+     *
214
+     * @param string $appId
215
+     * @throws AppPathNotFoundException
216
+     */
217
+    public function enableApp($appId) {
218
+        // Check if app exists
219
+        $this->getAppPath($appId);
220
+
221
+        $this->installedAppsCache[$appId] = 'yes';
222
+        $this->appConfig->setValue($appId, 'enabled', 'yes');
223
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
224
+            ManagerEvent::EVENT_APP_ENABLE, $appId
225
+        ));
226
+        $this->clearAppsCache();
227
+    }
228
+
229
+    /**
230
+     * Whether a list of types contains a protected app type
231
+     *
232
+     * @param string[] $types
233
+     * @return bool
234
+     */
235
+    public function hasProtectedAppType($types) {
236
+        if (empty($types)) {
237
+            return false;
238
+        }
239
+
240
+        $protectedTypes = array_intersect($this->protectedAppTypes, $types);
241
+        return !empty($protectedTypes);
242
+    }
243
+
244
+    /**
245
+     * Enable an app only for specific groups
246
+     *
247
+     * @param string $appId
248
+     * @param \OCP\IGroup[] $groups
249
+     * @throws \Exception if app can't be enabled for groups
250
+     */
251
+    public function enableAppForGroups($appId, $groups) {
252
+        $info = $this->getAppInfo($appId);
253
+        if (!empty($info['types'])) {
254
+            $protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
255
+            if (!empty($protectedTypes)) {
256
+                throw new \Exception("$appId can't be enabled for groups.");
257
+            }
258
+        }
259
+
260
+        $groupIds = array_map(function ($group) {
261
+            /** @var \OCP\IGroup $group */
262
+            return $group->getGID();
263
+        }, $groups);
264
+        $this->installedAppsCache[$appId] = json_encode($groupIds);
265
+        $this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
266
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
267
+            ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
268
+        ));
269
+        $this->clearAppsCache();
270
+    }
271
+
272
+    /**
273
+     * Disable an app for every user
274
+     *
275
+     * @param string $appId
276
+     * @throws \Exception if app can't be disabled
277
+     */
278
+    public function disableApp($appId) {
279
+        if ($this->isAlwaysEnabled($appId)) {
280
+            throw new \Exception("$appId can't be disabled.");
281
+        }
282
+        unset($this->installedAppsCache[$appId]);
283
+        $this->appConfig->setValue($appId, 'enabled', 'no');
284
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
285
+            ManagerEvent::EVENT_APP_DISABLE, $appId
286
+        ));
287
+        $this->clearAppsCache();
288
+    }
289
+
290
+    /**
291
+     * Get the directory for the given app.
292
+     *
293
+     * @param string $appId
294
+     * @return string
295
+     * @throws AppPathNotFoundException if app folder can't be found
296
+     */
297
+    public function getAppPath($appId) {
298
+        $appPath = \OC_App::getAppPath($appId);
299
+        if($appPath === false) {
300
+            throw new AppPathNotFoundException('Could not find path for ' . $appId);
301
+        }
302
+        return $appPath;
303
+    }
304
+
305
+    /**
306
+     * Clear the cached list of apps when enabling/disabling an app
307
+     */
308
+    public function clearAppsCache() {
309
+        $settingsMemCache = $this->memCacheFactory->createDistributed('settings');
310
+        $settingsMemCache->clear('listApps');
311
+    }
312
+
313
+    /**
314
+     * Returns a list of apps that need upgrade
315
+     *
316
+     * @param string $version Nextcloud version as array of version components
317
+     * @return array list of app info from apps that need an upgrade
318
+     *
319
+     * @internal
320
+     */
321
+    public function getAppsNeedingUpgrade($version) {
322
+        $appsToUpgrade = [];
323
+        $apps = $this->getInstalledApps();
324
+        foreach ($apps as $appId) {
325
+            $appInfo = $this->getAppInfo($appId);
326
+            $appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
327
+            if ($appDbVersion
328
+                && isset($appInfo['version'])
329
+                && version_compare($appInfo['version'], $appDbVersion, '>')
330
+                && \OC_App::isAppCompatible($version, $appInfo)
331
+            ) {
332
+                $appsToUpgrade[] = $appInfo;
333
+            }
334
+        }
335
+
336
+        return $appsToUpgrade;
337
+    }
338
+
339
+    /**
340
+     * Returns the app information from "appinfo/info.xml".
341
+     *
342
+     * @param string $appId app id
343
+     *
344
+     * @return array app info
345
+     *
346
+     * @internal
347
+     */
348
+    public function getAppInfo($appId) {
349
+        $appInfo = \OC_App::getAppInfo($appId);
350
+        if (!isset($appInfo['version'])) {
351
+            // read version from separate file
352
+            $appInfo['version'] = \OC_App::getAppVersion($appId);
353
+        }
354
+        return $appInfo;
355
+    }
356
+
357
+    /**
358
+     * Returns a list of apps incompatible with the given version
359
+     *
360
+     * @param string $version Nextcloud version as array of version components
361
+     *
362
+     * @return array list of app info from incompatible apps
363
+     *
364
+     * @internal
365
+     */
366
+    public function getIncompatibleApps($version) {
367
+        $apps = $this->getInstalledApps();
368
+        $incompatibleApps = array();
369
+        foreach ($apps as $appId) {
370
+            $info = $this->getAppInfo($appId);
371
+            if (!\OC_App::isAppCompatible($version, $info)) {
372
+                $incompatibleApps[] = $info;
373
+            }
374
+        }
375
+        return $incompatibleApps;
376
+    }
377
+
378
+    /**
379
+     * @inheritdoc
380
+     */
381
+    public function isShipped($appId) {
382
+        $this->loadShippedJson();
383
+        return in_array($appId, $this->shippedApps, true);
384
+    }
385
+
386
+    private function isAlwaysEnabled($appId) {
387
+        $alwaysEnabled = $this->getAlwaysEnabledApps();
388
+        return in_array($appId, $alwaysEnabled, true);
389
+    }
390
+
391
+    private function loadShippedJson() {
392
+        if ($this->shippedApps === null) {
393
+            $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
394
+            if (!file_exists($shippedJson)) {
395
+                throw new \Exception("File not found: $shippedJson");
396
+            }
397
+            $content = json_decode(file_get_contents($shippedJson), true);
398
+            $this->shippedApps = $content['shippedApps'];
399
+            $this->alwaysEnabled = $content['alwaysEnabled'];
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @inheritdoc
405
+     */
406
+    public function getAlwaysEnabledApps() {
407
+        $this->loadShippedJson();
408
+        return $this->alwaysEnabled;
409
+    }
410 410
 }
Please login to merge, or discard this patch.