Completed
Pull Request — master (#9293)
by Blizzz
18:49
created
lib/private/legacy/user.php 1 patch
Indentation   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -60,350 +60,350 @@
 block discarded – undo
60 60
  */
61 61
 class OC_User {
62 62
 
63
-	private static $_usedBackends = array();
64
-
65
-	private static $_setupedBackends = array();
66
-
67
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
68
-	private static $incognitoMode = false;
69
-
70
-	/**
71
-	 * Adds the backend to the list of used backends
72
-	 *
73
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
74
-	 * @return bool
75
-	 *
76
-	 * Set the User Authentication Module
77
-	 * @suppress PhanDeprecatedFunction
78
-	 */
79
-	public static function useBackend($backend = 'database') {
80
-		if ($backend instanceof \OCP\UserInterface) {
81
-			self::$_usedBackends[get_class($backend)] = $backend;
82
-			\OC::$server->getUserManager()->registerBackend($backend);
83
-		} else {
84
-			// You'll never know what happens
85
-			if (null === $backend OR !is_string($backend)) {
86
-				$backend = 'database';
87
-			}
88
-
89
-			// Load backend
90
-			switch ($backend) {
91
-				case 'database':
92
-				case 'mysql':
93
-				case 'sqlite':
94
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
95
-					self::$_usedBackends[$backend] = new \OC\User\Database();
96
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97
-					break;
98
-				case 'dummy':
99
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
100
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101
-					break;
102
-				default:
103
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
-					$className = 'OC_USER_' . strtoupper($backend);
105
-					self::$_usedBackends[$backend] = new $className();
106
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107
-					break;
108
-			}
109
-		}
110
-		return true;
111
-	}
112
-
113
-	/**
114
-	 * remove all used backends
115
-	 */
116
-	public static function clearBackends() {
117
-		self::$_usedBackends = array();
118
-		\OC::$server->getUserManager()->clearBackends();
119
-	}
120
-
121
-	/**
122
-	 * setup the configured backends in config.php
123
-	 * @suppress PhanDeprecatedFunction
124
-	 */
125
-	public static function setupBackends() {
126
-		OC_App::loadApps(['prelogin']);
127
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
128
-		if (isset($backends['default']) && !$backends['default']) {
129
-			// clear default backends
130
-			self::clearBackends();
131
-		}
132
-		foreach ($backends as $i => $config) {
133
-			if (!is_array($config)) {
134
-				continue;
135
-			}
136
-			$class = $config['class'];
137
-			$arguments = $config['arguments'];
138
-			if (class_exists($class)) {
139
-				if (array_search($i, self::$_setupedBackends) === false) {
140
-					// make a reflection object
141
-					$reflectionObj = new ReflectionClass($class);
142
-
143
-					// use Reflection to create a new instance, using the $args
144
-					$backend = $reflectionObj->newInstanceArgs($arguments);
145
-					self::useBackend($backend);
146
-					self::$_setupedBackends[] = $i;
147
-				} else {
148
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
149
-				}
150
-			} else {
151
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
152
-			}
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * Try to login a user, assuming authentication
158
-	 * has already happened (e.g. via Single Sign On).
159
-	 *
160
-	 * Log in a user and regenerate a new session.
161
-	 *
162
-	 * @param \OCP\Authentication\IApacheBackend $backend
163
-	 * @return bool
164
-	 */
165
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
166
-
167
-		$uid = $backend->getCurrentUserId();
168
-		$run = true;
169
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
170
-
171
-		if ($uid) {
172
-			if (self::getUser() !== $uid) {
173
-				self::setUserId($uid);
174
-				$userSession = \OC::$server->getUserSession();
175
-				$userSession->setLoginName($uid);
176
-				$request = OC::$server->getRequest();
177
-				$userSession->createSessionToken($request, $uid, $uid);
178
-				// setup the filesystem
179
-				OC_Util::setupFS($uid);
180
-				// first call the post_login hooks, the login-process needs to be
181
-				// completed before we can safely create the users folder.
182
-				// For example encryption needs to initialize the users keys first
183
-				// before we can create the user folder with the skeleton files
184
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
185
-				//trigger creation of user home and /files folder
186
-				\OC::$server->getUserFolder($uid);
187
-			}
188
-			return true;
189
-		}
190
-		return false;
191
-	}
192
-
193
-	/**
194
-	 * Verify with Apache whether user is authenticated.
195
-	 *
196
-	 * @return boolean|null
197
-	 *          true: authenticated
198
-	 *          false: not authenticated
199
-	 *          null: not handled / no backend available
200
-	 */
201
-	public static function handleApacheAuth() {
202
-		$backend = self::findFirstActiveUsedBackend();
203
-		if ($backend) {
204
-			OC_App::loadApps();
205
-
206
-			//setup extra user backends
207
-			self::setupBackends();
208
-			\OC::$server->getUserSession()->unsetMagicInCookie();
209
-
210
-			return self::loginWithApache($backend);
211
-		}
212
-
213
-		return null;
214
-	}
215
-
216
-
217
-	/**
218
-	 * Sets user id for session and triggers emit
219
-	 *
220
-	 * @param string $uid
221
-	 */
222
-	public static function setUserId($uid) {
223
-		$userSession = \OC::$server->getUserSession();
224
-		$userManager = \OC::$server->getUserManager();
225
-		if ($user = $userManager->get($uid)) {
226
-			$userSession->setUser($user);
227
-		} else {
228
-			\OC::$server->getSession()->set('user_id', $uid);
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * Check if the user is logged in, considers also the HTTP basic credentials
234
-	 *
235
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
236
-	 * @return bool
237
-	 */
238
-	public static function isLoggedIn() {
239
-		return \OC::$server->getUserSession()->isLoggedIn();
240
-	}
241
-
242
-	/**
243
-	 * set incognito mode, e.g. if a user wants to open a public link
244
-	 *
245
-	 * @param bool $status
246
-	 */
247
-	public static function setIncognitoMode($status) {
248
-		self::$incognitoMode = $status;
249
-	}
250
-
251
-	/**
252
-	 * get incognito mode status
253
-	 *
254
-	 * @return bool
255
-	 */
256
-	public static function isIncognitoMode() {
257
-		return self::$incognitoMode;
258
-	}
259
-
260
-	/**
261
-	 * Returns the current logout URL valid for the currently logged-in user
262
-	 *
263
-	 * @param \OCP\IURLGenerator $urlGenerator
264
-	 * @return string
265
-	 */
266
-	public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
267
-		$backend = self::findFirstActiveUsedBackend();
268
-		if ($backend) {
269
-			return $backend->getLogoutUrl();
270
-		}
271
-
272
-		$logoutUrl = $urlGenerator->linkToRouteAbsolute(
273
-			'core.login.logout',
274
-			[
275
-				'requesttoken' => \OCP\Util::callRegister(),
276
-			]
277
-		);
278
-
279
-		return $logoutUrl;
280
-	}
281
-
282
-	/**
283
-	 * Check if the user is an admin user
284
-	 *
285
-	 * @param string $uid uid of the admin
286
-	 * @return bool
287
-	 */
288
-	public static function isAdminUser($uid) {
289
-		$group = \OC::$server->getGroupManager()->get('admin');
290
-		$user = \OC::$server->getUserManager()->get($uid);
291
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
292
-			return true;
293
-		}
294
-		return false;
295
-	}
296
-
297
-
298
-	/**
299
-	 * get the user id of the user currently logged in.
300
-	 *
301
-	 * @return string|bool uid or false
302
-	 */
303
-	public static function getUser() {
304
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
305
-		if (!is_null($uid) && self::$incognitoMode === false) {
306
-			return $uid;
307
-		} else {
308
-			return false;
309
-		}
310
-	}
311
-
312
-	/**
313
-	 * get the display name of the user currently logged in.
314
-	 *
315
-	 * @param string $uid
316
-	 * @return string|bool uid or false
317
-	 * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
318
-	 *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
319
-	 */
320
-	public static function getDisplayName($uid = null) {
321
-		if ($uid) {
322
-			$user = \OC::$server->getUserManager()->get($uid);
323
-			if ($user) {
324
-				return $user->getDisplayName();
325
-			} else {
326
-				return $uid;
327
-			}
328
-		} else {
329
-			$user = \OC::$server->getUserSession()->getUser();
330
-			if ($user) {
331
-				return $user->getDisplayName();
332
-			} else {
333
-				return false;
334
-			}
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * Set password
340
-	 *
341
-	 * @param string $uid The username
342
-	 * @param string $password The new password
343
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
344
-	 * @return bool
345
-	 *
346
-	 * Change the password of a user
347
-	 */
348
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
349
-		$user = \OC::$server->getUserManager()->get($uid);
350
-		if ($user) {
351
-			return $user->setPassword($password, $recoveryPassword);
352
-		} else {
353
-			return false;
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * @param string $uid The username
359
-	 * @return string
360
-	 *
361
-	 * returns the path to the users home directory
362
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
363
-	 */
364
-	public static function getHome($uid) {
365
-		$user = \OC::$server->getUserManager()->get($uid);
366
-		if ($user) {
367
-			return $user->getHome();
368
-		} else {
369
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
370
-		}
371
-	}
372
-
373
-	/**
374
-	 * Get a list of all users display name
375
-	 *
376
-	 * @param string $search
377
-	 * @param int $limit
378
-	 * @param int $offset
379
-	 * @return array associative array with all display names (value) and corresponding uids (key)
380
-	 *
381
-	 * Get a list of all display names and user ids.
382
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
383
-	 */
384
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
385
-		$displayNames = array();
386
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
387
-		foreach ($users as $user) {
388
-			$displayNames[$user->getUID()] = $user->getDisplayName();
389
-		}
390
-		return $displayNames;
391
-	}
392
-
393
-	/**
394
-	 * Returns the first active backend from self::$_usedBackends.
395
-	 *
396
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
397
-	 */
398
-	private static function findFirstActiveUsedBackend() {
399
-		foreach (self::$_usedBackends as $backend) {
400
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
401
-				if ($backend->isSessionActive()) {
402
-					return $backend;
403
-				}
404
-			}
405
-		}
406
-
407
-		return null;
408
-	}
63
+    private static $_usedBackends = array();
64
+
65
+    private static $_setupedBackends = array();
66
+
67
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
68
+    private static $incognitoMode = false;
69
+
70
+    /**
71
+     * Adds the backend to the list of used backends
72
+     *
73
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
74
+     * @return bool
75
+     *
76
+     * Set the User Authentication Module
77
+     * @suppress PhanDeprecatedFunction
78
+     */
79
+    public static function useBackend($backend = 'database') {
80
+        if ($backend instanceof \OCP\UserInterface) {
81
+            self::$_usedBackends[get_class($backend)] = $backend;
82
+            \OC::$server->getUserManager()->registerBackend($backend);
83
+        } else {
84
+            // You'll never know what happens
85
+            if (null === $backend OR !is_string($backend)) {
86
+                $backend = 'database';
87
+            }
88
+
89
+            // Load backend
90
+            switch ($backend) {
91
+                case 'database':
92
+                case 'mysql':
93
+                case 'sqlite':
94
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
95
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
96
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97
+                    break;
98
+                case 'dummy':
99
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
100
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101
+                    break;
102
+                default:
103
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
+                    $className = 'OC_USER_' . strtoupper($backend);
105
+                    self::$_usedBackends[$backend] = new $className();
106
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107
+                    break;
108
+            }
109
+        }
110
+        return true;
111
+    }
112
+
113
+    /**
114
+     * remove all used backends
115
+     */
116
+    public static function clearBackends() {
117
+        self::$_usedBackends = array();
118
+        \OC::$server->getUserManager()->clearBackends();
119
+    }
120
+
121
+    /**
122
+     * setup the configured backends in config.php
123
+     * @suppress PhanDeprecatedFunction
124
+     */
125
+    public static function setupBackends() {
126
+        OC_App::loadApps(['prelogin']);
127
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
128
+        if (isset($backends['default']) && !$backends['default']) {
129
+            // clear default backends
130
+            self::clearBackends();
131
+        }
132
+        foreach ($backends as $i => $config) {
133
+            if (!is_array($config)) {
134
+                continue;
135
+            }
136
+            $class = $config['class'];
137
+            $arguments = $config['arguments'];
138
+            if (class_exists($class)) {
139
+                if (array_search($i, self::$_setupedBackends) === false) {
140
+                    // make a reflection object
141
+                    $reflectionObj = new ReflectionClass($class);
142
+
143
+                    // use Reflection to create a new instance, using the $args
144
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
145
+                    self::useBackend($backend);
146
+                    self::$_setupedBackends[] = $i;
147
+                } else {
148
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
149
+                }
150
+            } else {
151
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
152
+            }
153
+        }
154
+    }
155
+
156
+    /**
157
+     * Try to login a user, assuming authentication
158
+     * has already happened (e.g. via Single Sign On).
159
+     *
160
+     * Log in a user and regenerate a new session.
161
+     *
162
+     * @param \OCP\Authentication\IApacheBackend $backend
163
+     * @return bool
164
+     */
165
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
166
+
167
+        $uid = $backend->getCurrentUserId();
168
+        $run = true;
169
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
170
+
171
+        if ($uid) {
172
+            if (self::getUser() !== $uid) {
173
+                self::setUserId($uid);
174
+                $userSession = \OC::$server->getUserSession();
175
+                $userSession->setLoginName($uid);
176
+                $request = OC::$server->getRequest();
177
+                $userSession->createSessionToken($request, $uid, $uid);
178
+                // setup the filesystem
179
+                OC_Util::setupFS($uid);
180
+                // first call the post_login hooks, the login-process needs to be
181
+                // completed before we can safely create the users folder.
182
+                // For example encryption needs to initialize the users keys first
183
+                // before we can create the user folder with the skeleton files
184
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
185
+                //trigger creation of user home and /files folder
186
+                \OC::$server->getUserFolder($uid);
187
+            }
188
+            return true;
189
+        }
190
+        return false;
191
+    }
192
+
193
+    /**
194
+     * Verify with Apache whether user is authenticated.
195
+     *
196
+     * @return boolean|null
197
+     *          true: authenticated
198
+     *          false: not authenticated
199
+     *          null: not handled / no backend available
200
+     */
201
+    public static function handleApacheAuth() {
202
+        $backend = self::findFirstActiveUsedBackend();
203
+        if ($backend) {
204
+            OC_App::loadApps();
205
+
206
+            //setup extra user backends
207
+            self::setupBackends();
208
+            \OC::$server->getUserSession()->unsetMagicInCookie();
209
+
210
+            return self::loginWithApache($backend);
211
+        }
212
+
213
+        return null;
214
+    }
215
+
216
+
217
+    /**
218
+     * Sets user id for session and triggers emit
219
+     *
220
+     * @param string $uid
221
+     */
222
+    public static function setUserId($uid) {
223
+        $userSession = \OC::$server->getUserSession();
224
+        $userManager = \OC::$server->getUserManager();
225
+        if ($user = $userManager->get($uid)) {
226
+            $userSession->setUser($user);
227
+        } else {
228
+            \OC::$server->getSession()->set('user_id', $uid);
229
+        }
230
+    }
231
+
232
+    /**
233
+     * Check if the user is logged in, considers also the HTTP basic credentials
234
+     *
235
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
236
+     * @return bool
237
+     */
238
+    public static function isLoggedIn() {
239
+        return \OC::$server->getUserSession()->isLoggedIn();
240
+    }
241
+
242
+    /**
243
+     * set incognito mode, e.g. if a user wants to open a public link
244
+     *
245
+     * @param bool $status
246
+     */
247
+    public static function setIncognitoMode($status) {
248
+        self::$incognitoMode = $status;
249
+    }
250
+
251
+    /**
252
+     * get incognito mode status
253
+     *
254
+     * @return bool
255
+     */
256
+    public static function isIncognitoMode() {
257
+        return self::$incognitoMode;
258
+    }
259
+
260
+    /**
261
+     * Returns the current logout URL valid for the currently logged-in user
262
+     *
263
+     * @param \OCP\IURLGenerator $urlGenerator
264
+     * @return string
265
+     */
266
+    public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
267
+        $backend = self::findFirstActiveUsedBackend();
268
+        if ($backend) {
269
+            return $backend->getLogoutUrl();
270
+        }
271
+
272
+        $logoutUrl = $urlGenerator->linkToRouteAbsolute(
273
+            'core.login.logout',
274
+            [
275
+                'requesttoken' => \OCP\Util::callRegister(),
276
+            ]
277
+        );
278
+
279
+        return $logoutUrl;
280
+    }
281
+
282
+    /**
283
+     * Check if the user is an admin user
284
+     *
285
+     * @param string $uid uid of the admin
286
+     * @return bool
287
+     */
288
+    public static function isAdminUser($uid) {
289
+        $group = \OC::$server->getGroupManager()->get('admin');
290
+        $user = \OC::$server->getUserManager()->get($uid);
291
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
292
+            return true;
293
+        }
294
+        return false;
295
+    }
296
+
297
+
298
+    /**
299
+     * get the user id of the user currently logged in.
300
+     *
301
+     * @return string|bool uid or false
302
+     */
303
+    public static function getUser() {
304
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
305
+        if (!is_null($uid) && self::$incognitoMode === false) {
306
+            return $uid;
307
+        } else {
308
+            return false;
309
+        }
310
+    }
311
+
312
+    /**
313
+     * get the display name of the user currently logged in.
314
+     *
315
+     * @param string $uid
316
+     * @return string|bool uid or false
317
+     * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
318
+     *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
319
+     */
320
+    public static function getDisplayName($uid = null) {
321
+        if ($uid) {
322
+            $user = \OC::$server->getUserManager()->get($uid);
323
+            if ($user) {
324
+                return $user->getDisplayName();
325
+            } else {
326
+                return $uid;
327
+            }
328
+        } else {
329
+            $user = \OC::$server->getUserSession()->getUser();
330
+            if ($user) {
331
+                return $user->getDisplayName();
332
+            } else {
333
+                return false;
334
+            }
335
+        }
336
+    }
337
+
338
+    /**
339
+     * Set password
340
+     *
341
+     * @param string $uid The username
342
+     * @param string $password The new password
343
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
344
+     * @return bool
345
+     *
346
+     * Change the password of a user
347
+     */
348
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
349
+        $user = \OC::$server->getUserManager()->get($uid);
350
+        if ($user) {
351
+            return $user->setPassword($password, $recoveryPassword);
352
+        } else {
353
+            return false;
354
+        }
355
+    }
356
+
357
+    /**
358
+     * @param string $uid The username
359
+     * @return string
360
+     *
361
+     * returns the path to the users home directory
362
+     * @deprecated Use \OC::$server->getUserManager->getHome()
363
+     */
364
+    public static function getHome($uid) {
365
+        $user = \OC::$server->getUserManager()->get($uid);
366
+        if ($user) {
367
+            return $user->getHome();
368
+        } else {
369
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
370
+        }
371
+    }
372
+
373
+    /**
374
+     * Get a list of all users display name
375
+     *
376
+     * @param string $search
377
+     * @param int $limit
378
+     * @param int $offset
379
+     * @return array associative array with all display names (value) and corresponding uids (key)
380
+     *
381
+     * Get a list of all display names and user ids.
382
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
383
+     */
384
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
385
+        $displayNames = array();
386
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
387
+        foreach ($users as $user) {
388
+            $displayNames[$user->getUID()] = $user->getDisplayName();
389
+        }
390
+        return $displayNames;
391
+    }
392
+
393
+    /**
394
+     * Returns the first active backend from self::$_usedBackends.
395
+     *
396
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
397
+     */
398
+    private static function findFirstActiveUsedBackend() {
399
+        foreach (self::$_usedBackends as $backend) {
400
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
401
+                if ($backend->isSessionActive()) {
402
+                    return $backend;
403
+                }
404
+            }
405
+        }
406
+
407
+        return null;
408
+    }
409 409
 }
Please login to merge, or discard this patch.
lib/private/legacy/db.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -36,209 +36,209 @@
 block discarded – undo
36 36
  */
37 37
 class OC_DB {
38 38
 
39
-	/**
40
-	 * get MDB2 schema manager
41
-	 *
42
-	 * @return \OC\DB\MDB2SchemaManager
43
-	 */
44
-	private static function getMDB2SchemaManager() {
45
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
46
-	}
39
+    /**
40
+     * get MDB2 schema manager
41
+     *
42
+     * @return \OC\DB\MDB2SchemaManager
43
+     */
44
+    private static function getMDB2SchemaManager() {
45
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
46
+    }
47 47
 
48
-	/**
49
-	 * Prepare a SQL query
50
-	 * @param string $query Query string
51
-	 * @param int|null $limit
52
-	 * @param int|null $offset
53
-	 * @param bool|null $isManipulation
54
-	 * @throws \OC\DatabaseException
55
-	 * @return OC_DB_StatementWrapper prepared SQL query
56
-	 *
57
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
58
-	 */
59
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
60
-		$connection = \OC::$server->getDatabaseConnection();
48
+    /**
49
+     * Prepare a SQL query
50
+     * @param string $query Query string
51
+     * @param int|null $limit
52
+     * @param int|null $offset
53
+     * @param bool|null $isManipulation
54
+     * @throws \OC\DatabaseException
55
+     * @return OC_DB_StatementWrapper prepared SQL query
56
+     *
57
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
58
+     */
59
+    static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
60
+        $connection = \OC::$server->getDatabaseConnection();
61 61
 
62
-		if ($isManipulation === null) {
63
-			//try to guess, so we return the number of rows on manipulations
64
-			$isManipulation = self::isManipulation($query);
65
-		}
62
+        if ($isManipulation === null) {
63
+            //try to guess, so we return the number of rows on manipulations
64
+            $isManipulation = self::isManipulation($query);
65
+        }
66 66
 
67
-		// return the result
68
-		try {
69
-			$result =$connection->prepare($query, $limit, $offset);
70
-		} catch (\Doctrine\DBAL\DBALException $e) {
71
-			throw new \OC\DatabaseException($e->getMessage());
72
-		}
73
-		// differentiate between query and manipulation
74
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
75
-		return $result;
76
-	}
67
+        // return the result
68
+        try {
69
+            $result =$connection->prepare($query, $limit, $offset);
70
+        } catch (\Doctrine\DBAL\DBALException $e) {
71
+            throw new \OC\DatabaseException($e->getMessage());
72
+        }
73
+        // differentiate between query and manipulation
74
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
75
+        return $result;
76
+    }
77 77
 
78
-	/**
79
-	 * tries to guess the type of statement based on the first 10 characters
80
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
81
-	 *
82
-	 * @param string $sql
83
-	 * @return bool
84
-	 */
85
-	static public function isManipulation( $sql ) {
86
-		$selectOccurrence = stripos($sql, 'SELECT');
87
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
88
-			return false;
89
-		}
90
-		$insertOccurrence = stripos($sql, 'INSERT');
91
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
92
-			return true;
93
-		}
94
-		$updateOccurrence = stripos($sql, 'UPDATE');
95
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
96
-			return true;
97
-		}
98
-		$deleteOccurrence = stripos($sql, 'DELETE');
99
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
100
-			return true;
101
-		}
102
-		return false;
103
-	}
78
+    /**
79
+     * tries to guess the type of statement based on the first 10 characters
80
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
81
+     *
82
+     * @param string $sql
83
+     * @return bool
84
+     */
85
+    static public function isManipulation( $sql ) {
86
+        $selectOccurrence = stripos($sql, 'SELECT');
87
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
88
+            return false;
89
+        }
90
+        $insertOccurrence = stripos($sql, 'INSERT');
91
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
92
+            return true;
93
+        }
94
+        $updateOccurrence = stripos($sql, 'UPDATE');
95
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
96
+            return true;
97
+        }
98
+        $deleteOccurrence = stripos($sql, 'DELETE');
99
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
100
+            return true;
101
+        }
102
+        return false;
103
+    }
104 104
 
105
-	/**
106
-	 * execute a prepared statement, on error write log and throw exception
107
-	 * @param mixed $stmt OC_DB_StatementWrapper,
108
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
109
-	 *					.. or a simple sql query string
110
-	 * @param array $parameters
111
-	 * @return OC_DB_StatementWrapper
112
-	 * @throws \OC\DatabaseException
113
-	 */
114
-	static public function executeAudited( $stmt, array $parameters = []) {
115
-		if (is_string($stmt)) {
116
-			// convert to an array with 'sql'
117
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
118
-				// TODO try to convert LIMIT OFFSET notation to parameters
119
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
120
-						 . ' pass an array with \'limit\' and \'offset\' instead';
121
-				throw new \OC\DatabaseException($message);
122
-			}
123
-			$stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
124
-		}
125
-		if (is_array($stmt)) {
126
-			// convert to prepared statement
127
-			if ( ! array_key_exists('sql', $stmt) ) {
128
-				$message = 'statement array must at least contain key \'sql\'';
129
-				throw new \OC\DatabaseException($message);
130
-			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
132
-				$stmt['limit'] = null;
133
-			}
134
-			if ( ! array_key_exists('limit', $stmt) ) {
135
-				$stmt['offset'] = null;
136
-			}
137
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
138
-		}
139
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
140
-		if ($stmt instanceof OC_DB_StatementWrapper) {
141
-			$result = $stmt->execute($parameters);
142
-			self::raiseExceptionOnError($result, 'Could not execute statement');
143
-		} else {
144
-			if (is_object($stmt)) {
145
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
146
-			} else {
147
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
148
-			}
149
-			throw new \OC\DatabaseException($message);
150
-		}
151
-		return $result;
152
-	}
105
+    /**
106
+     * execute a prepared statement, on error write log and throw exception
107
+     * @param mixed $stmt OC_DB_StatementWrapper,
108
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
109
+     *					.. or a simple sql query string
110
+     * @param array $parameters
111
+     * @return OC_DB_StatementWrapper
112
+     * @throws \OC\DatabaseException
113
+     */
114
+    static public function executeAudited( $stmt, array $parameters = []) {
115
+        if (is_string($stmt)) {
116
+            // convert to an array with 'sql'
117
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
118
+                // TODO try to convert LIMIT OFFSET notation to parameters
119
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
120
+                            . ' pass an array with \'limit\' and \'offset\' instead';
121
+                throw new \OC\DatabaseException($message);
122
+            }
123
+            $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
124
+        }
125
+        if (is_array($stmt)) {
126
+            // convert to prepared statement
127
+            if ( ! array_key_exists('sql', $stmt) ) {
128
+                $message = 'statement array must at least contain key \'sql\'';
129
+                throw new \OC\DatabaseException($message);
130
+            }
131
+            if ( ! array_key_exists('limit', $stmt) ) {
132
+                $stmt['limit'] = null;
133
+            }
134
+            if ( ! array_key_exists('limit', $stmt) ) {
135
+                $stmt['offset'] = null;
136
+            }
137
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
138
+        }
139
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
140
+        if ($stmt instanceof OC_DB_StatementWrapper) {
141
+            $result = $stmt->execute($parameters);
142
+            self::raiseExceptionOnError($result, 'Could not execute statement');
143
+        } else {
144
+            if (is_object($stmt)) {
145
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
146
+            } else {
147
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
148
+            }
149
+            throw new \OC\DatabaseException($message);
150
+        }
151
+        return $result;
152
+    }
153 153
 
154
-	/**
155
-	 * saves database schema to xml file
156
-	 * @param string $file name of file
157
-	 * @return bool
158
-	 *
159
-	 * TODO: write more documentation
160
-	 */
161
-	public static function getDbStructure($file) {
162
-		$schemaManager = self::getMDB2SchemaManager();
163
-		return $schemaManager->getDbStructure($file);
164
-	}
154
+    /**
155
+     * saves database schema to xml file
156
+     * @param string $file name of file
157
+     * @return bool
158
+     *
159
+     * TODO: write more documentation
160
+     */
161
+    public static function getDbStructure($file) {
162
+        $schemaManager = self::getMDB2SchemaManager();
163
+        return $schemaManager->getDbStructure($file);
164
+    }
165 165
 
166
-	/**
167
-	 * Creates tables from XML file
168
-	 * @param string $file file to read structure from
169
-	 * @return bool
170
-	 *
171
-	 * TODO: write more documentation
172
-	 */
173
-	public static function createDbFromStructure( $file ) {
174
-		$schemaManager = self::getMDB2SchemaManager();
175
-		return $schemaManager->createDbFromStructure($file);
176
-	}
166
+    /**
167
+     * Creates tables from XML file
168
+     * @param string $file file to read structure from
169
+     * @return bool
170
+     *
171
+     * TODO: write more documentation
172
+     */
173
+    public static function createDbFromStructure( $file ) {
174
+        $schemaManager = self::getMDB2SchemaManager();
175
+        return $schemaManager->createDbFromStructure($file);
176
+    }
177 177
 
178
-	/**
179
-	 * update the database schema
180
-	 * @param string $file file to read structure from
181
-	 * @throws Exception
182
-	 * @return string|boolean
183
-	 * @suppress PhanDeprecatedFunction
184
-	 */
185
-	public static function updateDbFromStructure($file) {
186
-		$schemaManager = self::getMDB2SchemaManager();
187
-		try {
188
-			$result = $schemaManager->updateDbFromStructure($file);
189
-		} catch (Exception $e) {
190
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
191
-			throw $e;
192
-		}
193
-		return $result;
194
-	}
178
+    /**
179
+     * update the database schema
180
+     * @param string $file file to read structure from
181
+     * @throws Exception
182
+     * @return string|boolean
183
+     * @suppress PhanDeprecatedFunction
184
+     */
185
+    public static function updateDbFromStructure($file) {
186
+        $schemaManager = self::getMDB2SchemaManager();
187
+        try {
188
+            $result = $schemaManager->updateDbFromStructure($file);
189
+        } catch (Exception $e) {
190
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
191
+            throw $e;
192
+        }
193
+        return $result;
194
+    }
195 195
 
196
-	/**
197
-	 * remove all tables defined in a database structure xml file
198
-	 * @param string $file the xml file describing the tables
199
-	 */
200
-	public static function removeDBStructure($file) {
201
-		$schemaManager = self::getMDB2SchemaManager();
202
-		$schemaManager->removeDBStructure($file);
203
-	}
196
+    /**
197
+     * remove all tables defined in a database structure xml file
198
+     * @param string $file the xml file describing the tables
199
+     */
200
+    public static function removeDBStructure($file) {
201
+        $schemaManager = self::getMDB2SchemaManager();
202
+        $schemaManager->removeDBStructure($file);
203
+    }
204 204
 
205
-	/**
206
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
207
-	 * @param mixed $result
208
-	 * @param string $message
209
-	 * @return void
210
-	 * @throws \OC\DatabaseException
211
-	 */
212
-	public static function raiseExceptionOnError($result, $message = null) {
213
-		if($result === false) {
214
-			if ($message === null) {
215
-				$message = self::getErrorMessage();
216
-			} else {
217
-				$message .= ', Root cause:' . self::getErrorMessage();
218
-			}
219
-			throw new \OC\DatabaseException($message);
220
-		}
221
-	}
205
+    /**
206
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
207
+     * @param mixed $result
208
+     * @param string $message
209
+     * @return void
210
+     * @throws \OC\DatabaseException
211
+     */
212
+    public static function raiseExceptionOnError($result, $message = null) {
213
+        if($result === false) {
214
+            if ($message === null) {
215
+                $message = self::getErrorMessage();
216
+            } else {
217
+                $message .= ', Root cause:' . self::getErrorMessage();
218
+            }
219
+            throw new \OC\DatabaseException($message);
220
+        }
221
+    }
222 222
 
223
-	/**
224
-	 * returns the error code and message as a string for logging
225
-	 * works with DoctrineException
226
-	 * @return string
227
-	 */
228
-	public static function getErrorMessage() {
229
-		$connection = \OC::$server->getDatabaseConnection();
230
-		return $connection->getError();
231
-	}
223
+    /**
224
+     * returns the error code and message as a string for logging
225
+     * works with DoctrineException
226
+     * @return string
227
+     */
228
+    public static function getErrorMessage() {
229
+        $connection = \OC::$server->getDatabaseConnection();
230
+        return $connection->getError();
231
+    }
232 232
 
233
-	/**
234
-	 * Checks if a table exists in the database - the database prefix will be prepended
235
-	 *
236
-	 * @param string $table
237
-	 * @return bool
238
-	 * @throws \OC\DatabaseException
239
-	 */
240
-	public static function tableExists($table) {
241
-		$connection = \OC::$server->getDatabaseConnection();
242
-		return $connection->tableExists($table);
243
-	}
233
+    /**
234
+     * Checks if a table exists in the database - the database prefix will be prepended
235
+     *
236
+     * @param string $table
237
+     * @return bool
238
+     * @throws \OC\DatabaseException
239
+     */
240
+    public static function tableExists($table) {
241
+        $connection = \OC::$server->getDatabaseConnection();
242
+        return $connection->tableExists($table);
243
+    }
244 244
 }
Please login to merge, or discard this patch.
lib/private/legacy/files.php 1 patch
Indentation   +430 added lines, -430 removed lines patch added patch discarded remove patch
@@ -49,438 +49,438 @@
 block discarded – undo
49 49
  *
50 50
  */
51 51
 class OC_Files {
52
-	const FILE = 1;
53
-	const ZIP_FILES = 2;
54
-	const ZIP_DIR = 3;
55
-
56
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
-
58
-
59
-	private static $multipartBoundary = '';
60
-
61
-	/**
62
-	 * @return string
63
-	 */
64
-	private static function getBoundary() {
65
-		if (empty(self::$multipartBoundary)) {
66
-			self::$multipartBoundary = md5(mt_rand());
67
-		}
68
-		return self::$multipartBoundary;
69
-	}
70
-
71
-	/**
72
-	 * @param string $filename
73
-	 * @param string $name
74
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
-	 */
76
-	private static function sendHeaders($filename, $name, array $rangeArray) {
77
-		OC_Response::setContentDispositionHeader($name, 'attachment');
78
-		header('Content-Transfer-Encoding: binary', true);
79
-		header('Pragma: public');// enable caching in IE
80
-		header('Expires: 0');
81
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
83
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
-		if ($fileSize > -1) {
85
-			if (!empty($rangeArray)) {
86
-			    header('HTTP/1.1 206 Partial Content', true);
87
-			    header('Accept-Ranges: bytes', true);
88
-			    if (count($rangeArray) > 1) {
89
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
90
-				// no Content-Length header here
91
-			    }
92
-			    else {
93
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
-			    }
96
-			}
97
-			else {
98
-			    OC_Response::setContentLengthHeader($fileSize);
99
-			}
100
-		}
101
-		header('Content-Type: '.$type, true);
102
-	}
103
-
104
-	/**
105
-	 * return the content of a file or return a zip file containing multiple files
106
-	 *
107
-	 * @param string $dir
108
-	 * @param string $files ; separated list of files to download
109
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
-	 */
111
-	public static function get($dir, $files, $params = null) {
112
-
113
-		$view = \OC\Files\Filesystem::getView();
114
-		$getType = self::FILE;
115
-		$filename = $dir;
116
-		try {
117
-
118
-			if (is_array($files) && count($files) === 1) {
119
-				$files = $files[0];
120
-			}
121
-
122
-			if (!is_array($files)) {
123
-				$filename = $dir . '/' . $files;
124
-				if (!$view->is_dir($filename)) {
125
-					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
-					return;
127
-				}
128
-			}
129
-
130
-			$name = 'download';
131
-			if (is_array($files)) {
132
-				$getType = self::ZIP_FILES;
133
-				$basename = basename($dir);
134
-				if ($basename) {
135
-					$name = $basename;
136
-				}
137
-
138
-				$filename = $dir . '/' . $name;
139
-			} else {
140
-				$filename = $dir . '/' . $files;
141
-				$getType = self::ZIP_DIR;
142
-				// downloading root ?
143
-				if ($files !== '') {
144
-					$name = $files;
145
-				}
146
-			}
147
-
148
-			self::lockFiles($view, $dir, $files);
149
-
150
-			/* Calculate filesize and number of files */
151
-			if ($getType === self::ZIP_FILES) {
152
-				$fileInfos = array();
153
-				$fileSize = 0;
154
-				foreach ($files as $file) {
155
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
-					$fileSize += $fileInfo->getSize();
157
-					$fileInfos[] = $fileInfo;
158
-				}
159
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
160
-			} elseif ($getType === self::ZIP_DIR) {
161
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
-				$fileSize = $fileInfo->getSize();
163
-				$numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
-			}
165
-
166
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
-			OC_Util::obEnd();
168
-
169
-			$streamer->sendHeaders($name);
170
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
-				@set_time_limit(0);
173
-			}
174
-			ignore_user_abort(true);
175
-
176
-			if ($getType === self::ZIP_FILES) {
177
-				foreach ($files as $file) {
178
-					$file = $dir . '/' . $file;
179
-					if (\OC\Files\Filesystem::is_file($file)) {
180
-						$fileSize = \OC\Files\Filesystem::filesize($file);
181
-						$fileTime = \OC\Files\Filesystem::filemtime($file);
182
-						$fh = \OC\Files\Filesystem::fopen($file, 'r');
183
-						$streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
-						fclose($fh);
185
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
186
-						$streamer->addDirRecursive($file);
187
-					}
188
-				}
189
-			} elseif ($getType === self::ZIP_DIR) {
190
-				$file = $dir . '/' . $files;
191
-				$streamer->addDirRecursive($file);
192
-			}
193
-			$streamer->finalize();
194
-			set_time_limit($executionTime);
195
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
-		} catch (\OCP\Lock\LockedException $ex) {
197
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
-			OC::$server->getLogger()->logException($ex);
199
-			$l = \OC::$server->getL10N('core');
200
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
202
-		} catch (\OCP\Files\ForbiddenException $ex) {
203
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
-			OC::$server->getLogger()->logException($ex);
205
-			$l = \OC::$server->getL10N('core');
206
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
207
-		} catch (\Exception $ex) {
208
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
-			OC::$server->getLogger()->logException($ex);
210
-			$l = \OC::$server->getL10N('core');
211
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * @param string $rangeHeaderPos
218
-	 * @param int $fileSize
219
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
-	 */
221
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
-		$rArray=explode(',', $rangeHeaderPos);
223
-		$minOffset = 0;
224
-		$ind = 0;
225
-
226
-		$rangeArray = array();
227
-
228
-		foreach ($rArray as $value) {
229
-			$ranges = explode('-', $value);
230
-			if (is_numeric($ranges[0])) {
231
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
-					$ranges[0] = $minOffset;
233
-				}
234
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
-					$ind--;
236
-					$ranges[0] = $rangeArray[$ind]['from'];
237
-				}
238
-			}
239
-
240
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
-				// case: x-x
242
-				if ($ranges[1] >= $fileSize) {
243
-					$ranges[1] = $fileSize-1;
244
-				}
245
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
-				$minOffset = $ranges[1] + 1;
247
-				if ($minOffset >= $fileSize) {
248
-					break;
249
-				}
250
-			}
251
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
-				// case: x-
253
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
-				break;
255
-			}
256
-			elseif (is_numeric($ranges[1])) {
257
-				// case: -x
258
-				if ($ranges[1] > $fileSize) {
259
-					$ranges[1] = $fileSize;
260
-				}
261
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
-				break;
263
-			}
264
-		}
265
-		return $rangeArray;
266
-	}
267
-
268
-	/**
269
-	 * @param View $view
270
-	 * @param string $name
271
-	 * @param string $dir
272
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
-	 */
274
-	private static function getSingleFile($view, $dir, $name, $params) {
275
-		$filename = $dir . '/' . $name;
276
-		OC_Util::obEnd();
277
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
52
+    const FILE = 1;
53
+    const ZIP_FILES = 2;
54
+    const ZIP_DIR = 3;
55
+
56
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
+
58
+
59
+    private static $multipartBoundary = '';
60
+
61
+    /**
62
+     * @return string
63
+     */
64
+    private static function getBoundary() {
65
+        if (empty(self::$multipartBoundary)) {
66
+            self::$multipartBoundary = md5(mt_rand());
67
+        }
68
+        return self::$multipartBoundary;
69
+    }
70
+
71
+    /**
72
+     * @param string $filename
73
+     * @param string $name
74
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
+     */
76
+    private static function sendHeaders($filename, $name, array $rangeArray) {
77
+        OC_Response::setContentDispositionHeader($name, 'attachment');
78
+        header('Content-Transfer-Encoding: binary', true);
79
+        header('Pragma: public');// enable caching in IE
80
+        header('Expires: 0');
81
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
83
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
+        if ($fileSize > -1) {
85
+            if (!empty($rangeArray)) {
86
+                header('HTTP/1.1 206 Partial Content', true);
87
+                header('Accept-Ranges: bytes', true);
88
+                if (count($rangeArray) > 1) {
89
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
90
+                // no Content-Length header here
91
+                }
92
+                else {
93
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
+                }
96
+            }
97
+            else {
98
+                OC_Response::setContentLengthHeader($fileSize);
99
+            }
100
+        }
101
+        header('Content-Type: '.$type, true);
102
+    }
103
+
104
+    /**
105
+     * return the content of a file or return a zip file containing multiple files
106
+     *
107
+     * @param string $dir
108
+     * @param string $files ; separated list of files to download
109
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
+     */
111
+    public static function get($dir, $files, $params = null) {
112
+
113
+        $view = \OC\Files\Filesystem::getView();
114
+        $getType = self::FILE;
115
+        $filename = $dir;
116
+        try {
117
+
118
+            if (is_array($files) && count($files) === 1) {
119
+                $files = $files[0];
120
+            }
121
+
122
+            if (!is_array($files)) {
123
+                $filename = $dir . '/' . $files;
124
+                if (!$view->is_dir($filename)) {
125
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
+                    return;
127
+                }
128
+            }
129
+
130
+            $name = 'download';
131
+            if (is_array($files)) {
132
+                $getType = self::ZIP_FILES;
133
+                $basename = basename($dir);
134
+                if ($basename) {
135
+                    $name = $basename;
136
+                }
137
+
138
+                $filename = $dir . '/' . $name;
139
+            } else {
140
+                $filename = $dir . '/' . $files;
141
+                $getType = self::ZIP_DIR;
142
+                // downloading root ?
143
+                if ($files !== '') {
144
+                    $name = $files;
145
+                }
146
+            }
147
+
148
+            self::lockFiles($view, $dir, $files);
149
+
150
+            /* Calculate filesize and number of files */
151
+            if ($getType === self::ZIP_FILES) {
152
+                $fileInfos = array();
153
+                $fileSize = 0;
154
+                foreach ($files as $file) {
155
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
+                    $fileSize += $fileInfo->getSize();
157
+                    $fileInfos[] = $fileInfo;
158
+                }
159
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
160
+            } elseif ($getType === self::ZIP_DIR) {
161
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
+                $fileSize = $fileInfo->getSize();
163
+                $numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
+            }
165
+
166
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
+            OC_Util::obEnd();
168
+
169
+            $streamer->sendHeaders($name);
170
+            $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
+                @set_time_limit(0);
173
+            }
174
+            ignore_user_abort(true);
175
+
176
+            if ($getType === self::ZIP_FILES) {
177
+                foreach ($files as $file) {
178
+                    $file = $dir . '/' . $file;
179
+                    if (\OC\Files\Filesystem::is_file($file)) {
180
+                        $fileSize = \OC\Files\Filesystem::filesize($file);
181
+                        $fileTime = \OC\Files\Filesystem::filemtime($file);
182
+                        $fh = \OC\Files\Filesystem::fopen($file, 'r');
183
+                        $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
+                        fclose($fh);
185
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
186
+                        $streamer->addDirRecursive($file);
187
+                    }
188
+                }
189
+            } elseif ($getType === self::ZIP_DIR) {
190
+                $file = $dir . '/' . $files;
191
+                $streamer->addDirRecursive($file);
192
+            }
193
+            $streamer->finalize();
194
+            set_time_limit($executionTime);
195
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
+        } catch (\OCP\Lock\LockedException $ex) {
197
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
+            OC::$server->getLogger()->logException($ex);
199
+            $l = \OC::$server->getL10N('core');
200
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
202
+        } catch (\OCP\Files\ForbiddenException $ex) {
203
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
+            OC::$server->getLogger()->logException($ex);
205
+            $l = \OC::$server->getL10N('core');
206
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
207
+        } catch (\Exception $ex) {
208
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
+            OC::$server->getLogger()->logException($ex);
210
+            $l = \OC::$server->getL10N('core');
211
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
213
+        }
214
+    }
215
+
216
+    /**
217
+     * @param string $rangeHeaderPos
218
+     * @param int $fileSize
219
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
+     */
221
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
+        $rArray=explode(',', $rangeHeaderPos);
223
+        $minOffset = 0;
224
+        $ind = 0;
225
+
226
+        $rangeArray = array();
227
+
228
+        foreach ($rArray as $value) {
229
+            $ranges = explode('-', $value);
230
+            if (is_numeric($ranges[0])) {
231
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
+                    $ranges[0] = $minOffset;
233
+                }
234
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
+                    $ind--;
236
+                    $ranges[0] = $rangeArray[$ind]['from'];
237
+                }
238
+            }
239
+
240
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
+                // case: x-x
242
+                if ($ranges[1] >= $fileSize) {
243
+                    $ranges[1] = $fileSize-1;
244
+                }
245
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
+                $minOffset = $ranges[1] + 1;
247
+                if ($minOffset >= $fileSize) {
248
+                    break;
249
+                }
250
+            }
251
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
+                // case: x-
253
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
+                break;
255
+            }
256
+            elseif (is_numeric($ranges[1])) {
257
+                // case: -x
258
+                if ($ranges[1] > $fileSize) {
259
+                    $ranges[1] = $fileSize;
260
+                }
261
+                $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
+                break;
263
+            }
264
+        }
265
+        return $rangeArray;
266
+    }
267
+
268
+    /**
269
+     * @param View $view
270
+     * @param string $name
271
+     * @param string $dir
272
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
+     */
274
+    private static function getSingleFile($view, $dir, $name, $params) {
275
+        $filename = $dir . '/' . $name;
276
+        OC_Util::obEnd();
277
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
278 278
 		
279
-		$rangeArray = array();
279
+        $rangeArray = array();
280 280
 
281
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
-								 \OC\Files\Filesystem::filesize($filename));
284
-		}
281
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
+                                    \OC\Files\Filesystem::filesize($filename));
284
+        }
285 285
 		
286
-		if (\OC\Files\Filesystem::isReadable($filename)) {
287
-			self::sendHeaders($filename, $name, $rangeArray);
288
-		} elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
-			header("HTTP/1.1 404 Not Found");
290
-			$tmpl = new OC_Template('', '404', 'guest');
291
-			$tmpl->printPage();
292
-			exit();
293
-		} else {
294
-			header("HTTP/1.1 403 Forbidden");
295
-			die('403 Forbidden');
296
-		}
297
-		if (isset($params['head']) && $params['head']) {
298
-			return;
299
-		}
300
-		if (!empty($rangeArray)) {
301
-			try {
302
-			    if (count($rangeArray) == 1) {
303
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
-			    }
305
-			    else {
306
-				// check if file is seekable (if not throw UnseekableException)
307
-				// we have to check it before body contents
308
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
-
310
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
-
312
-				foreach ($rangeArray as $range) {
313
-				    echo "\r\n--".self::getBoundary()."\r\n".
314
-				         "Content-type: ".$type."\r\n".
315
-				         "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
-				    $view->readfilePart($filename, $range['from'], $range['to']);
317
-				}
318
-				echo "\r\n--".self::getBoundary()."--\r\n";
319
-			    }
320
-			} catch (\OCP\Files\UnseekableException $ex) {
321
-			    // file is unseekable
322
-			    header_remove('Accept-Ranges');
323
-			    header_remove('Content-Range');
324
-			    header("HTTP/1.1 200 OK");
325
-			    self::sendHeaders($filename, $name, array());
326
-			    $view->readfile($filename);
327
-			}
328
-		}
329
-		else {
330
-		    $view->readfile($filename);
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * Returns the total (recursive) number of files and folders in the given
336
-	 * FileInfos.
337
-	 *
338
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
-	 * @return int the total number of files and folders
340
-	 */
341
-	private static function getNumberOfFiles($fileInfos) {
342
-		$numberOfFiles = 0;
343
-
344
-		$view = new View();
345
-
346
-		while ($fileInfo = array_pop($fileInfos)) {
347
-			$numberOfFiles++;
348
-
349
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
-			}
352
-		}
353
-
354
-		return $numberOfFiles;
355
-	}
356
-
357
-	/**
358
-	 * @param View $view
359
-	 * @param string $dir
360
-	 * @param string[]|string $files
361
-	 */
362
-	public static function lockFiles($view, $dir, $files) {
363
-		if (!is_array($files)) {
364
-			$file = $dir . '/' . $files;
365
-			$files = [$file];
366
-		}
367
-		foreach ($files as $file) {
368
-			$file = $dir . '/' . $file;
369
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
-			if ($view->is_dir($file)) {
371
-				$contents = $view->getDirectoryContent($file);
372
-				$contents = array_map(function($fileInfo) use ($file) {
373
-					/** @var \OCP\Files\FileInfo $fileInfo */
374
-					return $file . '/' . $fileInfo->getName();
375
-				}, $contents);
376
-				self::lockFiles($view, $dir, $contents);
377
-			}
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * set the maximum upload size limit for apache hosts using .htaccess
383
-	 *
384
-	 * @param int $size file size in bytes
385
-	 * @param array $files override '.htaccess' and '.user.ini' locations
386
-	 * @return bool|int false on failure, size on success
387
-	 */
388
-	public static function setUploadLimit($size, $files = []) {
389
-		//don't allow user to break his config
390
-		$size = (int)$size;
391
-		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
-			return false;
393
-		}
394
-		$size = OC_Helper::phpFileSize($size);
395
-
396
-		$phpValueKeys = array(
397
-			'upload_max_filesize',
398
-			'post_max_size'
399
-		);
400
-
401
-		// default locations if not overridden by $files
402
-		$files = array_merge([
403
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
-		], $files);
406
-
407
-		$updateFiles = [
408
-			$files['.htaccess'] => [
409
-				'pattern' => '/php_value %1$s (\S)*/',
410
-				'setting' => 'php_value %1$s %2$s'
411
-			],
412
-			$files['.user.ini'] => [
413
-				'pattern' => '/%1$s=(\S)*/',
414
-				'setting' => '%1$s=%2$s'
415
-			]
416
-		];
417
-
418
-		$success = true;
419
-
420
-		foreach ($updateFiles as $filename => $patternMap) {
421
-			// suppress warnings from fopen()
422
-			$handle = @fopen($filename, 'r+');
423
-			if (!$handle) {
424
-				\OCP\Util::writeLog('files',
425
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
-					ILogger::WARN);
427
-				$success = false;
428
-				continue; // try to update as many files as possible
429
-			}
430
-
431
-			$content = '';
432
-			while (!feof($handle)) {
433
-				$content .= fread($handle, 1000);
434
-			}
435
-
436
-			foreach ($phpValueKeys as $key) {
437
-				$pattern = vsprintf($patternMap['pattern'], [$key]);
438
-				$setting = vsprintf($patternMap['setting'], [$key, $size]);
439
-				$hasReplaced = 0;
440
-				$newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
-				if ($newContent !== null) {
442
-					$content = $newContent;
443
-				}
444
-				if ($hasReplaced === 0) {
445
-					$content .= "\n" . $setting;
446
-				}
447
-			}
448
-
449
-			// write file back
450
-			ftruncate($handle, 0);
451
-			rewind($handle);
452
-			fwrite($handle, $content);
453
-
454
-			fclose($handle);
455
-		}
456
-
457
-		if ($success) {
458
-			return OC_Helper::computerFileSize($size);
459
-		}
460
-		return false;
461
-	}
462
-
463
-	/**
464
-	 * @param string $dir
465
-	 * @param $files
466
-	 * @param integer $getType
467
-	 * @param View $view
468
-	 * @param string $filename
469
-	 */
470
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
-		if ($getType === self::FILE) {
472
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
-		}
474
-		if ($getType === self::ZIP_FILES) {
475
-			foreach ($files as $file) {
476
-				$file = $dir . '/' . $file;
477
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
-			}
479
-		}
480
-		if ($getType === self::ZIP_DIR) {
481
-			$file = $dir . '/' . $files;
482
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
-		}
484
-	}
286
+        if (\OC\Files\Filesystem::isReadable($filename)) {
287
+            self::sendHeaders($filename, $name, $rangeArray);
288
+        } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
+            header("HTTP/1.1 404 Not Found");
290
+            $tmpl = new OC_Template('', '404', 'guest');
291
+            $tmpl->printPage();
292
+            exit();
293
+        } else {
294
+            header("HTTP/1.1 403 Forbidden");
295
+            die('403 Forbidden');
296
+        }
297
+        if (isset($params['head']) && $params['head']) {
298
+            return;
299
+        }
300
+        if (!empty($rangeArray)) {
301
+            try {
302
+                if (count($rangeArray) == 1) {
303
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
+                }
305
+                else {
306
+                // check if file is seekable (if not throw UnseekableException)
307
+                // we have to check it before body contents
308
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
+
310
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
+
312
+                foreach ($rangeArray as $range) {
313
+                    echo "\r\n--".self::getBoundary()."\r\n".
314
+                            "Content-type: ".$type."\r\n".
315
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
+                    $view->readfilePart($filename, $range['from'], $range['to']);
317
+                }
318
+                echo "\r\n--".self::getBoundary()."--\r\n";
319
+                }
320
+            } catch (\OCP\Files\UnseekableException $ex) {
321
+                // file is unseekable
322
+                header_remove('Accept-Ranges');
323
+                header_remove('Content-Range');
324
+                header("HTTP/1.1 200 OK");
325
+                self::sendHeaders($filename, $name, array());
326
+                $view->readfile($filename);
327
+            }
328
+        }
329
+        else {
330
+            $view->readfile($filename);
331
+        }
332
+    }
333
+
334
+    /**
335
+     * Returns the total (recursive) number of files and folders in the given
336
+     * FileInfos.
337
+     *
338
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
+     * @return int the total number of files and folders
340
+     */
341
+    private static function getNumberOfFiles($fileInfos) {
342
+        $numberOfFiles = 0;
343
+
344
+        $view = new View();
345
+
346
+        while ($fileInfo = array_pop($fileInfos)) {
347
+            $numberOfFiles++;
348
+
349
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
+            }
352
+        }
353
+
354
+        return $numberOfFiles;
355
+    }
356
+
357
+    /**
358
+     * @param View $view
359
+     * @param string $dir
360
+     * @param string[]|string $files
361
+     */
362
+    public static function lockFiles($view, $dir, $files) {
363
+        if (!is_array($files)) {
364
+            $file = $dir . '/' . $files;
365
+            $files = [$file];
366
+        }
367
+        foreach ($files as $file) {
368
+            $file = $dir . '/' . $file;
369
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
+            if ($view->is_dir($file)) {
371
+                $contents = $view->getDirectoryContent($file);
372
+                $contents = array_map(function($fileInfo) use ($file) {
373
+                    /** @var \OCP\Files\FileInfo $fileInfo */
374
+                    return $file . '/' . $fileInfo->getName();
375
+                }, $contents);
376
+                self::lockFiles($view, $dir, $contents);
377
+            }
378
+        }
379
+    }
380
+
381
+    /**
382
+     * set the maximum upload size limit for apache hosts using .htaccess
383
+     *
384
+     * @param int $size file size in bytes
385
+     * @param array $files override '.htaccess' and '.user.ini' locations
386
+     * @return bool|int false on failure, size on success
387
+     */
388
+    public static function setUploadLimit($size, $files = []) {
389
+        //don't allow user to break his config
390
+        $size = (int)$size;
391
+        if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
+            return false;
393
+        }
394
+        $size = OC_Helper::phpFileSize($size);
395
+
396
+        $phpValueKeys = array(
397
+            'upload_max_filesize',
398
+            'post_max_size'
399
+        );
400
+
401
+        // default locations if not overridden by $files
402
+        $files = array_merge([
403
+            '.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
+            '.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
+        ], $files);
406
+
407
+        $updateFiles = [
408
+            $files['.htaccess'] => [
409
+                'pattern' => '/php_value %1$s (\S)*/',
410
+                'setting' => 'php_value %1$s %2$s'
411
+            ],
412
+            $files['.user.ini'] => [
413
+                'pattern' => '/%1$s=(\S)*/',
414
+                'setting' => '%1$s=%2$s'
415
+            ]
416
+        ];
417
+
418
+        $success = true;
419
+
420
+        foreach ($updateFiles as $filename => $patternMap) {
421
+            // suppress warnings from fopen()
422
+            $handle = @fopen($filename, 'r+');
423
+            if (!$handle) {
424
+                \OCP\Util::writeLog('files',
425
+                    'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
+                    ILogger::WARN);
427
+                $success = false;
428
+                continue; // try to update as many files as possible
429
+            }
430
+
431
+            $content = '';
432
+            while (!feof($handle)) {
433
+                $content .= fread($handle, 1000);
434
+            }
435
+
436
+            foreach ($phpValueKeys as $key) {
437
+                $pattern = vsprintf($patternMap['pattern'], [$key]);
438
+                $setting = vsprintf($patternMap['setting'], [$key, $size]);
439
+                $hasReplaced = 0;
440
+                $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
+                if ($newContent !== null) {
442
+                    $content = $newContent;
443
+                }
444
+                if ($hasReplaced === 0) {
445
+                    $content .= "\n" . $setting;
446
+                }
447
+            }
448
+
449
+            // write file back
450
+            ftruncate($handle, 0);
451
+            rewind($handle);
452
+            fwrite($handle, $content);
453
+
454
+            fclose($handle);
455
+        }
456
+
457
+        if ($success) {
458
+            return OC_Helper::computerFileSize($size);
459
+        }
460
+        return false;
461
+    }
462
+
463
+    /**
464
+     * @param string $dir
465
+     * @param $files
466
+     * @param integer $getType
467
+     * @param View $view
468
+     * @param string $filename
469
+     */
470
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
+        if ($getType === self::FILE) {
472
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
+        }
474
+        if ($getType === self::ZIP_FILES) {
475
+            foreach ($files as $file) {
476
+                $file = $dir . '/' . $file;
477
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
+            }
479
+        }
480
+        if ($getType === self::ZIP_DIR) {
481
+            $file = $dir . '/' . $files;
482
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
+        }
484
+    }
485 485
 
486 486
 }
Please login to merge, or discard this patch.
lib/private/legacy/util.php 1 patch
Indentation   +1432 added lines, -1432 removed lines patch added patch discarded remove patch
@@ -66,1440 +66,1440 @@
 block discarded – undo
66 66
 use OCP\IUser;
67 67
 
68 68
 class OC_Util {
69
-	public static $scripts = array();
70
-	public static $styles = array();
71
-	public static $headers = array();
72
-	private static $rootMounted = false;
73
-	private static $fsSetup = false;
74
-
75
-	/** @var array Local cache of version.php */
76
-	private static $versionCache = null;
77
-
78
-	protected static function getAppManager() {
79
-		return \OC::$server->getAppManager();
80
-	}
81
-
82
-	private static function initLocalStorageRootFS() {
83
-		// mount local file backend as root
84
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
85
-		//first set up the local "root" storage
86
-		\OC\Files\Filesystem::initMountManager();
87
-		if (!self::$rootMounted) {
88
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
89
-			self::$rootMounted = true;
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * mounting an object storage as the root fs will in essence remove the
95
-	 * necessity of a data folder being present.
96
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
97
-	 *
98
-	 * @param array $config containing 'class' and optional 'arguments'
99
-	 * @suppress PhanDeprecatedFunction
100
-	 */
101
-	private static function initObjectStoreRootFS($config) {
102
-		// check misconfiguration
103
-		if (empty($config['class'])) {
104
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
105
-		}
106
-		if (!isset($config['arguments'])) {
107
-			$config['arguments'] = array();
108
-		}
109
-
110
-		// instantiate object store implementation
111
-		$name = $config['class'];
112
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
113
-			$segments = explode('\\', $name);
114
-			OC_App::loadApp(strtolower($segments[1]));
115
-		}
116
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
117
-		// mount with plain / root object store implementation
118
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
119
-
120
-		// mount object storage as root
121
-		\OC\Files\Filesystem::initMountManager();
122
-		if (!self::$rootMounted) {
123
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
124
-			self::$rootMounted = true;
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * mounting an object storage as the root fs will in essence remove the
130
-	 * necessity of a data folder being present.
131
-	 *
132
-	 * @param array $config containing 'class' and optional 'arguments'
133
-	 * @suppress PhanDeprecatedFunction
134
-	 */
135
-	private static function initObjectStoreMultibucketRootFS($config) {
136
-		// check misconfiguration
137
-		if (empty($config['class'])) {
138
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
139
-		}
140
-		if (!isset($config['arguments'])) {
141
-			$config['arguments'] = array();
142
-		}
143
-
144
-		// instantiate object store implementation
145
-		$name = $config['class'];
146
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
147
-			$segments = explode('\\', $name);
148
-			OC_App::loadApp(strtolower($segments[1]));
149
-		}
150
-
151
-		if (!isset($config['arguments']['bucket'])) {
152
-			$config['arguments']['bucket'] = '';
153
-		}
154
-		// put the root FS always in first bucket for multibucket configuration
155
-		$config['arguments']['bucket'] .= '0';
156
-
157
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
158
-		// mount with plain / root object store implementation
159
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
160
-
161
-		// mount object storage as root
162
-		\OC\Files\Filesystem::initMountManager();
163
-		if (!self::$rootMounted) {
164
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
165
-			self::$rootMounted = true;
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * Can be set up
171
-	 *
172
-	 * @param string $user
173
-	 * @return boolean
174
-	 * @description configure the initial filesystem based on the configuration
175
-	 * @suppress PhanDeprecatedFunction
176
-	 * @suppress PhanAccessMethodInternal
177
-	 */
178
-	public static function setupFS($user = '') {
179
-		//setting up the filesystem twice can only lead to trouble
180
-		if (self::$fsSetup) {
181
-			return false;
182
-		}
183
-
184
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
185
-
186
-		// If we are not forced to load a specific user we load the one that is logged in
187
-		if ($user === null) {
188
-			$user = '';
189
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
190
-			$user = OC_User::getUser();
191
-		}
192
-
193
-		// load all filesystem apps before, so no setup-hook gets lost
194
-		OC_App::loadApps(array('filesystem'));
195
-
196
-		// the filesystem will finish when $user is not empty,
197
-		// mark fs setup here to avoid doing the setup from loading
198
-		// OC_Filesystem
199
-		if ($user != '') {
200
-			self::$fsSetup = true;
201
-		}
202
-
203
-		\OC\Files\Filesystem::initMountManager();
204
-
205
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
206
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
207
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
208
-				/** @var \OC\Files\Storage\Common $storage */
209
-				$storage->setMountOptions($mount->getOptions());
210
-			}
211
-			return $storage;
212
-		});
213
-
214
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
215
-			if (!$mount->getOption('enable_sharing', true)) {
216
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
217
-					'storage' => $storage,
218
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
219
-				]);
220
-			}
221
-			return $storage;
222
-		});
223
-
224
-		// install storage availability wrapper, before most other wrappers
225
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
226
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
227
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
228
-			}
229
-			return $storage;
230
-		});
231
-
232
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
233
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
235
-			}
236
-			return $storage;
237
-		});
238
-
239
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
240
-			// set up quota for home storages, even for other users
241
-			// which can happen when using sharing
242
-
243
-			/**
244
-			 * @var \OC\Files\Storage\Storage $storage
245
-			 */
246
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
247
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
248
-			) {
249
-				/** @var \OC\Files\Storage\Home $storage */
250
-				if (is_object($storage->getUser())) {
251
-					$user = $storage->getUser()->getUID();
252
-					$quota = OC_Util::getUserQuota($user);
253
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
254
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
255
-					}
256
-				}
257
-			}
258
-
259
-			return $storage;
260
-		});
261
-
262
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
263
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
264
-
265
-		//check if we are using an object storage
266
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
267
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
268
-
269
-		// use the same order as in ObjectHomeMountProvider
270
-		if (isset($objectStoreMultibucket)) {
271
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
272
-		} elseif (isset($objectStore)) {
273
-			self::initObjectStoreRootFS($objectStore);
274
-		} else {
275
-			self::initLocalStorageRootFS();
276
-		}
277
-
278
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
279
-			\OC::$server->getEventLogger()->end('setup_fs');
280
-			return false;
281
-		}
282
-
283
-		//if we aren't logged in, there is no use to set up the filesystem
284
-		if ($user != "") {
285
-
286
-			$userDir = '/' . $user . '/files';
287
-
288
-			//jail the user into his "home" directory
289
-			\OC\Files\Filesystem::init($user, $userDir);
290
-
291
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
292
-		}
293
-		\OC::$server->getEventLogger()->end('setup_fs');
294
-		return true;
295
-	}
296
-
297
-	/**
298
-	 * check if a password is required for each public link
299
-	 *
300
-	 * @return boolean
301
-	 * @suppress PhanDeprecatedFunction
302
-	 */
303
-	public static function isPublicLinkPasswordRequired() {
304
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
305
-		return $enforcePassword === 'yes';
306
-	}
307
-
308
-	/**
309
-	 * check if sharing is disabled for the current user
310
-	 * @param IConfig $config
311
-	 * @param IGroupManager $groupManager
312
-	 * @param IUser|null $user
313
-	 * @return bool
314
-	 */
315
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
-			$excludedGroups = json_decode($groupsList);
319
-			if (is_null($excludedGroups)) {
320
-				$excludedGroups = explode(',', $groupsList);
321
-				$newValue = json_encode($excludedGroups);
322
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
-			}
324
-			$usersGroups = $groupManager->getUserGroupIds($user);
325
-			if (!empty($usersGroups)) {
326
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
327
-				// if the user is only in groups which are disabled for sharing then
328
-				// sharing is also disabled for the user
329
-				if (empty($remainingGroups)) {
330
-					return true;
331
-				}
332
-			}
333
-		}
334
-		return false;
335
-	}
336
-
337
-	/**
338
-	 * check if share API enforces a default expire date
339
-	 *
340
-	 * @return boolean
341
-	 * @suppress PhanDeprecatedFunction
342
-	 */
343
-	public static function isDefaultExpireDateEnforced() {
344
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
345
-		$enforceDefaultExpireDate = false;
346
-		if ($isDefaultExpireDateEnabled === 'yes') {
347
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
-			$enforceDefaultExpireDate = $value === 'yes';
349
-		}
350
-
351
-		return $enforceDefaultExpireDate;
352
-	}
353
-
354
-	/**
355
-	 * Get the quota of a user
356
-	 *
357
-	 * @param string $userId
358
-	 * @return float Quota bytes
359
-	 */
360
-	public static function getUserQuota($userId) {
361
-		$user = \OC::$server->getUserManager()->get($userId);
362
-		if (is_null($user)) {
363
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
-		}
365
-		$userQuota = $user->getQuota();
366
-		if($userQuota === 'none') {
367
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
-		}
369
-		return OC_Helper::computerFileSize($userQuota);
370
-	}
371
-
372
-	/**
373
-	 * copies the skeleton to the users /files
374
-	 *
375
-	 * @param String $userId
376
-	 * @param \OCP\Files\Folder $userDirectory
377
-	 * @throws \RuntimeException
378
-	 * @suppress PhanDeprecatedFunction
379
-	 */
380
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
-
382
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
384
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
385
-
386
-		if (!file_exists($skeletonDirectory)) {
387
-			$dialectStart = strpos($userLang, '_');
388
-			if ($dialectStart !== false) {
389
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
390
-			}
391
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
392
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
393
-			}
394
-			if (!file_exists($skeletonDirectory)) {
395
-				$skeletonDirectory = '';
396
-			}
397
-		}
398
-
399
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
400
-
401
-		if ($instanceId === null) {
402
-			throw new \RuntimeException('no instance id!');
403
-		}
404
-		$appdata = 'appdata_' . $instanceId;
405
-		if ($userId === $appdata) {
406
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
407
-		}
408
-
409
-		if (!empty($skeletonDirectory)) {
410
-			\OCP\Util::writeLog(
411
-				'files_skeleton',
412
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
413
-				ILogger::DEBUG
414
-			);
415
-			self::copyr($skeletonDirectory, $userDirectory);
416
-			// update the file cache
417
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
418
-		}
419
-	}
420
-
421
-	/**
422
-	 * copies a directory recursively by using streams
423
-	 *
424
-	 * @param string $source
425
-	 * @param \OCP\Files\Folder $target
426
-	 * @return void
427
-	 */
428
-	public static function copyr($source, \OCP\Files\Folder $target) {
429
-		$logger = \OC::$server->getLogger();
430
-
431
-		// Verify if folder exists
432
-		$dir = opendir($source);
433
-		if($dir === false) {
434
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
435
-			return;
436
-		}
437
-
438
-		// Copy the files
439
-		while (false !== ($file = readdir($dir))) {
440
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
441
-				if (is_dir($source . '/' . $file)) {
442
-					$child = $target->newFolder($file);
443
-					self::copyr($source . '/' . $file, $child);
444
-				} else {
445
-					$child = $target->newFile($file);
446
-					$sourceStream = fopen($source . '/' . $file, 'r');
447
-					if($sourceStream === false) {
448
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
449
-						closedir($dir);
450
-						return;
451
-					}
452
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
453
-				}
454
-			}
455
-		}
456
-		closedir($dir);
457
-	}
458
-
459
-	/**
460
-	 * @return void
461
-	 * @suppress PhanUndeclaredMethod
462
-	 */
463
-	public static function tearDownFS() {
464
-		\OC\Files\Filesystem::tearDown();
465
-		\OC::$server->getRootFolder()->clearCache();
466
-		self::$fsSetup = false;
467
-		self::$rootMounted = false;
468
-	}
469
-
470
-	/**
471
-	 * get the current installed version of ownCloud
472
-	 *
473
-	 * @return array
474
-	 */
475
-	public static function getVersion() {
476
-		OC_Util::loadVersion();
477
-		return self::$versionCache['OC_Version'];
478
-	}
479
-
480
-	/**
481
-	 * get the current installed version string of ownCloud
482
-	 *
483
-	 * @return string
484
-	 */
485
-	public static function getVersionString() {
486
-		OC_Util::loadVersion();
487
-		return self::$versionCache['OC_VersionString'];
488
-	}
489
-
490
-	/**
491
-	 * @deprecated the value is of no use anymore
492
-	 * @return string
493
-	 */
494
-	public static function getEditionString() {
495
-		return '';
496
-	}
497
-
498
-	/**
499
-	 * @description get the update channel of the current installed of ownCloud.
500
-	 * @return string
501
-	 */
502
-	public static function getChannel() {
503
-		OC_Util::loadVersion();
504
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
505
-	}
506
-
507
-	/**
508
-	 * @description get the build number of the current installed of ownCloud.
509
-	 * @return string
510
-	 */
511
-	public static function getBuild() {
512
-		OC_Util::loadVersion();
513
-		return self::$versionCache['OC_Build'];
514
-	}
515
-
516
-	/**
517
-	 * @description load the version.php into the session as cache
518
-	 * @suppress PhanUndeclaredVariable
519
-	 */
520
-	private static function loadVersion() {
521
-		if (self::$versionCache !== null) {
522
-			return;
523
-		}
524
-
525
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
526
-		require OC::$SERVERROOT . '/version.php';
527
-		/** @var $timestamp int */
528
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
529
-		/** @var $OC_Version string */
530
-		self::$versionCache['OC_Version'] = $OC_Version;
531
-		/** @var $OC_VersionString string */
532
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
533
-		/** @var $OC_Build string */
534
-		self::$versionCache['OC_Build'] = $OC_Build;
535
-
536
-		/** @var $OC_Channel string */
537
-		self::$versionCache['OC_Channel'] = $OC_Channel;
538
-	}
539
-
540
-	/**
541
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
542
-	 *
543
-	 * @param string $application application to get the files from
544
-	 * @param string $directory directory within this application (css, js, vendor, etc)
545
-	 * @param string $file the file inside of the above folder
546
-	 * @return string the path
547
-	 */
548
-	private static function generatePath($application, $directory, $file) {
549
-		if (is_null($file)) {
550
-			$file = $application;
551
-			$application = "";
552
-		}
553
-		if (!empty($application)) {
554
-			return "$application/$directory/$file";
555
-		} else {
556
-			return "$directory/$file";
557
-		}
558
-	}
559
-
560
-	/**
561
-	 * add a javascript file
562
-	 *
563
-	 * @param string $application application id
564
-	 * @param string|null $file filename
565
-	 * @param bool $prepend prepend the Script to the beginning of the list
566
-	 * @return void
567
-	 */
568
-	public static function addScript($application, $file = null, $prepend = false) {
569
-		$path = OC_Util::generatePath($application, 'js', $file);
570
-
571
-		// core js files need separate handling
572
-		if ($application !== 'core' && $file !== null) {
573
-			self::addTranslations ( $application );
574
-		}
575
-		self::addExternalResource($application, $prepend, $path, "script");
576
-	}
577
-
578
-	/**
579
-	 * add a javascript file from the vendor sub folder
580
-	 *
581
-	 * @param string $application application id
582
-	 * @param string|null $file filename
583
-	 * @param bool $prepend prepend the Script to the beginning of the list
584
-	 * @return void
585
-	 */
586
-	public static function addVendorScript($application, $file = null, $prepend = false) {
587
-		$path = OC_Util::generatePath($application, 'vendor', $file);
588
-		self::addExternalResource($application, $prepend, $path, "script");
589
-	}
590
-
591
-	/**
592
-	 * add a translation JS file
593
-	 *
594
-	 * @param string $application application id
595
-	 * @param string|null $languageCode language code, defaults to the current language
596
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
597
-	 */
598
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
599
-		if (is_null($languageCode)) {
600
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
601
-		}
602
-		if (!empty($application)) {
603
-			$path = "$application/l10n/$languageCode";
604
-		} else {
605
-			$path = "l10n/$languageCode";
606
-		}
607
-		self::addExternalResource($application, $prepend, $path, "script");
608
-	}
609
-
610
-	/**
611
-	 * add a css file
612
-	 *
613
-	 * @param string $application application id
614
-	 * @param string|null $file filename
615
-	 * @param bool $prepend prepend the Style to the beginning of the list
616
-	 * @return void
617
-	 */
618
-	public static function addStyle($application, $file = null, $prepend = false) {
619
-		$path = OC_Util::generatePath($application, 'css', $file);
620
-		self::addExternalResource($application, $prepend, $path, "style");
621
-	}
622
-
623
-	/**
624
-	 * add a css file from the vendor sub folder
625
-	 *
626
-	 * @param string $application application id
627
-	 * @param string|null $file filename
628
-	 * @param bool $prepend prepend the Style to the beginning of the list
629
-	 * @return void
630
-	 */
631
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
632
-		$path = OC_Util::generatePath($application, 'vendor', $file);
633
-		self::addExternalResource($application, $prepend, $path, "style");
634
-	}
635
-
636
-	/**
637
-	 * add an external resource css/js file
638
-	 *
639
-	 * @param string $application application id
640
-	 * @param bool $prepend prepend the file to the beginning of the list
641
-	 * @param string $path
642
-	 * @param string $type (script or style)
643
-	 * @return void
644
-	 */
645
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
646
-
647
-		if ($type === "style") {
648
-			if (!in_array($path, self::$styles)) {
649
-				if ($prepend === true) {
650
-					array_unshift ( self::$styles, $path );
651
-				} else {
652
-					self::$styles[] = $path;
653
-				}
654
-			}
655
-		} elseif ($type === "script") {
656
-			if (!in_array($path, self::$scripts)) {
657
-				if ($prepend === true) {
658
-					array_unshift ( self::$scripts, $path );
659
-				} else {
660
-					self::$scripts [] = $path;
661
-				}
662
-			}
663
-		}
664
-	}
665
-
666
-	/**
667
-	 * Add a custom element to the header
668
-	 * If $text is null then the element will be written as empty element.
669
-	 * So use "" to get a closing tag.
670
-	 * @param string $tag tag name of the element
671
-	 * @param array $attributes array of attributes for the element
672
-	 * @param string $text the text content for the element
673
-	 */
674
-	public static function addHeader($tag, $attributes, $text=null) {
675
-		self::$headers[] = array(
676
-			'tag' => $tag,
677
-			'attributes' => $attributes,
678
-			'text' => $text
679
-		);
680
-	}
681
-
682
-	/**
683
-	 * check if the current server configuration is suitable for ownCloud
684
-	 *
685
-	 * @param \OC\SystemConfig $config
686
-	 * @return array arrays with error messages and hints
687
-	 */
688
-	public static function checkServer(\OC\SystemConfig $config) {
689
-		$l = \OC::$server->getL10N('lib');
690
-		$errors = array();
691
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
692
-
693
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
694
-			// this check needs to be done every time
695
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
696
-		}
697
-
698
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
699
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
700
-			return $errors;
701
-		}
702
-
703
-		$webServerRestart = false;
704
-		$setup = new \OC\Setup(
705
-			$config,
706
-			\OC::$server->getIniWrapper(),
707
-			\OC::$server->getL10N('lib'),
708
-			\OC::$server->query(\OCP\Defaults::class),
709
-			\OC::$server->getLogger(),
710
-			\OC::$server->getSecureRandom(),
711
-			\OC::$server->query(\OC\Installer::class)
712
-		);
713
-
714
-		$urlGenerator = \OC::$server->getURLGenerator();
715
-
716
-		$availableDatabases = $setup->getSupportedDatabases();
717
-		if (empty($availableDatabases)) {
718
-			$errors[] = array(
719
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
720
-				'hint' => '' //TODO: sane hint
721
-			);
722
-			$webServerRestart = true;
723
-		}
724
-
725
-		// Check if config folder is writable.
726
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
727
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
728
-				$errors[] = array(
729
-					'error' => $l->t('Cannot write into "config" directory'),
730
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
731
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
732
-				);
733
-			}
734
-		}
735
-
736
-		// Check if there is a writable install folder.
737
-		if ($config->getValue('appstoreenabled', true)) {
738
-			if (OC_App::getInstallPath() === null
739
-				|| !is_writable(OC_App::getInstallPath())
740
-				|| !is_readable(OC_App::getInstallPath())
741
-			) {
742
-				$errors[] = array(
743
-					'error' => $l->t('Cannot write into "apps" directory'),
744
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
745
-						. ' or disabling the appstore in the config file. See %s',
746
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
747
-				);
748
-			}
749
-		}
750
-		// Create root dir.
751
-		if ($config->getValue('installed', false)) {
752
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
753
-				$success = @mkdir($CONFIG_DATADIRECTORY);
754
-				if ($success) {
755
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
756
-				} else {
757
-					$errors[] = [
758
-						'error' => $l->t('Cannot create "data" directory'),
759
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
760
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
761
-					];
762
-				}
763
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
764
-				//common hint for all file permissions error messages
765
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
766
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
767
-				$errors[] = [
768
-					'error' => 'Your data directory is not writable',
769
-					'hint' => $permissionsHint
770
-				];
771
-			} else {
772
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
773
-			}
774
-		}
775
-
776
-		if (!OC_Util::isSetLocaleWorking()) {
777
-			$errors[] = array(
778
-				'error' => $l->t('Setting locale to %s failed',
779
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
780
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
781
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
782
-			);
783
-		}
784
-
785
-		// Contains the dependencies that should be checked against
786
-		// classes = class_exists
787
-		// functions = function_exists
788
-		// defined = defined
789
-		// ini = ini_get
790
-		// If the dependency is not found the missing module name is shown to the EndUser
791
-		// When adding new checks always verify that they pass on Travis as well
792
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
793
-		$dependencies = array(
794
-			'classes' => array(
795
-				'ZipArchive' => 'zip',
796
-				'DOMDocument' => 'dom',
797
-				'XMLWriter' => 'XMLWriter',
798
-				'XMLReader' => 'XMLReader',
799
-			),
800
-			'functions' => [
801
-				'xml_parser_create' => 'libxml',
802
-				'mb_strcut' => 'mb multibyte',
803
-				'ctype_digit' => 'ctype',
804
-				'json_encode' => 'JSON',
805
-				'gd_info' => 'GD',
806
-				'gzencode' => 'zlib',
807
-				'iconv' => 'iconv',
808
-				'simplexml_load_string' => 'SimpleXML',
809
-				'hash' => 'HASH Message Digest Framework',
810
-				'curl_init' => 'cURL',
811
-				'openssl_verify' => 'OpenSSL',
812
-			],
813
-			'defined' => array(
814
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
815
-			),
816
-			'ini' => [
817
-				'default_charset' => 'UTF-8',
818
-			],
819
-		);
820
-		$missingDependencies = array();
821
-		$invalidIniSettings = [];
822
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
823
-
824
-		/**
825
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
826
-		 *        and prevents installation. Once HHVM is more compatible with our
827
-		 *        approach to check for these values we should re-enable those
828
-		 *        checks.
829
-		 */
830
-		$iniWrapper = \OC::$server->getIniWrapper();
831
-		if (!self::runningOnHhvm()) {
832
-			foreach ($dependencies['classes'] as $class => $module) {
833
-				if (!class_exists($class)) {
834
-					$missingDependencies[] = $module;
835
-				}
836
-			}
837
-			foreach ($dependencies['functions'] as $function => $module) {
838
-				if (!function_exists($function)) {
839
-					$missingDependencies[] = $module;
840
-				}
841
-			}
842
-			foreach ($dependencies['defined'] as $defined => $module) {
843
-				if (!defined($defined)) {
844
-					$missingDependencies[] = $module;
845
-				}
846
-			}
847
-			foreach ($dependencies['ini'] as $setting => $expected) {
848
-				if (is_bool($expected)) {
849
-					if ($iniWrapper->getBool($setting) !== $expected) {
850
-						$invalidIniSettings[] = [$setting, $expected];
851
-					}
852
-				}
853
-				if (is_int($expected)) {
854
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
855
-						$invalidIniSettings[] = [$setting, $expected];
856
-					}
857
-				}
858
-				if (is_string($expected)) {
859
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
860
-						$invalidIniSettings[] = [$setting, $expected];
861
-					}
862
-				}
863
-			}
864
-		}
865
-
866
-		foreach($missingDependencies as $missingDependency) {
867
-			$errors[] = array(
868
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
869
-				'hint' => $moduleHint
870
-			);
871
-			$webServerRestart = true;
872
-		}
873
-		foreach($invalidIniSettings as $setting) {
874
-			if(is_bool($setting[1])) {
875
-				$setting[1] = $setting[1] ? 'on' : 'off';
876
-			}
877
-			$errors[] = [
878
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
879
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
880
-			];
881
-			$webServerRestart = true;
882
-		}
883
-
884
-		/**
885
-		 * The mbstring.func_overload check can only be performed if the mbstring
886
-		 * module is installed as it will return null if the checking setting is
887
-		 * not available and thus a check on the boolean value fails.
888
-		 *
889
-		 * TODO: Should probably be implemented in the above generic dependency
890
-		 *       check somehow in the long-term.
891
-		 */
892
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
893
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
894
-			$errors[] = array(
895
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
896
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
897
-			);
898
-		}
899
-
900
-		if(function_exists('xml_parser_create') &&
901
-			LIBXML_LOADED_VERSION < 20700 ) {
902
-			$version = LIBXML_LOADED_VERSION;
903
-			$major = floor($version/10000);
904
-			$version -= ($major * 10000);
905
-			$minor = floor($version/100);
906
-			$version -= ($minor * 100);
907
-			$patch = $version;
908
-			$errors[] = array(
909
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
910
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
911
-			);
912
-		}
913
-
914
-		if (!self::isAnnotationsWorking()) {
915
-			$errors[] = array(
916
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
917
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
918
-			);
919
-		}
920
-
921
-		if (!\OC::$CLI && $webServerRestart) {
922
-			$errors[] = array(
923
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
924
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
925
-			);
926
-		}
927
-
928
-		$errors = array_merge($errors, self::checkDatabaseVersion());
929
-
930
-		// Cache the result of this function
931
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
932
-
933
-		return $errors;
934
-	}
935
-
936
-	/**
937
-	 * Check the database version
938
-	 *
939
-	 * @return array errors array
940
-	 */
941
-	public static function checkDatabaseVersion() {
942
-		$l = \OC::$server->getL10N('lib');
943
-		$errors = array();
944
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
945
-		if ($dbType === 'pgsql') {
946
-			// check PostgreSQL version
947
-			try {
948
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
949
-				$data = $result->fetchRow();
950
-				if (isset($data['server_version'])) {
951
-					$version = $data['server_version'];
952
-					if (version_compare($version, '9.0.0', '<')) {
953
-						$errors[] = array(
954
-							'error' => $l->t('PostgreSQL >= 9 required'),
955
-							'hint' => $l->t('Please upgrade your database version')
956
-						);
957
-					}
958
-				}
959
-			} catch (\Doctrine\DBAL\DBALException $e) {
960
-				$logger = \OC::$server->getLogger();
961
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
962
-				$logger->logException($e);
963
-			}
964
-		}
965
-		return $errors;
966
-	}
967
-
968
-	/**
969
-	 * Check for correct file permissions of data directory
970
-	 *
971
-	 * @param string $dataDirectory
972
-	 * @return array arrays with error messages and hints
973
-	 */
974
-	public static function checkDataDirectoryPermissions($dataDirectory) {
975
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
976
-			return  [];
977
-		}
978
-		$l = \OC::$server->getL10N('lib');
979
-		$errors = [];
980
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
981
-			. ' cannot be listed by other users.');
982
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
983
-		if (substr($perms, -1) !== '0') {
984
-			chmod($dataDirectory, 0770);
985
-			clearstatcache();
986
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
987
-			if ($perms[2] !== '0') {
988
-				$errors[] = [
989
-					'error' => $l->t('Your data directory is readable by other users'),
990
-					'hint' => $permissionsModHint
991
-				];
992
-			}
993
-		}
994
-		return $errors;
995
-	}
996
-
997
-	/**
998
-	 * Check that the data directory exists and is valid by
999
-	 * checking the existence of the ".ocdata" file.
1000
-	 *
1001
-	 * @param string $dataDirectory data directory path
1002
-	 * @return array errors found
1003
-	 */
1004
-	public static function checkDataDirectoryValidity($dataDirectory) {
1005
-		$l = \OC::$server->getL10N('lib');
1006
-		$errors = [];
1007
-		if ($dataDirectory[0] !== '/') {
1008
-			$errors[] = [
1009
-				'error' => $l->t('Your data directory must be an absolute path'),
1010
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1011
-			];
1012
-		}
1013
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1014
-			$errors[] = [
1015
-				'error' => $l->t('Your data directory is invalid'),
1016
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1017
-					' in the root of the data directory.')
1018
-			];
1019
-		}
1020
-		return $errors;
1021
-	}
1022
-
1023
-	/**
1024
-	 * Check if the user is logged in, redirects to home if not. With
1025
-	 * redirect URL parameter to the request URI.
1026
-	 *
1027
-	 * @return void
1028
-	 */
1029
-	public static function checkLoggedIn() {
1030
-		// Check if we are a user
1031
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1032
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1033
-						'core.login.showLoginForm',
1034
-						[
1035
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1036
-						]
1037
-					)
1038
-			);
1039
-			exit();
1040
-		}
1041
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1042
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1043
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1044
-			exit();
1045
-		}
1046
-	}
1047
-
1048
-	/**
1049
-	 * Check if the user is a admin, redirects to home if not
1050
-	 *
1051
-	 * @return void
1052
-	 */
1053
-	public static function checkAdminUser() {
1054
-		OC_Util::checkLoggedIn();
1055
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1056
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1057
-			exit();
1058
-		}
1059
-	}
1060
-
1061
-	/**
1062
-	 * Check if the user is a subadmin, redirects to home if not
1063
-	 *
1064
-	 * @return null|boolean $groups where the current user is subadmin
1065
-	 */
1066
-	public static function checkSubAdminUser() {
1067
-		OC_Util::checkLoggedIn();
1068
-		$userObject = \OC::$server->getUserSession()->getUser();
1069
-		$isSubAdmin = false;
1070
-		if($userObject !== null) {
1071
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1072
-		}
1073
-
1074
-		if (!$isSubAdmin) {
1075
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1076
-			exit();
1077
-		}
1078
-		return true;
1079
-	}
1080
-
1081
-	/**
1082
-	 * Returns the URL of the default page
1083
-	 * based on the system configuration and
1084
-	 * the apps visible for the current user
1085
-	 *
1086
-	 * @return string URL
1087
-	 * @suppress PhanDeprecatedFunction
1088
-	 */
1089
-	public static function getDefaultPageUrl() {
1090
-		$urlGenerator = \OC::$server->getURLGenerator();
1091
-		// Deny the redirect if the URL contains a @
1092
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1093
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1094
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1095
-		} else {
1096
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1097
-			if ($defaultPage) {
1098
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1099
-			} else {
1100
-				$appId = 'files';
1101
-				$config = \OC::$server->getConfig();
1102
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1103
-				// find the first app that is enabled for the current user
1104
-				foreach ($defaultApps as $defaultApp) {
1105
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1106
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1107
-						$appId = $defaultApp;
1108
-						break;
1109
-					}
1110
-				}
1111
-
1112
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1113
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1114
-				} else {
1115
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1116
-				}
1117
-			}
1118
-		}
1119
-		return $location;
1120
-	}
1121
-
1122
-	/**
1123
-	 * Redirect to the user default page
1124
-	 *
1125
-	 * @return void
1126
-	 */
1127
-	public static function redirectToDefaultPage() {
1128
-		$location = self::getDefaultPageUrl();
1129
-		header('Location: ' . $location);
1130
-		exit();
1131
-	}
1132
-
1133
-	/**
1134
-	 * get an id unique for this instance
1135
-	 *
1136
-	 * @return string
1137
-	 */
1138
-	public static function getInstanceId() {
1139
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1140
-		if (is_null($id)) {
1141
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1142
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1143
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1144
-		}
1145
-		return $id;
1146
-	}
1147
-
1148
-	/**
1149
-	 * Public function to sanitize HTML
1150
-	 *
1151
-	 * This function is used to sanitize HTML and should be applied on any
1152
-	 * string or array of strings before displaying it on a web page.
1153
-	 *
1154
-	 * @param string|array $value
1155
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1156
-	 */
1157
-	public static function sanitizeHTML($value) {
1158
-		if (is_array($value)) {
1159
-			$value = array_map(function($value) {
1160
-				return self::sanitizeHTML($value);
1161
-			}, $value);
1162
-		} else {
1163
-			// Specify encoding for PHP<5.4
1164
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1165
-		}
1166
-		return $value;
1167
-	}
1168
-
1169
-	/**
1170
-	 * Public function to encode url parameters
1171
-	 *
1172
-	 * This function is used to encode path to file before output.
1173
-	 * Encoding is done according to RFC 3986 with one exception:
1174
-	 * Character '/' is preserved as is.
1175
-	 *
1176
-	 * @param string $component part of URI to encode
1177
-	 * @return string
1178
-	 */
1179
-	public static function encodePath($component) {
1180
-		$encoded = rawurlencode($component);
1181
-		$encoded = str_replace('%2F', '/', $encoded);
1182
-		return $encoded;
1183
-	}
1184
-
1185
-
1186
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1187
-		// php dev server does not support htaccess
1188
-		if (php_sapi_name() === 'cli-server') {
1189
-			return false;
1190
-		}
1191
-
1192
-		// testdata
1193
-		$fileName = '/htaccesstest.txt';
1194
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1195
-
1196
-		// creating a test file
1197
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1198
-
1199
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1200
-			return false;
1201
-		}
1202
-
1203
-		$fp = @fopen($testFile, 'w');
1204
-		if (!$fp) {
1205
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1206
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1207
-		}
1208
-		fwrite($fp, $testContent);
1209
-		fclose($fp);
1210
-
1211
-		return $testContent;
1212
-	}
1213
-
1214
-	/**
1215
-	 * Check if the .htaccess file is working
1216
-	 * @param \OCP\IConfig $config
1217
-	 * @return bool
1218
-	 * @throws Exception
1219
-	 * @throws \OC\HintException If the test file can't get written.
1220
-	 */
1221
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1222
-
1223
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1224
-			return true;
1225
-		}
1226
-
1227
-		$testContent = $this->createHtaccessTestFile($config);
1228
-		if ($testContent === false) {
1229
-			return false;
1230
-		}
1231
-
1232
-		$fileName = '/htaccesstest.txt';
1233
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1234
-
1235
-		// accessing the file via http
1236
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1237
-		try {
1238
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1239
-		} catch (\Exception $e) {
1240
-			$content = false;
1241
-		}
1242
-
1243
-		// cleanup
1244
-		@unlink($testFile);
1245
-
1246
-		/*
69
+    public static $scripts = array();
70
+    public static $styles = array();
71
+    public static $headers = array();
72
+    private static $rootMounted = false;
73
+    private static $fsSetup = false;
74
+
75
+    /** @var array Local cache of version.php */
76
+    private static $versionCache = null;
77
+
78
+    protected static function getAppManager() {
79
+        return \OC::$server->getAppManager();
80
+    }
81
+
82
+    private static function initLocalStorageRootFS() {
83
+        // mount local file backend as root
84
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
85
+        //first set up the local "root" storage
86
+        \OC\Files\Filesystem::initMountManager();
87
+        if (!self::$rootMounted) {
88
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
89
+            self::$rootMounted = true;
90
+        }
91
+    }
92
+
93
+    /**
94
+     * mounting an object storage as the root fs will in essence remove the
95
+     * necessity of a data folder being present.
96
+     * TODO make home storage aware of this and use the object storage instead of local disk access
97
+     *
98
+     * @param array $config containing 'class' and optional 'arguments'
99
+     * @suppress PhanDeprecatedFunction
100
+     */
101
+    private static function initObjectStoreRootFS($config) {
102
+        // check misconfiguration
103
+        if (empty($config['class'])) {
104
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
105
+        }
106
+        if (!isset($config['arguments'])) {
107
+            $config['arguments'] = array();
108
+        }
109
+
110
+        // instantiate object store implementation
111
+        $name = $config['class'];
112
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
113
+            $segments = explode('\\', $name);
114
+            OC_App::loadApp(strtolower($segments[1]));
115
+        }
116
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
117
+        // mount with plain / root object store implementation
118
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
119
+
120
+        // mount object storage as root
121
+        \OC\Files\Filesystem::initMountManager();
122
+        if (!self::$rootMounted) {
123
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
124
+            self::$rootMounted = true;
125
+        }
126
+    }
127
+
128
+    /**
129
+     * mounting an object storage as the root fs will in essence remove the
130
+     * necessity of a data folder being present.
131
+     *
132
+     * @param array $config containing 'class' and optional 'arguments'
133
+     * @suppress PhanDeprecatedFunction
134
+     */
135
+    private static function initObjectStoreMultibucketRootFS($config) {
136
+        // check misconfiguration
137
+        if (empty($config['class'])) {
138
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
139
+        }
140
+        if (!isset($config['arguments'])) {
141
+            $config['arguments'] = array();
142
+        }
143
+
144
+        // instantiate object store implementation
145
+        $name = $config['class'];
146
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
147
+            $segments = explode('\\', $name);
148
+            OC_App::loadApp(strtolower($segments[1]));
149
+        }
150
+
151
+        if (!isset($config['arguments']['bucket'])) {
152
+            $config['arguments']['bucket'] = '';
153
+        }
154
+        // put the root FS always in first bucket for multibucket configuration
155
+        $config['arguments']['bucket'] .= '0';
156
+
157
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
158
+        // mount with plain / root object store implementation
159
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
160
+
161
+        // mount object storage as root
162
+        \OC\Files\Filesystem::initMountManager();
163
+        if (!self::$rootMounted) {
164
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
165
+            self::$rootMounted = true;
166
+        }
167
+    }
168
+
169
+    /**
170
+     * Can be set up
171
+     *
172
+     * @param string $user
173
+     * @return boolean
174
+     * @description configure the initial filesystem based on the configuration
175
+     * @suppress PhanDeprecatedFunction
176
+     * @suppress PhanAccessMethodInternal
177
+     */
178
+    public static function setupFS($user = '') {
179
+        //setting up the filesystem twice can only lead to trouble
180
+        if (self::$fsSetup) {
181
+            return false;
182
+        }
183
+
184
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
185
+
186
+        // If we are not forced to load a specific user we load the one that is logged in
187
+        if ($user === null) {
188
+            $user = '';
189
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
190
+            $user = OC_User::getUser();
191
+        }
192
+
193
+        // load all filesystem apps before, so no setup-hook gets lost
194
+        OC_App::loadApps(array('filesystem'));
195
+
196
+        // the filesystem will finish when $user is not empty,
197
+        // mark fs setup here to avoid doing the setup from loading
198
+        // OC_Filesystem
199
+        if ($user != '') {
200
+            self::$fsSetup = true;
201
+        }
202
+
203
+        \OC\Files\Filesystem::initMountManager();
204
+
205
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
206
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
207
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
208
+                /** @var \OC\Files\Storage\Common $storage */
209
+                $storage->setMountOptions($mount->getOptions());
210
+            }
211
+            return $storage;
212
+        });
213
+
214
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
215
+            if (!$mount->getOption('enable_sharing', true)) {
216
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
217
+                    'storage' => $storage,
218
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
219
+                ]);
220
+            }
221
+            return $storage;
222
+        });
223
+
224
+        // install storage availability wrapper, before most other wrappers
225
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
226
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
227
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
228
+            }
229
+            return $storage;
230
+        });
231
+
232
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
233
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
235
+            }
236
+            return $storage;
237
+        });
238
+
239
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
240
+            // set up quota for home storages, even for other users
241
+            // which can happen when using sharing
242
+
243
+            /**
244
+             * @var \OC\Files\Storage\Storage $storage
245
+             */
246
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
247
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
248
+            ) {
249
+                /** @var \OC\Files\Storage\Home $storage */
250
+                if (is_object($storage->getUser())) {
251
+                    $user = $storage->getUser()->getUID();
252
+                    $quota = OC_Util::getUserQuota($user);
253
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
254
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
255
+                    }
256
+                }
257
+            }
258
+
259
+            return $storage;
260
+        });
261
+
262
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
263
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
264
+
265
+        //check if we are using an object storage
266
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
267
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
268
+
269
+        // use the same order as in ObjectHomeMountProvider
270
+        if (isset($objectStoreMultibucket)) {
271
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
272
+        } elseif (isset($objectStore)) {
273
+            self::initObjectStoreRootFS($objectStore);
274
+        } else {
275
+            self::initLocalStorageRootFS();
276
+        }
277
+
278
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
279
+            \OC::$server->getEventLogger()->end('setup_fs');
280
+            return false;
281
+        }
282
+
283
+        //if we aren't logged in, there is no use to set up the filesystem
284
+        if ($user != "") {
285
+
286
+            $userDir = '/' . $user . '/files';
287
+
288
+            //jail the user into his "home" directory
289
+            \OC\Files\Filesystem::init($user, $userDir);
290
+
291
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
292
+        }
293
+        \OC::$server->getEventLogger()->end('setup_fs');
294
+        return true;
295
+    }
296
+
297
+    /**
298
+     * check if a password is required for each public link
299
+     *
300
+     * @return boolean
301
+     * @suppress PhanDeprecatedFunction
302
+     */
303
+    public static function isPublicLinkPasswordRequired() {
304
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
305
+        return $enforcePassword === 'yes';
306
+    }
307
+
308
+    /**
309
+     * check if sharing is disabled for the current user
310
+     * @param IConfig $config
311
+     * @param IGroupManager $groupManager
312
+     * @param IUser|null $user
313
+     * @return bool
314
+     */
315
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
+            $excludedGroups = json_decode($groupsList);
319
+            if (is_null($excludedGroups)) {
320
+                $excludedGroups = explode(',', $groupsList);
321
+                $newValue = json_encode($excludedGroups);
322
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
+            }
324
+            $usersGroups = $groupManager->getUserGroupIds($user);
325
+            if (!empty($usersGroups)) {
326
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
327
+                // if the user is only in groups which are disabled for sharing then
328
+                // sharing is also disabled for the user
329
+                if (empty($remainingGroups)) {
330
+                    return true;
331
+                }
332
+            }
333
+        }
334
+        return false;
335
+    }
336
+
337
+    /**
338
+     * check if share API enforces a default expire date
339
+     *
340
+     * @return boolean
341
+     * @suppress PhanDeprecatedFunction
342
+     */
343
+    public static function isDefaultExpireDateEnforced() {
344
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
345
+        $enforceDefaultExpireDate = false;
346
+        if ($isDefaultExpireDateEnabled === 'yes') {
347
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
+            $enforceDefaultExpireDate = $value === 'yes';
349
+        }
350
+
351
+        return $enforceDefaultExpireDate;
352
+    }
353
+
354
+    /**
355
+     * Get the quota of a user
356
+     *
357
+     * @param string $userId
358
+     * @return float Quota bytes
359
+     */
360
+    public static function getUserQuota($userId) {
361
+        $user = \OC::$server->getUserManager()->get($userId);
362
+        if (is_null($user)) {
363
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
+        }
365
+        $userQuota = $user->getQuota();
366
+        if($userQuota === 'none') {
367
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
+        }
369
+        return OC_Helper::computerFileSize($userQuota);
370
+    }
371
+
372
+    /**
373
+     * copies the skeleton to the users /files
374
+     *
375
+     * @param String $userId
376
+     * @param \OCP\Files\Folder $userDirectory
377
+     * @throws \RuntimeException
378
+     * @suppress PhanDeprecatedFunction
379
+     */
380
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
+
382
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
384
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
385
+
386
+        if (!file_exists($skeletonDirectory)) {
387
+            $dialectStart = strpos($userLang, '_');
388
+            if ($dialectStart !== false) {
389
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
390
+            }
391
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
392
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
393
+            }
394
+            if (!file_exists($skeletonDirectory)) {
395
+                $skeletonDirectory = '';
396
+            }
397
+        }
398
+
399
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
400
+
401
+        if ($instanceId === null) {
402
+            throw new \RuntimeException('no instance id!');
403
+        }
404
+        $appdata = 'appdata_' . $instanceId;
405
+        if ($userId === $appdata) {
406
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
407
+        }
408
+
409
+        if (!empty($skeletonDirectory)) {
410
+            \OCP\Util::writeLog(
411
+                'files_skeleton',
412
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
413
+                ILogger::DEBUG
414
+            );
415
+            self::copyr($skeletonDirectory, $userDirectory);
416
+            // update the file cache
417
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
418
+        }
419
+    }
420
+
421
+    /**
422
+     * copies a directory recursively by using streams
423
+     *
424
+     * @param string $source
425
+     * @param \OCP\Files\Folder $target
426
+     * @return void
427
+     */
428
+    public static function copyr($source, \OCP\Files\Folder $target) {
429
+        $logger = \OC::$server->getLogger();
430
+
431
+        // Verify if folder exists
432
+        $dir = opendir($source);
433
+        if($dir === false) {
434
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
435
+            return;
436
+        }
437
+
438
+        // Copy the files
439
+        while (false !== ($file = readdir($dir))) {
440
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
441
+                if (is_dir($source . '/' . $file)) {
442
+                    $child = $target->newFolder($file);
443
+                    self::copyr($source . '/' . $file, $child);
444
+                } else {
445
+                    $child = $target->newFile($file);
446
+                    $sourceStream = fopen($source . '/' . $file, 'r');
447
+                    if($sourceStream === false) {
448
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
449
+                        closedir($dir);
450
+                        return;
451
+                    }
452
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
453
+                }
454
+            }
455
+        }
456
+        closedir($dir);
457
+    }
458
+
459
+    /**
460
+     * @return void
461
+     * @suppress PhanUndeclaredMethod
462
+     */
463
+    public static function tearDownFS() {
464
+        \OC\Files\Filesystem::tearDown();
465
+        \OC::$server->getRootFolder()->clearCache();
466
+        self::$fsSetup = false;
467
+        self::$rootMounted = false;
468
+    }
469
+
470
+    /**
471
+     * get the current installed version of ownCloud
472
+     *
473
+     * @return array
474
+     */
475
+    public static function getVersion() {
476
+        OC_Util::loadVersion();
477
+        return self::$versionCache['OC_Version'];
478
+    }
479
+
480
+    /**
481
+     * get the current installed version string of ownCloud
482
+     *
483
+     * @return string
484
+     */
485
+    public static function getVersionString() {
486
+        OC_Util::loadVersion();
487
+        return self::$versionCache['OC_VersionString'];
488
+    }
489
+
490
+    /**
491
+     * @deprecated the value is of no use anymore
492
+     * @return string
493
+     */
494
+    public static function getEditionString() {
495
+        return '';
496
+    }
497
+
498
+    /**
499
+     * @description get the update channel of the current installed of ownCloud.
500
+     * @return string
501
+     */
502
+    public static function getChannel() {
503
+        OC_Util::loadVersion();
504
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
505
+    }
506
+
507
+    /**
508
+     * @description get the build number of the current installed of ownCloud.
509
+     * @return string
510
+     */
511
+    public static function getBuild() {
512
+        OC_Util::loadVersion();
513
+        return self::$versionCache['OC_Build'];
514
+    }
515
+
516
+    /**
517
+     * @description load the version.php into the session as cache
518
+     * @suppress PhanUndeclaredVariable
519
+     */
520
+    private static function loadVersion() {
521
+        if (self::$versionCache !== null) {
522
+            return;
523
+        }
524
+
525
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
526
+        require OC::$SERVERROOT . '/version.php';
527
+        /** @var $timestamp int */
528
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
529
+        /** @var $OC_Version string */
530
+        self::$versionCache['OC_Version'] = $OC_Version;
531
+        /** @var $OC_VersionString string */
532
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
533
+        /** @var $OC_Build string */
534
+        self::$versionCache['OC_Build'] = $OC_Build;
535
+
536
+        /** @var $OC_Channel string */
537
+        self::$versionCache['OC_Channel'] = $OC_Channel;
538
+    }
539
+
540
+    /**
541
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
542
+     *
543
+     * @param string $application application to get the files from
544
+     * @param string $directory directory within this application (css, js, vendor, etc)
545
+     * @param string $file the file inside of the above folder
546
+     * @return string the path
547
+     */
548
+    private static function generatePath($application, $directory, $file) {
549
+        if (is_null($file)) {
550
+            $file = $application;
551
+            $application = "";
552
+        }
553
+        if (!empty($application)) {
554
+            return "$application/$directory/$file";
555
+        } else {
556
+            return "$directory/$file";
557
+        }
558
+    }
559
+
560
+    /**
561
+     * add a javascript file
562
+     *
563
+     * @param string $application application id
564
+     * @param string|null $file filename
565
+     * @param bool $prepend prepend the Script to the beginning of the list
566
+     * @return void
567
+     */
568
+    public static function addScript($application, $file = null, $prepend = false) {
569
+        $path = OC_Util::generatePath($application, 'js', $file);
570
+
571
+        // core js files need separate handling
572
+        if ($application !== 'core' && $file !== null) {
573
+            self::addTranslations ( $application );
574
+        }
575
+        self::addExternalResource($application, $prepend, $path, "script");
576
+    }
577
+
578
+    /**
579
+     * add a javascript file from the vendor sub folder
580
+     *
581
+     * @param string $application application id
582
+     * @param string|null $file filename
583
+     * @param bool $prepend prepend the Script to the beginning of the list
584
+     * @return void
585
+     */
586
+    public static function addVendorScript($application, $file = null, $prepend = false) {
587
+        $path = OC_Util::generatePath($application, 'vendor', $file);
588
+        self::addExternalResource($application, $prepend, $path, "script");
589
+    }
590
+
591
+    /**
592
+     * add a translation JS file
593
+     *
594
+     * @param string $application application id
595
+     * @param string|null $languageCode language code, defaults to the current language
596
+     * @param bool|null $prepend prepend the Script to the beginning of the list
597
+     */
598
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
599
+        if (is_null($languageCode)) {
600
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
601
+        }
602
+        if (!empty($application)) {
603
+            $path = "$application/l10n/$languageCode";
604
+        } else {
605
+            $path = "l10n/$languageCode";
606
+        }
607
+        self::addExternalResource($application, $prepend, $path, "script");
608
+    }
609
+
610
+    /**
611
+     * add a css file
612
+     *
613
+     * @param string $application application id
614
+     * @param string|null $file filename
615
+     * @param bool $prepend prepend the Style to the beginning of the list
616
+     * @return void
617
+     */
618
+    public static function addStyle($application, $file = null, $prepend = false) {
619
+        $path = OC_Util::generatePath($application, 'css', $file);
620
+        self::addExternalResource($application, $prepend, $path, "style");
621
+    }
622
+
623
+    /**
624
+     * add a css file from the vendor sub folder
625
+     *
626
+     * @param string $application application id
627
+     * @param string|null $file filename
628
+     * @param bool $prepend prepend the Style to the beginning of the list
629
+     * @return void
630
+     */
631
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
632
+        $path = OC_Util::generatePath($application, 'vendor', $file);
633
+        self::addExternalResource($application, $prepend, $path, "style");
634
+    }
635
+
636
+    /**
637
+     * add an external resource css/js file
638
+     *
639
+     * @param string $application application id
640
+     * @param bool $prepend prepend the file to the beginning of the list
641
+     * @param string $path
642
+     * @param string $type (script or style)
643
+     * @return void
644
+     */
645
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
646
+
647
+        if ($type === "style") {
648
+            if (!in_array($path, self::$styles)) {
649
+                if ($prepend === true) {
650
+                    array_unshift ( self::$styles, $path );
651
+                } else {
652
+                    self::$styles[] = $path;
653
+                }
654
+            }
655
+        } elseif ($type === "script") {
656
+            if (!in_array($path, self::$scripts)) {
657
+                if ($prepend === true) {
658
+                    array_unshift ( self::$scripts, $path );
659
+                } else {
660
+                    self::$scripts [] = $path;
661
+                }
662
+            }
663
+        }
664
+    }
665
+
666
+    /**
667
+     * Add a custom element to the header
668
+     * If $text is null then the element will be written as empty element.
669
+     * So use "" to get a closing tag.
670
+     * @param string $tag tag name of the element
671
+     * @param array $attributes array of attributes for the element
672
+     * @param string $text the text content for the element
673
+     */
674
+    public static function addHeader($tag, $attributes, $text=null) {
675
+        self::$headers[] = array(
676
+            'tag' => $tag,
677
+            'attributes' => $attributes,
678
+            'text' => $text
679
+        );
680
+    }
681
+
682
+    /**
683
+     * check if the current server configuration is suitable for ownCloud
684
+     *
685
+     * @param \OC\SystemConfig $config
686
+     * @return array arrays with error messages and hints
687
+     */
688
+    public static function checkServer(\OC\SystemConfig $config) {
689
+        $l = \OC::$server->getL10N('lib');
690
+        $errors = array();
691
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
692
+
693
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
694
+            // this check needs to be done every time
695
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
696
+        }
697
+
698
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
699
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
700
+            return $errors;
701
+        }
702
+
703
+        $webServerRestart = false;
704
+        $setup = new \OC\Setup(
705
+            $config,
706
+            \OC::$server->getIniWrapper(),
707
+            \OC::$server->getL10N('lib'),
708
+            \OC::$server->query(\OCP\Defaults::class),
709
+            \OC::$server->getLogger(),
710
+            \OC::$server->getSecureRandom(),
711
+            \OC::$server->query(\OC\Installer::class)
712
+        );
713
+
714
+        $urlGenerator = \OC::$server->getURLGenerator();
715
+
716
+        $availableDatabases = $setup->getSupportedDatabases();
717
+        if (empty($availableDatabases)) {
718
+            $errors[] = array(
719
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
720
+                'hint' => '' //TODO: sane hint
721
+            );
722
+            $webServerRestart = true;
723
+        }
724
+
725
+        // Check if config folder is writable.
726
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
727
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
728
+                $errors[] = array(
729
+                    'error' => $l->t('Cannot write into "config" directory'),
730
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
731
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
732
+                );
733
+            }
734
+        }
735
+
736
+        // Check if there is a writable install folder.
737
+        if ($config->getValue('appstoreenabled', true)) {
738
+            if (OC_App::getInstallPath() === null
739
+                || !is_writable(OC_App::getInstallPath())
740
+                || !is_readable(OC_App::getInstallPath())
741
+            ) {
742
+                $errors[] = array(
743
+                    'error' => $l->t('Cannot write into "apps" directory'),
744
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
745
+                        . ' or disabling the appstore in the config file. See %s',
746
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
747
+                );
748
+            }
749
+        }
750
+        // Create root dir.
751
+        if ($config->getValue('installed', false)) {
752
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
753
+                $success = @mkdir($CONFIG_DATADIRECTORY);
754
+                if ($success) {
755
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
756
+                } else {
757
+                    $errors[] = [
758
+                        'error' => $l->t('Cannot create "data" directory'),
759
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
760
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
761
+                    ];
762
+                }
763
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
764
+                //common hint for all file permissions error messages
765
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
766
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
767
+                $errors[] = [
768
+                    'error' => 'Your data directory is not writable',
769
+                    'hint' => $permissionsHint
770
+                ];
771
+            } else {
772
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
773
+            }
774
+        }
775
+
776
+        if (!OC_Util::isSetLocaleWorking()) {
777
+            $errors[] = array(
778
+                'error' => $l->t('Setting locale to %s failed',
779
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
780
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
781
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
782
+            );
783
+        }
784
+
785
+        // Contains the dependencies that should be checked against
786
+        // classes = class_exists
787
+        // functions = function_exists
788
+        // defined = defined
789
+        // ini = ini_get
790
+        // If the dependency is not found the missing module name is shown to the EndUser
791
+        // When adding new checks always verify that they pass on Travis as well
792
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
793
+        $dependencies = array(
794
+            'classes' => array(
795
+                'ZipArchive' => 'zip',
796
+                'DOMDocument' => 'dom',
797
+                'XMLWriter' => 'XMLWriter',
798
+                'XMLReader' => 'XMLReader',
799
+            ),
800
+            'functions' => [
801
+                'xml_parser_create' => 'libxml',
802
+                'mb_strcut' => 'mb multibyte',
803
+                'ctype_digit' => 'ctype',
804
+                'json_encode' => 'JSON',
805
+                'gd_info' => 'GD',
806
+                'gzencode' => 'zlib',
807
+                'iconv' => 'iconv',
808
+                'simplexml_load_string' => 'SimpleXML',
809
+                'hash' => 'HASH Message Digest Framework',
810
+                'curl_init' => 'cURL',
811
+                'openssl_verify' => 'OpenSSL',
812
+            ],
813
+            'defined' => array(
814
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
815
+            ),
816
+            'ini' => [
817
+                'default_charset' => 'UTF-8',
818
+            ],
819
+        );
820
+        $missingDependencies = array();
821
+        $invalidIniSettings = [];
822
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
823
+
824
+        /**
825
+         * FIXME: The dependency check does not work properly on HHVM on the moment
826
+         *        and prevents installation. Once HHVM is more compatible with our
827
+         *        approach to check for these values we should re-enable those
828
+         *        checks.
829
+         */
830
+        $iniWrapper = \OC::$server->getIniWrapper();
831
+        if (!self::runningOnHhvm()) {
832
+            foreach ($dependencies['classes'] as $class => $module) {
833
+                if (!class_exists($class)) {
834
+                    $missingDependencies[] = $module;
835
+                }
836
+            }
837
+            foreach ($dependencies['functions'] as $function => $module) {
838
+                if (!function_exists($function)) {
839
+                    $missingDependencies[] = $module;
840
+                }
841
+            }
842
+            foreach ($dependencies['defined'] as $defined => $module) {
843
+                if (!defined($defined)) {
844
+                    $missingDependencies[] = $module;
845
+                }
846
+            }
847
+            foreach ($dependencies['ini'] as $setting => $expected) {
848
+                if (is_bool($expected)) {
849
+                    if ($iniWrapper->getBool($setting) !== $expected) {
850
+                        $invalidIniSettings[] = [$setting, $expected];
851
+                    }
852
+                }
853
+                if (is_int($expected)) {
854
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
855
+                        $invalidIniSettings[] = [$setting, $expected];
856
+                    }
857
+                }
858
+                if (is_string($expected)) {
859
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
860
+                        $invalidIniSettings[] = [$setting, $expected];
861
+                    }
862
+                }
863
+            }
864
+        }
865
+
866
+        foreach($missingDependencies as $missingDependency) {
867
+            $errors[] = array(
868
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
869
+                'hint' => $moduleHint
870
+            );
871
+            $webServerRestart = true;
872
+        }
873
+        foreach($invalidIniSettings as $setting) {
874
+            if(is_bool($setting[1])) {
875
+                $setting[1] = $setting[1] ? 'on' : 'off';
876
+            }
877
+            $errors[] = [
878
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
879
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
880
+            ];
881
+            $webServerRestart = true;
882
+        }
883
+
884
+        /**
885
+         * The mbstring.func_overload check can only be performed if the mbstring
886
+         * module is installed as it will return null if the checking setting is
887
+         * not available and thus a check on the boolean value fails.
888
+         *
889
+         * TODO: Should probably be implemented in the above generic dependency
890
+         *       check somehow in the long-term.
891
+         */
892
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
893
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
894
+            $errors[] = array(
895
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
896
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
897
+            );
898
+        }
899
+
900
+        if(function_exists('xml_parser_create') &&
901
+            LIBXML_LOADED_VERSION < 20700 ) {
902
+            $version = LIBXML_LOADED_VERSION;
903
+            $major = floor($version/10000);
904
+            $version -= ($major * 10000);
905
+            $minor = floor($version/100);
906
+            $version -= ($minor * 100);
907
+            $patch = $version;
908
+            $errors[] = array(
909
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
910
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
911
+            );
912
+        }
913
+
914
+        if (!self::isAnnotationsWorking()) {
915
+            $errors[] = array(
916
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
917
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
918
+            );
919
+        }
920
+
921
+        if (!\OC::$CLI && $webServerRestart) {
922
+            $errors[] = array(
923
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
924
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
925
+            );
926
+        }
927
+
928
+        $errors = array_merge($errors, self::checkDatabaseVersion());
929
+
930
+        // Cache the result of this function
931
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
932
+
933
+        return $errors;
934
+    }
935
+
936
+    /**
937
+     * Check the database version
938
+     *
939
+     * @return array errors array
940
+     */
941
+    public static function checkDatabaseVersion() {
942
+        $l = \OC::$server->getL10N('lib');
943
+        $errors = array();
944
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
945
+        if ($dbType === 'pgsql') {
946
+            // check PostgreSQL version
947
+            try {
948
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
949
+                $data = $result->fetchRow();
950
+                if (isset($data['server_version'])) {
951
+                    $version = $data['server_version'];
952
+                    if (version_compare($version, '9.0.0', '<')) {
953
+                        $errors[] = array(
954
+                            'error' => $l->t('PostgreSQL >= 9 required'),
955
+                            'hint' => $l->t('Please upgrade your database version')
956
+                        );
957
+                    }
958
+                }
959
+            } catch (\Doctrine\DBAL\DBALException $e) {
960
+                $logger = \OC::$server->getLogger();
961
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
962
+                $logger->logException($e);
963
+            }
964
+        }
965
+        return $errors;
966
+    }
967
+
968
+    /**
969
+     * Check for correct file permissions of data directory
970
+     *
971
+     * @param string $dataDirectory
972
+     * @return array arrays with error messages and hints
973
+     */
974
+    public static function checkDataDirectoryPermissions($dataDirectory) {
975
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
976
+            return  [];
977
+        }
978
+        $l = \OC::$server->getL10N('lib');
979
+        $errors = [];
980
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
981
+            . ' cannot be listed by other users.');
982
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
983
+        if (substr($perms, -1) !== '0') {
984
+            chmod($dataDirectory, 0770);
985
+            clearstatcache();
986
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
987
+            if ($perms[2] !== '0') {
988
+                $errors[] = [
989
+                    'error' => $l->t('Your data directory is readable by other users'),
990
+                    'hint' => $permissionsModHint
991
+                ];
992
+            }
993
+        }
994
+        return $errors;
995
+    }
996
+
997
+    /**
998
+     * Check that the data directory exists and is valid by
999
+     * checking the existence of the ".ocdata" file.
1000
+     *
1001
+     * @param string $dataDirectory data directory path
1002
+     * @return array errors found
1003
+     */
1004
+    public static function checkDataDirectoryValidity($dataDirectory) {
1005
+        $l = \OC::$server->getL10N('lib');
1006
+        $errors = [];
1007
+        if ($dataDirectory[0] !== '/') {
1008
+            $errors[] = [
1009
+                'error' => $l->t('Your data directory must be an absolute path'),
1010
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1011
+            ];
1012
+        }
1013
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1014
+            $errors[] = [
1015
+                'error' => $l->t('Your data directory is invalid'),
1016
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1017
+                    ' in the root of the data directory.')
1018
+            ];
1019
+        }
1020
+        return $errors;
1021
+    }
1022
+
1023
+    /**
1024
+     * Check if the user is logged in, redirects to home if not. With
1025
+     * redirect URL parameter to the request URI.
1026
+     *
1027
+     * @return void
1028
+     */
1029
+    public static function checkLoggedIn() {
1030
+        // Check if we are a user
1031
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1032
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1033
+                        'core.login.showLoginForm',
1034
+                        [
1035
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1036
+                        ]
1037
+                    )
1038
+            );
1039
+            exit();
1040
+        }
1041
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1042
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1043
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1044
+            exit();
1045
+        }
1046
+    }
1047
+
1048
+    /**
1049
+     * Check if the user is a admin, redirects to home if not
1050
+     *
1051
+     * @return void
1052
+     */
1053
+    public static function checkAdminUser() {
1054
+        OC_Util::checkLoggedIn();
1055
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1056
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1057
+            exit();
1058
+        }
1059
+    }
1060
+
1061
+    /**
1062
+     * Check if the user is a subadmin, redirects to home if not
1063
+     *
1064
+     * @return null|boolean $groups where the current user is subadmin
1065
+     */
1066
+    public static function checkSubAdminUser() {
1067
+        OC_Util::checkLoggedIn();
1068
+        $userObject = \OC::$server->getUserSession()->getUser();
1069
+        $isSubAdmin = false;
1070
+        if($userObject !== null) {
1071
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1072
+        }
1073
+
1074
+        if (!$isSubAdmin) {
1075
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1076
+            exit();
1077
+        }
1078
+        return true;
1079
+    }
1080
+
1081
+    /**
1082
+     * Returns the URL of the default page
1083
+     * based on the system configuration and
1084
+     * the apps visible for the current user
1085
+     *
1086
+     * @return string URL
1087
+     * @suppress PhanDeprecatedFunction
1088
+     */
1089
+    public static function getDefaultPageUrl() {
1090
+        $urlGenerator = \OC::$server->getURLGenerator();
1091
+        // Deny the redirect if the URL contains a @
1092
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1093
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1094
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1095
+        } else {
1096
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1097
+            if ($defaultPage) {
1098
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1099
+            } else {
1100
+                $appId = 'files';
1101
+                $config = \OC::$server->getConfig();
1102
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1103
+                // find the first app that is enabled for the current user
1104
+                foreach ($defaultApps as $defaultApp) {
1105
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1106
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1107
+                        $appId = $defaultApp;
1108
+                        break;
1109
+                    }
1110
+                }
1111
+
1112
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1113
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1114
+                } else {
1115
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1116
+                }
1117
+            }
1118
+        }
1119
+        return $location;
1120
+    }
1121
+
1122
+    /**
1123
+     * Redirect to the user default page
1124
+     *
1125
+     * @return void
1126
+     */
1127
+    public static function redirectToDefaultPage() {
1128
+        $location = self::getDefaultPageUrl();
1129
+        header('Location: ' . $location);
1130
+        exit();
1131
+    }
1132
+
1133
+    /**
1134
+     * get an id unique for this instance
1135
+     *
1136
+     * @return string
1137
+     */
1138
+    public static function getInstanceId() {
1139
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1140
+        if (is_null($id)) {
1141
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1142
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1143
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1144
+        }
1145
+        return $id;
1146
+    }
1147
+
1148
+    /**
1149
+     * Public function to sanitize HTML
1150
+     *
1151
+     * This function is used to sanitize HTML and should be applied on any
1152
+     * string or array of strings before displaying it on a web page.
1153
+     *
1154
+     * @param string|array $value
1155
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1156
+     */
1157
+    public static function sanitizeHTML($value) {
1158
+        if (is_array($value)) {
1159
+            $value = array_map(function($value) {
1160
+                return self::sanitizeHTML($value);
1161
+            }, $value);
1162
+        } else {
1163
+            // Specify encoding for PHP<5.4
1164
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1165
+        }
1166
+        return $value;
1167
+    }
1168
+
1169
+    /**
1170
+     * Public function to encode url parameters
1171
+     *
1172
+     * This function is used to encode path to file before output.
1173
+     * Encoding is done according to RFC 3986 with one exception:
1174
+     * Character '/' is preserved as is.
1175
+     *
1176
+     * @param string $component part of URI to encode
1177
+     * @return string
1178
+     */
1179
+    public static function encodePath($component) {
1180
+        $encoded = rawurlencode($component);
1181
+        $encoded = str_replace('%2F', '/', $encoded);
1182
+        return $encoded;
1183
+    }
1184
+
1185
+
1186
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1187
+        // php dev server does not support htaccess
1188
+        if (php_sapi_name() === 'cli-server') {
1189
+            return false;
1190
+        }
1191
+
1192
+        // testdata
1193
+        $fileName = '/htaccesstest.txt';
1194
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1195
+
1196
+        // creating a test file
1197
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1198
+
1199
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1200
+            return false;
1201
+        }
1202
+
1203
+        $fp = @fopen($testFile, 'w');
1204
+        if (!$fp) {
1205
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1206
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1207
+        }
1208
+        fwrite($fp, $testContent);
1209
+        fclose($fp);
1210
+
1211
+        return $testContent;
1212
+    }
1213
+
1214
+    /**
1215
+     * Check if the .htaccess file is working
1216
+     * @param \OCP\IConfig $config
1217
+     * @return bool
1218
+     * @throws Exception
1219
+     * @throws \OC\HintException If the test file can't get written.
1220
+     */
1221
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1222
+
1223
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1224
+            return true;
1225
+        }
1226
+
1227
+        $testContent = $this->createHtaccessTestFile($config);
1228
+        if ($testContent === false) {
1229
+            return false;
1230
+        }
1231
+
1232
+        $fileName = '/htaccesstest.txt';
1233
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1234
+
1235
+        // accessing the file via http
1236
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1237
+        try {
1238
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1239
+        } catch (\Exception $e) {
1240
+            $content = false;
1241
+        }
1242
+
1243
+        // cleanup
1244
+        @unlink($testFile);
1245
+
1246
+        /*
1247 1247
 		 * If the content is not equal to test content our .htaccess
1248 1248
 		 * is working as required
1249 1249
 		 */
1250
-		return $content !== $testContent;
1251
-	}
1252
-
1253
-	/**
1254
-	 * Check if the setlocal call does not work. This can happen if the right
1255
-	 * local packages are not available on the server.
1256
-	 *
1257
-	 * @return bool
1258
-	 */
1259
-	public static function isSetLocaleWorking() {
1260
-		\Patchwork\Utf8\Bootup::initLocale();
1261
-		if ('' === basename('§')) {
1262
-			return false;
1263
-		}
1264
-		return true;
1265
-	}
1266
-
1267
-	/**
1268
-	 * Check if it's possible to get the inline annotations
1269
-	 *
1270
-	 * @return bool
1271
-	 */
1272
-	public static function isAnnotationsWorking() {
1273
-		$reflection = new \ReflectionMethod(__METHOD__);
1274
-		$docs = $reflection->getDocComment();
1275
-
1276
-		return (is_string($docs) && strlen($docs) > 50);
1277
-	}
1278
-
1279
-	/**
1280
-	 * Check if the PHP module fileinfo is loaded.
1281
-	 *
1282
-	 * @return bool
1283
-	 */
1284
-	public static function fileInfoLoaded() {
1285
-		return function_exists('finfo_open');
1286
-	}
1287
-
1288
-	/**
1289
-	 * clear all levels of output buffering
1290
-	 *
1291
-	 * @return void
1292
-	 */
1293
-	public static function obEnd() {
1294
-		while (ob_get_level()) {
1295
-			ob_end_clean();
1296
-		}
1297
-	}
1298
-
1299
-	/**
1300
-	 * Checks whether the server is running on Mac OS X
1301
-	 *
1302
-	 * @return bool true if running on Mac OS X, false otherwise
1303
-	 */
1304
-	public static function runningOnMac() {
1305
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1306
-	}
1307
-
1308
-	/**
1309
-	 * Checks whether server is running on HHVM
1310
-	 *
1311
-	 * @return bool True if running on HHVM, false otherwise
1312
-	 */
1313
-	public static function runningOnHhvm() {
1314
-		return defined('HHVM_VERSION');
1315
-	}
1316
-
1317
-	/**
1318
-	 * Handles the case that there may not be a theme, then check if a "default"
1319
-	 * theme exists and take that one
1320
-	 *
1321
-	 * @return string the theme
1322
-	 */
1323
-	public static function getTheme() {
1324
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1325
-
1326
-		if ($theme === '') {
1327
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1328
-				$theme = 'default';
1329
-			}
1330
-		}
1331
-
1332
-		return $theme;
1333
-	}
1334
-
1335
-	/**
1336
-	 * Clear a single file from the opcode cache
1337
-	 * This is useful for writing to the config file
1338
-	 * in case the opcode cache does not re-validate files
1339
-	 * Returns true if successful, false if unsuccessful:
1340
-	 * caller should fall back on clearing the entire cache
1341
-	 * with clearOpcodeCache() if unsuccessful
1342
-	 *
1343
-	 * @param string $path the path of the file to clear from the cache
1344
-	 * @return bool true if underlying function returns true, otherwise false
1345
-	 */
1346
-	public static function deleteFromOpcodeCache($path) {
1347
-		$ret = false;
1348
-		if ($path) {
1349
-			// APC >= 3.1.1
1350
-			if (function_exists('apc_delete_file')) {
1351
-				$ret = @apc_delete_file($path);
1352
-			}
1353
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1354
-			if (function_exists('opcache_invalidate')) {
1355
-				$ret = opcache_invalidate($path);
1356
-			}
1357
-		}
1358
-		return $ret;
1359
-	}
1360
-
1361
-	/**
1362
-	 * Clear the opcode cache if one exists
1363
-	 * This is necessary for writing to the config file
1364
-	 * in case the opcode cache does not re-validate files
1365
-	 *
1366
-	 * @return void
1367
-	 * @suppress PhanDeprecatedFunction
1368
-	 * @suppress PhanUndeclaredConstant
1369
-	 */
1370
-	public static function clearOpcodeCache() {
1371
-		// APC
1372
-		if (function_exists('apc_clear_cache')) {
1373
-			apc_clear_cache();
1374
-		}
1375
-		// Zend Opcache
1376
-		if (function_exists('accelerator_reset')) {
1377
-			accelerator_reset();
1378
-		}
1379
-		// XCache
1380
-		if (function_exists('xcache_clear_cache')) {
1381
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1382
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', ILogger::WARN);
1383
-			} else {
1384
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1385
-			}
1386
-		}
1387
-		// Opcache (PHP >= 5.5)
1388
-		if (function_exists('opcache_reset')) {
1389
-			opcache_reset();
1390
-		}
1391
-	}
1392
-
1393
-	/**
1394
-	 * Normalize a unicode string
1395
-	 *
1396
-	 * @param string $value a not normalized string
1397
-	 * @return bool|string
1398
-	 */
1399
-	public static function normalizeUnicode($value) {
1400
-		if(Normalizer::isNormalized($value)) {
1401
-			return $value;
1402
-		}
1403
-
1404
-		$normalizedValue = Normalizer::normalize($value);
1405
-		if ($normalizedValue === null || $normalizedValue === false) {
1406
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1407
-			return $value;
1408
-		}
1409
-
1410
-		return $normalizedValue;
1411
-	}
1412
-
1413
-	/**
1414
-	 * A human readable string is generated based on version and build number
1415
-	 *
1416
-	 * @return string
1417
-	 */
1418
-	public static function getHumanVersion() {
1419
-		$version = OC_Util::getVersionString();
1420
-		$build = OC_Util::getBuild();
1421
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1422
-			$version .= ' Build:' . $build;
1423
-		}
1424
-		return $version;
1425
-	}
1426
-
1427
-	/**
1428
-	 * Returns whether the given file name is valid
1429
-	 *
1430
-	 * @param string $file file name to check
1431
-	 * @return bool true if the file name is valid, false otherwise
1432
-	 * @deprecated use \OC\Files\View::verifyPath()
1433
-	 */
1434
-	public static function isValidFileName($file) {
1435
-		$trimmed = trim($file);
1436
-		if ($trimmed === '') {
1437
-			return false;
1438
-		}
1439
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1440
-			return false;
1441
-		}
1442
-
1443
-		// detect part files
1444
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1445
-			return false;
1446
-		}
1447
-
1448
-		foreach (str_split($trimmed) as $char) {
1449
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1450
-				return false;
1451
-			}
1452
-		}
1453
-		return true;
1454
-	}
1455
-
1456
-	/**
1457
-	 * Check whether the instance needs to perform an upgrade,
1458
-	 * either when the core version is higher or any app requires
1459
-	 * an upgrade.
1460
-	 *
1461
-	 * @param \OC\SystemConfig $config
1462
-	 * @return bool whether the core or any app needs an upgrade
1463
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1464
-	 */
1465
-	public static function needUpgrade(\OC\SystemConfig $config) {
1466
-		if ($config->getValue('installed', false)) {
1467
-			$installedVersion = $config->getValue('version', '0.0.0');
1468
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1469
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1470
-			if ($versionDiff > 0) {
1471
-				return true;
1472
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1473
-				// downgrade with debug
1474
-				$installedMajor = explode('.', $installedVersion);
1475
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1476
-				$currentMajor = explode('.', $currentVersion);
1477
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1478
-				if ($installedMajor === $currentMajor) {
1479
-					// Same major, allow downgrade for developers
1480
-					return true;
1481
-				} else {
1482
-					// downgrade attempt, throw exception
1483
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1484
-				}
1485
-			} else if ($versionDiff < 0) {
1486
-				// downgrade attempt, throw exception
1487
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1488
-			}
1489
-
1490
-			// also check for upgrades for apps (independently from the user)
1491
-			$apps = \OC_App::getEnabledApps(false, true);
1492
-			$shouldUpgrade = false;
1493
-			foreach ($apps as $app) {
1494
-				if (\OC_App::shouldUpgrade($app)) {
1495
-					$shouldUpgrade = true;
1496
-					break;
1497
-				}
1498
-			}
1499
-			return $shouldUpgrade;
1500
-		} else {
1501
-			return false;
1502
-		}
1503
-	}
1250
+        return $content !== $testContent;
1251
+    }
1252
+
1253
+    /**
1254
+     * Check if the setlocal call does not work. This can happen if the right
1255
+     * local packages are not available on the server.
1256
+     *
1257
+     * @return bool
1258
+     */
1259
+    public static function isSetLocaleWorking() {
1260
+        \Patchwork\Utf8\Bootup::initLocale();
1261
+        if ('' === basename('§')) {
1262
+            return false;
1263
+        }
1264
+        return true;
1265
+    }
1266
+
1267
+    /**
1268
+     * Check if it's possible to get the inline annotations
1269
+     *
1270
+     * @return bool
1271
+     */
1272
+    public static function isAnnotationsWorking() {
1273
+        $reflection = new \ReflectionMethod(__METHOD__);
1274
+        $docs = $reflection->getDocComment();
1275
+
1276
+        return (is_string($docs) && strlen($docs) > 50);
1277
+    }
1278
+
1279
+    /**
1280
+     * Check if the PHP module fileinfo is loaded.
1281
+     *
1282
+     * @return bool
1283
+     */
1284
+    public static function fileInfoLoaded() {
1285
+        return function_exists('finfo_open');
1286
+    }
1287
+
1288
+    /**
1289
+     * clear all levels of output buffering
1290
+     *
1291
+     * @return void
1292
+     */
1293
+    public static function obEnd() {
1294
+        while (ob_get_level()) {
1295
+            ob_end_clean();
1296
+        }
1297
+    }
1298
+
1299
+    /**
1300
+     * Checks whether the server is running on Mac OS X
1301
+     *
1302
+     * @return bool true if running on Mac OS X, false otherwise
1303
+     */
1304
+    public static function runningOnMac() {
1305
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1306
+    }
1307
+
1308
+    /**
1309
+     * Checks whether server is running on HHVM
1310
+     *
1311
+     * @return bool True if running on HHVM, false otherwise
1312
+     */
1313
+    public static function runningOnHhvm() {
1314
+        return defined('HHVM_VERSION');
1315
+    }
1316
+
1317
+    /**
1318
+     * Handles the case that there may not be a theme, then check if a "default"
1319
+     * theme exists and take that one
1320
+     *
1321
+     * @return string the theme
1322
+     */
1323
+    public static function getTheme() {
1324
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1325
+
1326
+        if ($theme === '') {
1327
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1328
+                $theme = 'default';
1329
+            }
1330
+        }
1331
+
1332
+        return $theme;
1333
+    }
1334
+
1335
+    /**
1336
+     * Clear a single file from the opcode cache
1337
+     * This is useful for writing to the config file
1338
+     * in case the opcode cache does not re-validate files
1339
+     * Returns true if successful, false if unsuccessful:
1340
+     * caller should fall back on clearing the entire cache
1341
+     * with clearOpcodeCache() if unsuccessful
1342
+     *
1343
+     * @param string $path the path of the file to clear from the cache
1344
+     * @return bool true if underlying function returns true, otherwise false
1345
+     */
1346
+    public static function deleteFromOpcodeCache($path) {
1347
+        $ret = false;
1348
+        if ($path) {
1349
+            // APC >= 3.1.1
1350
+            if (function_exists('apc_delete_file')) {
1351
+                $ret = @apc_delete_file($path);
1352
+            }
1353
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1354
+            if (function_exists('opcache_invalidate')) {
1355
+                $ret = opcache_invalidate($path);
1356
+            }
1357
+        }
1358
+        return $ret;
1359
+    }
1360
+
1361
+    /**
1362
+     * Clear the opcode cache if one exists
1363
+     * This is necessary for writing to the config file
1364
+     * in case the opcode cache does not re-validate files
1365
+     *
1366
+     * @return void
1367
+     * @suppress PhanDeprecatedFunction
1368
+     * @suppress PhanUndeclaredConstant
1369
+     */
1370
+    public static function clearOpcodeCache() {
1371
+        // APC
1372
+        if (function_exists('apc_clear_cache')) {
1373
+            apc_clear_cache();
1374
+        }
1375
+        // Zend Opcache
1376
+        if (function_exists('accelerator_reset')) {
1377
+            accelerator_reset();
1378
+        }
1379
+        // XCache
1380
+        if (function_exists('xcache_clear_cache')) {
1381
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1382
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', ILogger::WARN);
1383
+            } else {
1384
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1385
+            }
1386
+        }
1387
+        // Opcache (PHP >= 5.5)
1388
+        if (function_exists('opcache_reset')) {
1389
+            opcache_reset();
1390
+        }
1391
+    }
1392
+
1393
+    /**
1394
+     * Normalize a unicode string
1395
+     *
1396
+     * @param string $value a not normalized string
1397
+     * @return bool|string
1398
+     */
1399
+    public static function normalizeUnicode($value) {
1400
+        if(Normalizer::isNormalized($value)) {
1401
+            return $value;
1402
+        }
1403
+
1404
+        $normalizedValue = Normalizer::normalize($value);
1405
+        if ($normalizedValue === null || $normalizedValue === false) {
1406
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1407
+            return $value;
1408
+        }
1409
+
1410
+        return $normalizedValue;
1411
+    }
1412
+
1413
+    /**
1414
+     * A human readable string is generated based on version and build number
1415
+     *
1416
+     * @return string
1417
+     */
1418
+    public static function getHumanVersion() {
1419
+        $version = OC_Util::getVersionString();
1420
+        $build = OC_Util::getBuild();
1421
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1422
+            $version .= ' Build:' . $build;
1423
+        }
1424
+        return $version;
1425
+    }
1426
+
1427
+    /**
1428
+     * Returns whether the given file name is valid
1429
+     *
1430
+     * @param string $file file name to check
1431
+     * @return bool true if the file name is valid, false otherwise
1432
+     * @deprecated use \OC\Files\View::verifyPath()
1433
+     */
1434
+    public static function isValidFileName($file) {
1435
+        $trimmed = trim($file);
1436
+        if ($trimmed === '') {
1437
+            return false;
1438
+        }
1439
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1440
+            return false;
1441
+        }
1442
+
1443
+        // detect part files
1444
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1445
+            return false;
1446
+        }
1447
+
1448
+        foreach (str_split($trimmed) as $char) {
1449
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1450
+                return false;
1451
+            }
1452
+        }
1453
+        return true;
1454
+    }
1455
+
1456
+    /**
1457
+     * Check whether the instance needs to perform an upgrade,
1458
+     * either when the core version is higher or any app requires
1459
+     * an upgrade.
1460
+     *
1461
+     * @param \OC\SystemConfig $config
1462
+     * @return bool whether the core or any app needs an upgrade
1463
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1464
+     */
1465
+    public static function needUpgrade(\OC\SystemConfig $config) {
1466
+        if ($config->getValue('installed', false)) {
1467
+            $installedVersion = $config->getValue('version', '0.0.0');
1468
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1469
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1470
+            if ($versionDiff > 0) {
1471
+                return true;
1472
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1473
+                // downgrade with debug
1474
+                $installedMajor = explode('.', $installedVersion);
1475
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1476
+                $currentMajor = explode('.', $currentVersion);
1477
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1478
+                if ($installedMajor === $currentMajor) {
1479
+                    // Same major, allow downgrade for developers
1480
+                    return true;
1481
+                } else {
1482
+                    // downgrade attempt, throw exception
1483
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1484
+                }
1485
+            } else if ($versionDiff < 0) {
1486
+                // downgrade attempt, throw exception
1487
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1488
+            }
1489
+
1490
+            // also check for upgrades for apps (independently from the user)
1491
+            $apps = \OC_App::getEnabledApps(false, true);
1492
+            $shouldUpgrade = false;
1493
+            foreach ($apps as $app) {
1494
+                if (\OC_App::shouldUpgrade($app)) {
1495
+                    $shouldUpgrade = true;
1496
+                    break;
1497
+                }
1498
+            }
1499
+            return $shouldUpgrade;
1500
+        } else {
1501
+            return false;
1502
+        }
1503
+    }
1504 1504
 
1505 1505
 }
Please login to merge, or discard this patch.
lib/private/App/AppStore/Fetcher/Fetcher.php 1 patch
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -39,162 +39,162 @@
 block discarded – undo
39 39
 use OCP\Util;
40 40
 
41 41
 abstract class Fetcher {
42
-	const INVALIDATE_AFTER_SECONDS = 300;
43
-
44
-	/** @var IAppData */
45
-	protected $appData;
46
-	/** @var IClientService */
47
-	protected $clientService;
48
-	/** @var ITimeFactory */
49
-	protected $timeFactory;
50
-	/** @var IConfig */
51
-	protected $config;
52
-	/** @var Ilogger */
53
-	protected $logger;
54
-	/** @var string */
55
-	protected $fileName;
56
-	/** @var string */
57
-	protected $endpointUrl;
58
-	/** @var string */
59
-	protected $version;
60
-
61
-	/**
62
-	 * @param Factory $appDataFactory
63
-	 * @param IClientService $clientService
64
-	 * @param ITimeFactory $timeFactory
65
-	 * @param IConfig $config
66
-	 * @param ILogger $logger
67
-	 */
68
-	public function __construct(Factory $appDataFactory,
69
-								IClientService $clientService,
70
-								ITimeFactory $timeFactory,
71
-								IConfig $config,
72
-								ILogger $logger) {
73
-		$this->appData = $appDataFactory->get('appstore');
74
-		$this->clientService = $clientService;
75
-		$this->timeFactory = $timeFactory;
76
-		$this->config = $config;
77
-		$this->logger = $logger;
78
-	}
79
-
80
-	/**
81
-	 * Fetches the response from the server
82
-	 *
83
-	 * @param string $ETag
84
-	 * @param string $content
85
-	 *
86
-	 * @return array
87
-	 */
88
-	protected function fetch($ETag, $content) {
89
-		$appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
90
-
91
-		if (!$appstoreenabled) {
92
-			return [];
93
-		}
94
-
95
-		$options = [
96
-			'timeout' => 10,
97
-		];
98
-
99
-		if ($ETag !== '') {
100
-			$options['headers'] = [
101
-				'If-None-Match' => $ETag,
102
-			];
103
-		}
104
-
105
-		$client = $this->clientService->newClient();
106
-		$response = $client->get($this->endpointUrl, $options);
107
-
108
-		$responseJson = [];
109
-		if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
110
-			$responseJson['data'] = json_decode($content, true);
111
-		} else {
112
-			$responseJson['data'] = json_decode($response->getBody(), true);
113
-			$ETag = $response->getHeader('ETag');
114
-		}
115
-
116
-		$responseJson['timestamp'] = $this->timeFactory->getTime();
117
-		$responseJson['ncversion'] = $this->getVersion();
118
-		if ($ETag !== '') {
119
-			$responseJson['ETag'] = $ETag;
120
-		}
121
-
122
-		return $responseJson;
123
-	}
124
-
125
-	/**
126
-	 * Returns the array with the categories on the appstore server
127
-	 *
128
-	 * @return array
129
-	 */
130
-	public function get() {
131
-		$appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
132
-		$internetavailable = $this->config->getSystemValue('has_internet_connection', true);
133
-
134
-		if (!$appstoreenabled || !$internetavailable) {
135
-			return [];
136
-		}
137
-
138
-		$rootFolder = $this->appData->getFolder('/');
139
-
140
-		$ETag = '';
141
-		$content = '';
142
-
143
-		try {
144
-			// File does already exists
145
-			$file = $rootFolder->getFile($this->fileName);
146
-			$jsonBlob = json_decode($file->getContent(), true);
147
-			if (is_array($jsonBlob)) {
148
-
149
-				// No caching when the version has been updated
150
-				if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
151
-
152
-					// If the timestamp is older than 300 seconds request the files new
153
-					if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
154
-						return $jsonBlob['data'];
155
-					}
156
-
157
-					if (isset($jsonBlob['ETag'])) {
158
-						$ETag = $jsonBlob['ETag'];
159
-						$content = json_encode($jsonBlob['data']);
160
-					}
161
-				}
162
-			}
163
-		} catch (NotFoundException $e) {
164
-			// File does not already exists
165
-			$file = $rootFolder->newFile($this->fileName);
166
-		}
167
-
168
-		// Refresh the file content
169
-		try {
170
-			$responseJson = $this->fetch($ETag, $content);
171
-			$file->putContent(json_encode($responseJson));
172
-			return json_decode($file->getContent(), true)['data'];
173
-		} catch (ConnectException $e) {
174
-			$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO, 'message' => 'Could not connect to appstore']);
175
-			return [];
176
-		} catch (\Exception $e) {
177
-			$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO]);
178
-			return [];
179
-		}
180
-	}
181
-
182
-	/**
183
-	 * Get the currently Nextcloud version
184
-	 * @return string
185
-	 */
186
-	protected function getVersion() {
187
-		if ($this->version === null) {
188
-			$this->version = $this->config->getSystemValue('version', '0.0.0');
189
-		}
190
-		return $this->version;
191
-	}
192
-
193
-	/**
194
-	 * Set the current Nextcloud version
195
-	 * @param string $version
196
-	 */
197
-	public function setVersion(string $version) {
198
-		$this->version = $version;
199
-	}
42
+    const INVALIDATE_AFTER_SECONDS = 300;
43
+
44
+    /** @var IAppData */
45
+    protected $appData;
46
+    /** @var IClientService */
47
+    protected $clientService;
48
+    /** @var ITimeFactory */
49
+    protected $timeFactory;
50
+    /** @var IConfig */
51
+    protected $config;
52
+    /** @var Ilogger */
53
+    protected $logger;
54
+    /** @var string */
55
+    protected $fileName;
56
+    /** @var string */
57
+    protected $endpointUrl;
58
+    /** @var string */
59
+    protected $version;
60
+
61
+    /**
62
+     * @param Factory $appDataFactory
63
+     * @param IClientService $clientService
64
+     * @param ITimeFactory $timeFactory
65
+     * @param IConfig $config
66
+     * @param ILogger $logger
67
+     */
68
+    public function __construct(Factory $appDataFactory,
69
+                                IClientService $clientService,
70
+                                ITimeFactory $timeFactory,
71
+                                IConfig $config,
72
+                                ILogger $logger) {
73
+        $this->appData = $appDataFactory->get('appstore');
74
+        $this->clientService = $clientService;
75
+        $this->timeFactory = $timeFactory;
76
+        $this->config = $config;
77
+        $this->logger = $logger;
78
+    }
79
+
80
+    /**
81
+     * Fetches the response from the server
82
+     *
83
+     * @param string $ETag
84
+     * @param string $content
85
+     *
86
+     * @return array
87
+     */
88
+    protected function fetch($ETag, $content) {
89
+        $appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
90
+
91
+        if (!$appstoreenabled) {
92
+            return [];
93
+        }
94
+
95
+        $options = [
96
+            'timeout' => 10,
97
+        ];
98
+
99
+        if ($ETag !== '') {
100
+            $options['headers'] = [
101
+                'If-None-Match' => $ETag,
102
+            ];
103
+        }
104
+
105
+        $client = $this->clientService->newClient();
106
+        $response = $client->get($this->endpointUrl, $options);
107
+
108
+        $responseJson = [];
109
+        if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
110
+            $responseJson['data'] = json_decode($content, true);
111
+        } else {
112
+            $responseJson['data'] = json_decode($response->getBody(), true);
113
+            $ETag = $response->getHeader('ETag');
114
+        }
115
+
116
+        $responseJson['timestamp'] = $this->timeFactory->getTime();
117
+        $responseJson['ncversion'] = $this->getVersion();
118
+        if ($ETag !== '') {
119
+            $responseJson['ETag'] = $ETag;
120
+        }
121
+
122
+        return $responseJson;
123
+    }
124
+
125
+    /**
126
+     * Returns the array with the categories on the appstore server
127
+     *
128
+     * @return array
129
+     */
130
+    public function get() {
131
+        $appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
132
+        $internetavailable = $this->config->getSystemValue('has_internet_connection', true);
133
+
134
+        if (!$appstoreenabled || !$internetavailable) {
135
+            return [];
136
+        }
137
+
138
+        $rootFolder = $this->appData->getFolder('/');
139
+
140
+        $ETag = '';
141
+        $content = '';
142
+
143
+        try {
144
+            // File does already exists
145
+            $file = $rootFolder->getFile($this->fileName);
146
+            $jsonBlob = json_decode($file->getContent(), true);
147
+            if (is_array($jsonBlob)) {
148
+
149
+                // No caching when the version has been updated
150
+                if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
151
+
152
+                    // If the timestamp is older than 300 seconds request the files new
153
+                    if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
154
+                        return $jsonBlob['data'];
155
+                    }
156
+
157
+                    if (isset($jsonBlob['ETag'])) {
158
+                        $ETag = $jsonBlob['ETag'];
159
+                        $content = json_encode($jsonBlob['data']);
160
+                    }
161
+                }
162
+            }
163
+        } catch (NotFoundException $e) {
164
+            // File does not already exists
165
+            $file = $rootFolder->newFile($this->fileName);
166
+        }
167
+
168
+        // Refresh the file content
169
+        try {
170
+            $responseJson = $this->fetch($ETag, $content);
171
+            $file->putContent(json_encode($responseJson));
172
+            return json_decode($file->getContent(), true)['data'];
173
+        } catch (ConnectException $e) {
174
+            $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO, 'message' => 'Could not connect to appstore']);
175
+            return [];
176
+        } catch (\Exception $e) {
177
+            $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO]);
178
+            return [];
179
+        }
180
+    }
181
+
182
+    /**
183
+     * Get the currently Nextcloud version
184
+     * @return string
185
+     */
186
+    protected function getVersion() {
187
+        if ($this->version === null) {
188
+            $this->version = $this->config->getSystemValue('version', '0.0.0');
189
+        }
190
+        return $this->version;
191
+    }
192
+
193
+    /**
194
+     * Set the current Nextcloud version
195
+     * @param string $version
196
+     */
197
+    public function setVersion(string $version) {
198
+        $this->version = $version;
199
+    }
200 200
 }
Please login to merge, or discard this patch.
lib/private/App/AppStore/Fetcher/AppFetcher.php 1 patch
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -37,119 +37,119 @@
 block discarded – undo
37 37
 
38 38
 class AppFetcher extends Fetcher {
39 39
 
40
-	/** @var CompareVersion */
41
-	private $compareVersion;
40
+    /** @var CompareVersion */
41
+    private $compareVersion;
42 42
 
43
-	/**
44
-	 * @param Factory $appDataFactory
45
-	 * @param IClientService $clientService
46
-	 * @param ITimeFactory $timeFactory
47
-	 * @param IConfig $config
48
-	 * @param CompareVersion $compareVersion
49
-	 * @param ILogger $logger
50
-	 */
51
-	public function __construct(Factory $appDataFactory,
52
-								IClientService $clientService,
53
-								ITimeFactory $timeFactory,
54
-								IConfig $config,
55
-								CompareVersion $compareVersion,
56
-								ILogger $logger) {
57
-		parent::__construct(
58
-			$appDataFactory,
59
-			$clientService,
60
-			$timeFactory,
61
-			$config,
62
-			$logger
63
-		);
43
+    /**
44
+     * @param Factory $appDataFactory
45
+     * @param IClientService $clientService
46
+     * @param ITimeFactory $timeFactory
47
+     * @param IConfig $config
48
+     * @param CompareVersion $compareVersion
49
+     * @param ILogger $logger
50
+     */
51
+    public function __construct(Factory $appDataFactory,
52
+                                IClientService $clientService,
53
+                                ITimeFactory $timeFactory,
54
+                                IConfig $config,
55
+                                CompareVersion $compareVersion,
56
+                                ILogger $logger) {
57
+        parent::__construct(
58
+            $appDataFactory,
59
+            $clientService,
60
+            $timeFactory,
61
+            $config,
62
+            $logger
63
+        );
64 64
 
65
-		$this->fileName = 'apps.json';
66
-		$this->setEndpoint();
67
-		$this->compareVersion = $compareVersion;
68
-	}
65
+        $this->fileName = 'apps.json';
66
+        $this->setEndpoint();
67
+        $this->compareVersion = $compareVersion;
68
+    }
69 69
 
70
-	/**
71
-	 * Only returns the latest compatible app release in the releases array
72
-	 *
73
-	 * @param string $ETag
74
-	 * @param string $content
75
-	 *
76
-	 * @return array
77
-	 */
78
-	protected function fetch($ETag, $content) {
79
-		/** @var mixed[] $response */
80
-		$response = parent::fetch($ETag, $content);
70
+    /**
71
+     * Only returns the latest compatible app release in the releases array
72
+     *
73
+     * @param string $ETag
74
+     * @param string $content
75
+     *
76
+     * @return array
77
+     */
78
+    protected function fetch($ETag, $content) {
79
+        /** @var mixed[] $response */
80
+        $response = parent::fetch($ETag, $content);
81 81
 
82
-		foreach($response['data'] as $dataKey => $app) {
83
-			$releases = [];
82
+        foreach($response['data'] as $dataKey => $app) {
83
+            $releases = [];
84 84
 
85
-			// Filter all compatible releases
86
-			foreach($app['releases'] as $release) {
87
-				// Exclude all nightly and pre-releases
88
-				if($release['isNightly'] === false
89
-					&& strpos($release['version'], '-') === false) {
90
-					// Exclude all versions not compatible with the current version
91
-					try {
92
-						$versionParser = new VersionParser();
93
-						$version = $versionParser->getVersion($release['rawPlatformVersionSpec']);
94
-						$ncVersion = $this->getVersion();
95
-						$min = $version->getMinimumVersion();
96
-						$max = $version->getMaximumVersion();
97
-						$minFulfilled = $this->compareVersion->isCompatible($ncVersion, $min, '>=');
98
-						$maxFulfilled = $max !== '' &&
99
-							$this->compareVersion->isCompatible($ncVersion, $max, '<=');
100
-						if ($minFulfilled && $maxFulfilled) {
101
-							$releases[] = $release;
102
-						}
103
-					} catch (\InvalidArgumentException $e) {
104
-						$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::WARN]);
105
-					}
106
-				}
107
-			}
85
+            // Filter all compatible releases
86
+            foreach($app['releases'] as $release) {
87
+                // Exclude all nightly and pre-releases
88
+                if($release['isNightly'] === false
89
+                    && strpos($release['version'], '-') === false) {
90
+                    // Exclude all versions not compatible with the current version
91
+                    try {
92
+                        $versionParser = new VersionParser();
93
+                        $version = $versionParser->getVersion($release['rawPlatformVersionSpec']);
94
+                        $ncVersion = $this->getVersion();
95
+                        $min = $version->getMinimumVersion();
96
+                        $max = $version->getMaximumVersion();
97
+                        $minFulfilled = $this->compareVersion->isCompatible($ncVersion, $min, '>=');
98
+                        $maxFulfilled = $max !== '' &&
99
+                            $this->compareVersion->isCompatible($ncVersion, $max, '<=');
100
+                        if ($minFulfilled && $maxFulfilled) {
101
+                            $releases[] = $release;
102
+                        }
103
+                    } catch (\InvalidArgumentException $e) {
104
+                        $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::WARN]);
105
+                    }
106
+                }
107
+            }
108 108
 
109
-			// Get the highest version
110
-			$versions = [];
111
-			foreach($releases as $release) {
112
-				$versions[] = $release['version'];
113
-			}
114
-			usort($versions, 'version_compare');
115
-			$versions = array_reverse($versions);
116
-			$compatible = false;
117
-			if(isset($versions[0])) {
118
-				$highestVersion = $versions[0];
119
-				foreach ($releases as $release) {
120
-					if ((string)$release['version'] === (string)$highestVersion) {
121
-						$compatible = true;
122
-						$response['data'][$dataKey]['releases'] = [$release];
123
-						break;
124
-					}
125
-				}
126
-			}
127
-			if(!$compatible) {
128
-				unset($response['data'][$dataKey]);
129
-			}
130
-		}
109
+            // Get the highest version
110
+            $versions = [];
111
+            foreach($releases as $release) {
112
+                $versions[] = $release['version'];
113
+            }
114
+            usort($versions, 'version_compare');
115
+            $versions = array_reverse($versions);
116
+            $compatible = false;
117
+            if(isset($versions[0])) {
118
+                $highestVersion = $versions[0];
119
+                foreach ($releases as $release) {
120
+                    if ((string)$release['version'] === (string)$highestVersion) {
121
+                        $compatible = true;
122
+                        $response['data'][$dataKey]['releases'] = [$release];
123
+                        break;
124
+                    }
125
+                }
126
+            }
127
+            if(!$compatible) {
128
+                unset($response['data'][$dataKey]);
129
+            }
130
+        }
131 131
 
132
-		$response['data'] = array_values($response['data']);
133
-		return $response;
134
-	}
132
+        $response['data'] = array_values($response['data']);
133
+        return $response;
134
+    }
135 135
 
136
-	private function setEndpoint() {
137
-		$versionArray = explode('.', $this->getVersion());
138
-		$this->endpointUrl = sprintf(
139
-			'https://apps.nextcloud.com/api/v1/platform/%d.%d.%d/apps.json',
140
-			$versionArray[0],
141
-			$versionArray[1],
142
-			$versionArray[2]
143
-		);
144
-	}
136
+    private function setEndpoint() {
137
+        $versionArray = explode('.', $this->getVersion());
138
+        $this->endpointUrl = sprintf(
139
+            'https://apps.nextcloud.com/api/v1/platform/%d.%d.%d/apps.json',
140
+            $versionArray[0],
141
+            $versionArray[1],
142
+            $versionArray[2]
143
+        );
144
+    }
145 145
 
146
-	/**
147
-	 * @param string $version
148
-	 * @param string $fileName
149
-	 */
150
-	public function setVersion(string $version, string $fileName = 'apps.json') {
151
-		parent::setVersion($version);
152
-		$this->fileName = $fileName;
153
-		$this->setEndpoint();
154
-	}
146
+    /**
147
+     * @param string $version
148
+     * @param string $fileName
149
+     */
150
+    public function setVersion(string $version, string $fileName = 'apps.json') {
151
+        parent::setVersion($version);
152
+        $this->fileName = $fileName;
153
+        $this->setEndpoint();
154
+    }
155 155
 }
Please login to merge, or discard this patch.
lib/private/Settings/Manager.php 1 patch
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -49,356 +49,356 @@
 block discarded – undo
49 49
 use OCP\Util;
50 50
 
51 51
 class Manager implements IManager {
52
-	/** @var ILogger */
53
-	private $log;
54
-	/** @var IDBConnection */
55
-	private $dbc;
56
-	/** @var IL10N */
57
-	private $l;
58
-	/** @var IConfig */
59
-	private $config;
60
-	/** @var EncryptionManager */
61
-	private $encryptionManager;
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-	/** @var ILockingProvider */
65
-	private $lockingProvider;
66
-	/** @var IRequest */
67
-	private $request;
68
-	/** @var IURLGenerator */
69
-	private $url;
70
-	/** @var AccountManager */
71
-	private $accountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IFactory */
75
-	private $l10nFactory;
76
-	/** @var IAppManager */
77
-	private $appManager;
78
-
79
-	/**
80
-	 * @param ILogger $log
81
-	 * @param IDBConnection $dbc
82
-	 * @param IL10N $l
83
-	 * @param IConfig $config
84
-	 * @param EncryptionManager $encryptionManager
85
-	 * @param IUserManager $userManager
86
-	 * @param ILockingProvider $lockingProvider
87
-	 * @param IRequest $request
88
-	 * @param IURLGenerator $url
89
-	 * @param AccountManager $accountManager
90
-	 * @param IGroupManager $groupManager
91
-	 * @param IFactory $l10nFactory
92
-	 * @param IAppManager $appManager
93
-	 */
94
-	public function __construct(
95
-		ILogger $log,
96
-		IDBConnection $dbc,
97
-		IL10N $l,
98
-		IConfig $config,
99
-		EncryptionManager $encryptionManager,
100
-		IUserManager $userManager,
101
-		ILockingProvider $lockingProvider,
102
-		IRequest $request,
103
-		IURLGenerator $url,
104
-		AccountManager $accountManager,
105
-		IGroupManager $groupManager,
106
-		IFactory $l10nFactory,
107
-		IAppManager $appManager
108
-	) {
109
-		$this->log = $log;
110
-		$this->dbc = $dbc;
111
-		$this->l = $l;
112
-		$this->config = $config;
113
-		$this->encryptionManager = $encryptionManager;
114
-		$this->userManager = $userManager;
115
-		$this->lockingProvider = $lockingProvider;
116
-		$this->request = $request;
117
-		$this->url = $url;
118
-		$this->accountManager = $accountManager;
119
-		$this->groupManager = $groupManager;
120
-		$this->l10nFactory = $l10nFactory;
121
-		$this->appManager = $appManager;
122
-	}
123
-
124
-	/** @var array */
125
-	protected $sectionClasses = [];
126
-
127
-	/** @var array */
128
-	protected $sections = [];
129
-
130
-	/**
131
-	 * @param string $type 'admin' or 'personal'
132
-	 * @param string $section Class must implement OCP\Settings\ISection
133
-	 * @return void
134
-	 */
135
-	public function registerSection(string $type, string $section) {
136
-		$this->sectionClasses[$section] = $type;
137
-	}
138
-
139
-	/**
140
-	 * @param string $type 'admin' or 'personal'
141
-	 * @return ISection[]
142
-	 */
143
-	protected function getSections(string $type): array {
144
-		if (!isset($this->sections[$type])) {
145
-			$this->sections[$type] = [];
146
-		}
147
-
148
-		foreach ($this->sectionClasses as $class => $sectionType) {
149
-			try {
150
-				/** @var ISection $section */
151
-				$section = \OC::$server->query($class);
152
-			} catch (QueryException $e) {
153
-				$this->log->logException($e, ['level' => ILogger::INFO]);
154
-				continue;
155
-			}
156
-
157
-			if (!$section instanceof ISection) {
158
-				$this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => ILogger::INFO]);
159
-				continue;
160
-			}
161
-
162
-			$this->sections[$sectionType][$section->getID()] = $section;
163
-
164
-			unset($this->sectionClasses[$class]);
165
-		}
166
-
167
-		return $this->sections[$type];
168
-	}
169
-
170
-	/** @var array */
171
-	protected $settingClasses = [];
172
-
173
-	/** @var array */
174
-	protected $settings = [];
175
-
176
-	/**
177
-	 * @param string $type 'admin' or 'personal'
178
-	 * @param string $setting Class must implement OCP\Settings\ISetting
179
-	 * @return void
180
-	 */
181
-	public function registerSetting(string $type, string $setting) {
182
-		$this->settingClasses[$setting] = $type;
183
-	}
184
-
185
-	/**
186
-	 * @param string $type 'admin' or 'personal'
187
-	 * @param string $section
188
-	 * @return ISettings[]
189
-	 */
190
-	protected function getSettings(string $type, string $section): array {
191
-		if (!isset($this->settings[$type])) {
192
-			$this->settings[$type] = [];
193
-		}
194
-		if (!isset($this->settings[$type][$section])) {
195
-			$this->settings[$type][$section] = [];
196
-		}
197
-
198
-		foreach ($this->settingClasses as $class => $settingsType) {
199
-			try {
200
-				/** @var ISettings $setting */
201
-				$setting = \OC::$server->query($class);
202
-			} catch (QueryException $e) {
203
-				$this->log->logException($e, ['level' => ILogger::INFO]);
204
-				continue;
205
-			}
206
-
207
-			if (!$setting instanceof ISettings) {
208
-				$this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => ILogger::INFO]);
209
-				continue;
210
-			}
211
-
212
-			if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
-				$this->settings[$settingsType][$setting->getSection()] = [];
214
-			}
215
-			$this->settings[$settingsType][$setting->getSection()][] = $setting;
216
-
217
-			unset($this->settingClasses[$class]);
218
-		}
219
-
220
-		return $this->settings[$type][$section];
221
-	}
222
-
223
-	/**
224
-	 * @inheritdoc
225
-	 */
226
-	public function getAdminSections(): array {
227
-		// built-in sections
228
-		$sections = [
229
-			0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
-			5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
-			10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
-			45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
-			98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
-			99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
-		];
236
-
237
-		$appSections = $this->getSections('admin');
238
-
239
-		foreach ($appSections as $section) {
240
-			/** @var ISection $section */
241
-			if (!isset($sections[$section->getPriority()])) {
242
-				$sections[$section->getPriority()] = [];
243
-			}
244
-
245
-			$sections[$section->getPriority()][] = $section;
246
-		}
247
-
248
-		ksort($sections);
249
-
250
-		return $sections;
251
-	}
252
-
253
-	/**
254
-	 * @param string $section
255
-	 * @return ISection[]
256
-	 */
257
-	private function getBuiltInAdminSettings($section): array {
258
-		$forms = [];
259
-
260
-		if ($section === 'server') {
261
-			/** @var ISettings $form */
262
-			$form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
-			$forms[$form->getPriority()] = [$form];
264
-			$form = new Admin\ServerDevNotice();
265
-			$forms[$form->getPriority()] = [$form];
266
-		}
267
-		if ($section === 'encryption') {
268
-			/** @var ISettings $form */
269
-			$form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
-			$forms[$form->getPriority()] = [$form];
271
-		}
272
-		if ($section === 'sharing') {
273
-			/** @var ISettings $form */
274
-			$form = new Admin\Sharing($this->config, $this->l);
275
-			$forms[$form->getPriority()] = [$form];
276
-		}
277
-		if ($section === 'additional') {
278
-			/** @var ISettings $form */
279
-			$form = new Admin\Additional($this->config);
280
-			$forms[$form->getPriority()] = [$form];
281
-		}
282
-		if ($section === 'tips-tricks') {
283
-			/** @var ISettings $form */
284
-			$form = new Admin\TipsTricks($this->config);
285
-			$forms[$form->getPriority()] = [$form];
286
-		}
287
-
288
-		return $forms;
289
-	}
290
-
291
-	/**
292
-	 * @param string $section
293
-	 * @return ISection[]
294
-	 */
295
-	private function getBuiltInPersonalSettings($section): array {
296
-		$forms = [];
297
-
298
-		if ($section === 'personal-info') {
299
-			/** @var ISettings $form */
300
-			$form = new Personal\PersonalInfo(
301
-				$this->config,
302
-				$this->userManager,
303
-				$this->groupManager,
304
-				$this->accountManager,
305
-				$this->appManager,
306
-				$this->l10nFactory,
307
-				$this->l
308
-			);
309
-			$forms[$form->getPriority()] = [$form];
310
-		}
311
-		if($section === 'security') {
312
-			/** @var ISettings $form */
313
-			$form = new Personal\Security();
314
-			$forms[$form->getPriority()] = [$form];
315
-		}
316
-		if ($section === 'additional') {
317
-			/** @var ISettings $form */
318
-			$form = new Personal\Additional();
319
-			$forms[$form->getPriority()] = [$form];
320
-		}
321
-
322
-		return $forms;
323
-	}
324
-
325
-	/**
326
-	 * @inheritdoc
327
-	 */
328
-	public function getAdminSettings($section): array {
329
-		$settings = $this->getBuiltInAdminSettings($section);
330
-		$appSettings = $this->getSettings('admin', $section);
331
-
332
-		foreach ($appSettings as $setting) {
333
-			if (!isset($settings[$setting->getPriority()])) {
334
-				$settings[$setting->getPriority()] = [];
335
-			}
336
-			$settings[$setting->getPriority()][] = $setting;
337
-		}
338
-
339
-		ksort($settings);
340
-		return $settings;
341
-	}
342
-
343
-	/**
344
-	 * @inheritdoc
345
-	 */
346
-	public function getPersonalSections(): array {
347
-		$sections = [
348
-			0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
-			5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
-			15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
-		];
352
-
353
-		$legacyForms = \OC_App::getForms('personal');
354
-		if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
-			$sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
-		}
357
-
358
-		$appSections = $this->getSections('personal');
359
-
360
-		foreach ($appSections as $section) {
361
-			/** @var ISection $section */
362
-			if (!isset($sections[$section->getPriority()])) {
363
-				$sections[$section->getPriority()] = [];
364
-			}
365
-
366
-			$sections[$section->getPriority()][] = $section;
367
-		}
368
-
369
-		ksort($sections);
370
-
371
-		return $sections;
372
-	}
373
-
374
-	/**
375
-	 * @param string[] $forms
376
-	 * @return bool
377
-	 */
378
-	private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
-		foreach ($forms as $form) {
380
-			if(trim($form) !== '') {
381
-				return true;
382
-			}
383
-		}
384
-		return false;
385
-	}
386
-
387
-	/**
388
-	 * @inheritdoc
389
-	 */
390
-	public function getPersonalSettings($section): array {
391
-		$settings = $this->getBuiltInPersonalSettings($section);
392
-		$appSettings = $this->getSettings('personal', $section);
393
-
394
-		foreach ($appSettings as $setting) {
395
-			if (!isset($settings[$setting->getPriority()])) {
396
-				$settings[$setting->getPriority()] = [];
397
-			}
398
-			$settings[$setting->getPriority()][] = $setting;
399
-		}
400
-
401
-		ksort($settings);
402
-		return $settings;
403
-	}
52
+    /** @var ILogger */
53
+    private $log;
54
+    /** @var IDBConnection */
55
+    private $dbc;
56
+    /** @var IL10N */
57
+    private $l;
58
+    /** @var IConfig */
59
+    private $config;
60
+    /** @var EncryptionManager */
61
+    private $encryptionManager;
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+    /** @var ILockingProvider */
65
+    private $lockingProvider;
66
+    /** @var IRequest */
67
+    private $request;
68
+    /** @var IURLGenerator */
69
+    private $url;
70
+    /** @var AccountManager */
71
+    private $accountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IFactory */
75
+    private $l10nFactory;
76
+    /** @var IAppManager */
77
+    private $appManager;
78
+
79
+    /**
80
+     * @param ILogger $log
81
+     * @param IDBConnection $dbc
82
+     * @param IL10N $l
83
+     * @param IConfig $config
84
+     * @param EncryptionManager $encryptionManager
85
+     * @param IUserManager $userManager
86
+     * @param ILockingProvider $lockingProvider
87
+     * @param IRequest $request
88
+     * @param IURLGenerator $url
89
+     * @param AccountManager $accountManager
90
+     * @param IGroupManager $groupManager
91
+     * @param IFactory $l10nFactory
92
+     * @param IAppManager $appManager
93
+     */
94
+    public function __construct(
95
+        ILogger $log,
96
+        IDBConnection $dbc,
97
+        IL10N $l,
98
+        IConfig $config,
99
+        EncryptionManager $encryptionManager,
100
+        IUserManager $userManager,
101
+        ILockingProvider $lockingProvider,
102
+        IRequest $request,
103
+        IURLGenerator $url,
104
+        AccountManager $accountManager,
105
+        IGroupManager $groupManager,
106
+        IFactory $l10nFactory,
107
+        IAppManager $appManager
108
+    ) {
109
+        $this->log = $log;
110
+        $this->dbc = $dbc;
111
+        $this->l = $l;
112
+        $this->config = $config;
113
+        $this->encryptionManager = $encryptionManager;
114
+        $this->userManager = $userManager;
115
+        $this->lockingProvider = $lockingProvider;
116
+        $this->request = $request;
117
+        $this->url = $url;
118
+        $this->accountManager = $accountManager;
119
+        $this->groupManager = $groupManager;
120
+        $this->l10nFactory = $l10nFactory;
121
+        $this->appManager = $appManager;
122
+    }
123
+
124
+    /** @var array */
125
+    protected $sectionClasses = [];
126
+
127
+    /** @var array */
128
+    protected $sections = [];
129
+
130
+    /**
131
+     * @param string $type 'admin' or 'personal'
132
+     * @param string $section Class must implement OCP\Settings\ISection
133
+     * @return void
134
+     */
135
+    public function registerSection(string $type, string $section) {
136
+        $this->sectionClasses[$section] = $type;
137
+    }
138
+
139
+    /**
140
+     * @param string $type 'admin' or 'personal'
141
+     * @return ISection[]
142
+     */
143
+    protected function getSections(string $type): array {
144
+        if (!isset($this->sections[$type])) {
145
+            $this->sections[$type] = [];
146
+        }
147
+
148
+        foreach ($this->sectionClasses as $class => $sectionType) {
149
+            try {
150
+                /** @var ISection $section */
151
+                $section = \OC::$server->query($class);
152
+            } catch (QueryException $e) {
153
+                $this->log->logException($e, ['level' => ILogger::INFO]);
154
+                continue;
155
+            }
156
+
157
+            if (!$section instanceof ISection) {
158
+                $this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => ILogger::INFO]);
159
+                continue;
160
+            }
161
+
162
+            $this->sections[$sectionType][$section->getID()] = $section;
163
+
164
+            unset($this->sectionClasses[$class]);
165
+        }
166
+
167
+        return $this->sections[$type];
168
+    }
169
+
170
+    /** @var array */
171
+    protected $settingClasses = [];
172
+
173
+    /** @var array */
174
+    protected $settings = [];
175
+
176
+    /**
177
+     * @param string $type 'admin' or 'personal'
178
+     * @param string $setting Class must implement OCP\Settings\ISetting
179
+     * @return void
180
+     */
181
+    public function registerSetting(string $type, string $setting) {
182
+        $this->settingClasses[$setting] = $type;
183
+    }
184
+
185
+    /**
186
+     * @param string $type 'admin' or 'personal'
187
+     * @param string $section
188
+     * @return ISettings[]
189
+     */
190
+    protected function getSettings(string $type, string $section): array {
191
+        if (!isset($this->settings[$type])) {
192
+            $this->settings[$type] = [];
193
+        }
194
+        if (!isset($this->settings[$type][$section])) {
195
+            $this->settings[$type][$section] = [];
196
+        }
197
+
198
+        foreach ($this->settingClasses as $class => $settingsType) {
199
+            try {
200
+                /** @var ISettings $setting */
201
+                $setting = \OC::$server->query($class);
202
+            } catch (QueryException $e) {
203
+                $this->log->logException($e, ['level' => ILogger::INFO]);
204
+                continue;
205
+            }
206
+
207
+            if (!$setting instanceof ISettings) {
208
+                $this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => ILogger::INFO]);
209
+                continue;
210
+            }
211
+
212
+            if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
+                $this->settings[$settingsType][$setting->getSection()] = [];
214
+            }
215
+            $this->settings[$settingsType][$setting->getSection()][] = $setting;
216
+
217
+            unset($this->settingClasses[$class]);
218
+        }
219
+
220
+        return $this->settings[$type][$section];
221
+    }
222
+
223
+    /**
224
+     * @inheritdoc
225
+     */
226
+    public function getAdminSections(): array {
227
+        // built-in sections
228
+        $sections = [
229
+            0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
+            5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
+            10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
+            45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
+            98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
+            99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
+        ];
236
+
237
+        $appSections = $this->getSections('admin');
238
+
239
+        foreach ($appSections as $section) {
240
+            /** @var ISection $section */
241
+            if (!isset($sections[$section->getPriority()])) {
242
+                $sections[$section->getPriority()] = [];
243
+            }
244
+
245
+            $sections[$section->getPriority()][] = $section;
246
+        }
247
+
248
+        ksort($sections);
249
+
250
+        return $sections;
251
+    }
252
+
253
+    /**
254
+     * @param string $section
255
+     * @return ISection[]
256
+     */
257
+    private function getBuiltInAdminSettings($section): array {
258
+        $forms = [];
259
+
260
+        if ($section === 'server') {
261
+            /** @var ISettings $form */
262
+            $form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
+            $forms[$form->getPriority()] = [$form];
264
+            $form = new Admin\ServerDevNotice();
265
+            $forms[$form->getPriority()] = [$form];
266
+        }
267
+        if ($section === 'encryption') {
268
+            /** @var ISettings $form */
269
+            $form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
+            $forms[$form->getPriority()] = [$form];
271
+        }
272
+        if ($section === 'sharing') {
273
+            /** @var ISettings $form */
274
+            $form = new Admin\Sharing($this->config, $this->l);
275
+            $forms[$form->getPriority()] = [$form];
276
+        }
277
+        if ($section === 'additional') {
278
+            /** @var ISettings $form */
279
+            $form = new Admin\Additional($this->config);
280
+            $forms[$form->getPriority()] = [$form];
281
+        }
282
+        if ($section === 'tips-tricks') {
283
+            /** @var ISettings $form */
284
+            $form = new Admin\TipsTricks($this->config);
285
+            $forms[$form->getPriority()] = [$form];
286
+        }
287
+
288
+        return $forms;
289
+    }
290
+
291
+    /**
292
+     * @param string $section
293
+     * @return ISection[]
294
+     */
295
+    private function getBuiltInPersonalSettings($section): array {
296
+        $forms = [];
297
+
298
+        if ($section === 'personal-info') {
299
+            /** @var ISettings $form */
300
+            $form = new Personal\PersonalInfo(
301
+                $this->config,
302
+                $this->userManager,
303
+                $this->groupManager,
304
+                $this->accountManager,
305
+                $this->appManager,
306
+                $this->l10nFactory,
307
+                $this->l
308
+            );
309
+            $forms[$form->getPriority()] = [$form];
310
+        }
311
+        if($section === 'security') {
312
+            /** @var ISettings $form */
313
+            $form = new Personal\Security();
314
+            $forms[$form->getPriority()] = [$form];
315
+        }
316
+        if ($section === 'additional') {
317
+            /** @var ISettings $form */
318
+            $form = new Personal\Additional();
319
+            $forms[$form->getPriority()] = [$form];
320
+        }
321
+
322
+        return $forms;
323
+    }
324
+
325
+    /**
326
+     * @inheritdoc
327
+     */
328
+    public function getAdminSettings($section): array {
329
+        $settings = $this->getBuiltInAdminSettings($section);
330
+        $appSettings = $this->getSettings('admin', $section);
331
+
332
+        foreach ($appSettings as $setting) {
333
+            if (!isset($settings[$setting->getPriority()])) {
334
+                $settings[$setting->getPriority()] = [];
335
+            }
336
+            $settings[$setting->getPriority()][] = $setting;
337
+        }
338
+
339
+        ksort($settings);
340
+        return $settings;
341
+    }
342
+
343
+    /**
344
+     * @inheritdoc
345
+     */
346
+    public function getPersonalSections(): array {
347
+        $sections = [
348
+            0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
+            5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
+            15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
+        ];
352
+
353
+        $legacyForms = \OC_App::getForms('personal');
354
+        if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
+            $sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
+        }
357
+
358
+        $appSections = $this->getSections('personal');
359
+
360
+        foreach ($appSections as $section) {
361
+            /** @var ISection $section */
362
+            if (!isset($sections[$section->getPriority()])) {
363
+                $sections[$section->getPriority()] = [];
364
+            }
365
+
366
+            $sections[$section->getPriority()][] = $section;
367
+        }
368
+
369
+        ksort($sections);
370
+
371
+        return $sections;
372
+    }
373
+
374
+    /**
375
+     * @param string[] $forms
376
+     * @return bool
377
+     */
378
+    private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
+        foreach ($forms as $form) {
380
+            if(trim($form) !== '') {
381
+                return true;
382
+            }
383
+        }
384
+        return false;
385
+    }
386
+
387
+    /**
388
+     * @inheritdoc
389
+     */
390
+    public function getPersonalSettings($section): array {
391
+        $settings = $this->getBuiltInPersonalSettings($section);
392
+        $appSettings = $this->getSettings('personal', $section);
393
+
394
+        foreach ($appSettings as $setting) {
395
+            if (!isset($settings[$setting->getPriority()])) {
396
+                $settings[$setting->getPriority()] = [];
397
+            }
398
+            $settings[$setting->getPriority()][] = $setting;
399
+        }
400
+
401
+        ksort($settings);
402
+        return $settings;
403
+    }
404 404
 }
Please login to merge, or discard this patch.
lib/private/CapabilitiesManager.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -32,58 +32,58 @@
 block discarded – undo
32 32
 
33 33
 class CapabilitiesManager {
34 34
 
35
-	/** @var \Closure[] */
36
-	private $capabilities = array();
35
+    /** @var \Closure[] */
36
+    private $capabilities = array();
37 37
 
38
-	/** @var ILogger */
39
-	private $logger;
38
+    /** @var ILogger */
39
+    private $logger;
40 40
 
41
-	public function __construct(ILogger $logger) {
42
-		$this->logger = $logger;
43
-	}
41
+    public function __construct(ILogger $logger) {
42
+        $this->logger = $logger;
43
+    }
44 44
 
45
-	/**
46
-	 * Get an array of al the capabilities that are registered at this manager
45
+    /**
46
+     * Get an array of al the capabilities that are registered at this manager
47 47
      *
48
-	 * @param bool $public get public capabilities only
49
-	 * @throws \InvalidArgumentException
50
-	 * @return array
51
-	 */
52
-	public function getCapabilities(bool $public = false) : array {
53
-		$capabilities = [];
54
-		foreach($this->capabilities as $capability) {
55
-			try {
56
-				$c = $capability();
57
-			} catch (QueryException $e) {
58
-				$this->logger->logException($e, [
59
-					'message' => 'CapabilitiesManager',
60
-					'level' => ILogger::ERROR,
61
-					'app' => 'core',
62
-				]);
63
-				continue;
64
-			}
48
+     * @param bool $public get public capabilities only
49
+     * @throws \InvalidArgumentException
50
+     * @return array
51
+     */
52
+    public function getCapabilities(bool $public = false) : array {
53
+        $capabilities = [];
54
+        foreach($this->capabilities as $capability) {
55
+            try {
56
+                $c = $capability();
57
+            } catch (QueryException $e) {
58
+                $this->logger->logException($e, [
59
+                    'message' => 'CapabilitiesManager',
60
+                    'level' => ILogger::ERROR,
61
+                    'app' => 'core',
62
+                ]);
63
+                continue;
64
+            }
65 65
 
66
-			if ($c instanceof ICapability) {
67
-				if(!$public || $c instanceof IPublicCapability) {
68
-					$capabilities = array_replace_recursive($capabilities, $c->getCapabilities());
69
-				}
70
-			} else {
71
-				throw new \InvalidArgumentException('The given Capability (' . get_class($c) . ') does not implement the ICapability interface');
72
-			}
73
-		}
66
+            if ($c instanceof ICapability) {
67
+                if(!$public || $c instanceof IPublicCapability) {
68
+                    $capabilities = array_replace_recursive($capabilities, $c->getCapabilities());
69
+                }
70
+            } else {
71
+                throw new \InvalidArgumentException('The given Capability (' . get_class($c) . ') does not implement the ICapability interface');
72
+            }
73
+        }
74 74
 
75
-		return $capabilities;
76
-	}
75
+        return $capabilities;
76
+    }
77 77
 
78
-	/**
79
-	 * In order to improve lazy loading a closure can be registered which will be called in case
80
-	 * capabilities are actually requested
81
-	 *
82
-	 * $callable has to return an instance of OCP\Capabilities\ICapability
83
-	 *
84
-	 * @param \Closure $callable
85
-	 */
86
-	public function registerCapability(\Closure $callable) {
87
-		$this->capabilities[] = $callable;
88
-	}
78
+    /**
79
+     * In order to improve lazy loading a closure can be registered which will be called in case
80
+     * capabilities are actually requested
81
+     *
82
+     * $callable has to return an instance of OCP\Capabilities\ICapability
83
+     *
84
+     * @param \Closure $callable
85
+     */
86
+    public function registerCapability(\Closure $callable) {
87
+        $this->capabilities[] = $callable;
88
+    }
89 89
 }
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/S3ConnectionTrait.php 1 patch
Indentation   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -30,116 +30,116 @@
 block discarded – undo
30 30
 use OCP\ILogger;
31 31
 
32 32
 trait S3ConnectionTrait {
33
-	/** @var array */
34
-	protected $params;
35
-
36
-	/** @var S3Client */
37
-	protected $connection;
38
-
39
-	/** @var string */
40
-	protected $id;
41
-
42
-	/** @var string */
43
-	protected $bucket;
44
-
45
-	/** @var int */
46
-	protected $timeout;
47
-
48
-	protected $test;
49
-
50
-	protected function parseParams($params) {
51
-		if (empty($params['key']) || empty($params['secret']) || empty($params['bucket'])) {
52
-			throw new \Exception("Access Key, Secret and Bucket have to be configured.");
53
-		}
54
-
55
-		$this->id = 'amazon::' . $params['bucket'];
56
-
57
-		$this->test = isset($params['test']);
58
-		$this->bucket = $params['bucket'];
59
-		$this->timeout = !isset($params['timeout']) ? 15 : $params['timeout'];
60
-		$params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
61
-		$params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
62
-		if (!isset($params['port']) || $params['port'] === '') {
63
-			$params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
64
-		}
65
-		$this->params = $params;
66
-	}
67
-
68
-
69
-	/**
70
-	 * Returns the connection
71
-	 *
72
-	 * @return S3Client connected client
73
-	 * @throws \Exception if connection could not be made
74
-	 */
75
-	protected function getConnection() {
76
-		if (!is_null($this->connection)) {
77
-			return $this->connection;
78
-		}
79
-
80
-		$scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
81
-		$base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
82
-
83
-		$options = [
84
-			'version' => isset($this->params['version']) ? $this->params['version'] : 'latest',
85
-			'credentials' => [
86
-				'key' => $this->params['key'],
87
-				'secret' => $this->params['secret'],
88
-			],
89
-			'endpoint' => $base_url,
90
-			'region' => $this->params['region'],
91
-			'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
92
-			'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider())
93
-		];
94
-		if (isset($this->params['proxy'])) {
95
-			$options['request.options'] = ['proxy' => $this->params['proxy']];
96
-		}
97
-		if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
98
-			$options['signature_version'] = 'v2';
99
-		}
100
-		$this->connection = new S3Client($options);
101
-
102
-		if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
103
-			throw new \Exception("The configured bucket name is invalid: " . $this->bucket);
104
-		}
105
-
106
-		if (!$this->connection->doesBucketExist($this->bucket)) {
107
-			$logger = \OC::$server->getLogger();
108
-			try {
109
-				$logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
110
-				$this->connection->createBucket(array(
111
-					'Bucket' => $this->bucket
112
-				));
113
-				$this->testTimeout();
114
-			} catch (S3Exception $e) {
115
-				$logger->logException($e, [
116
-					'message' => 'Invalid remote storage.',
117
-					'level' => ILogger::DEBUG,
118
-					'app' => 'objectstore',
119
-				]);
120
-				throw new \Exception('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
121
-			}
122
-		}
123
-
124
-		return $this->connection;
125
-	}
126
-
127
-	/**
128
-	 * when running the tests wait to let the buckets catch up
129
-	 */
130
-	private function testTimeout() {
131
-		if ($this->test) {
132
-			sleep($this->timeout);
133
-		}
134
-	}
135
-
136
-	public static function legacySignatureProvider($version, $service, $region) {
137
-		switch ($version) {
138
-			case 'v2':
139
-			case 's3':
140
-				return new S3Signature();
141
-			default:
142
-				return null;
143
-		}
144
-	}
33
+    /** @var array */
34
+    protected $params;
35
+
36
+    /** @var S3Client */
37
+    protected $connection;
38
+
39
+    /** @var string */
40
+    protected $id;
41
+
42
+    /** @var string */
43
+    protected $bucket;
44
+
45
+    /** @var int */
46
+    protected $timeout;
47
+
48
+    protected $test;
49
+
50
+    protected function parseParams($params) {
51
+        if (empty($params['key']) || empty($params['secret']) || empty($params['bucket'])) {
52
+            throw new \Exception("Access Key, Secret and Bucket have to be configured.");
53
+        }
54
+
55
+        $this->id = 'amazon::' . $params['bucket'];
56
+
57
+        $this->test = isset($params['test']);
58
+        $this->bucket = $params['bucket'];
59
+        $this->timeout = !isset($params['timeout']) ? 15 : $params['timeout'];
60
+        $params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
61
+        $params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
62
+        if (!isset($params['port']) || $params['port'] === '') {
63
+            $params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
64
+        }
65
+        $this->params = $params;
66
+    }
67
+
68
+
69
+    /**
70
+     * Returns the connection
71
+     *
72
+     * @return S3Client connected client
73
+     * @throws \Exception if connection could not be made
74
+     */
75
+    protected function getConnection() {
76
+        if (!is_null($this->connection)) {
77
+            return $this->connection;
78
+        }
79
+
80
+        $scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
81
+        $base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
82
+
83
+        $options = [
84
+            'version' => isset($this->params['version']) ? $this->params['version'] : 'latest',
85
+            'credentials' => [
86
+                'key' => $this->params['key'],
87
+                'secret' => $this->params['secret'],
88
+            ],
89
+            'endpoint' => $base_url,
90
+            'region' => $this->params['region'],
91
+            'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
92
+            'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider())
93
+        ];
94
+        if (isset($this->params['proxy'])) {
95
+            $options['request.options'] = ['proxy' => $this->params['proxy']];
96
+        }
97
+        if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
98
+            $options['signature_version'] = 'v2';
99
+        }
100
+        $this->connection = new S3Client($options);
101
+
102
+        if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
103
+            throw new \Exception("The configured bucket name is invalid: " . $this->bucket);
104
+        }
105
+
106
+        if (!$this->connection->doesBucketExist($this->bucket)) {
107
+            $logger = \OC::$server->getLogger();
108
+            try {
109
+                $logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
110
+                $this->connection->createBucket(array(
111
+                    'Bucket' => $this->bucket
112
+                ));
113
+                $this->testTimeout();
114
+            } catch (S3Exception $e) {
115
+                $logger->logException($e, [
116
+                    'message' => 'Invalid remote storage.',
117
+                    'level' => ILogger::DEBUG,
118
+                    'app' => 'objectstore',
119
+                ]);
120
+                throw new \Exception('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
121
+            }
122
+        }
123
+
124
+        return $this->connection;
125
+    }
126
+
127
+    /**
128
+     * when running the tests wait to let the buckets catch up
129
+     */
130
+    private function testTimeout() {
131
+        if ($this->test) {
132
+            sleep($this->timeout);
133
+        }
134
+    }
135
+
136
+    public static function legacySignatureProvider($version, $service, $region) {
137
+        switch ($version) {
138
+            case 'v2':
139
+            case 's3':
140
+                return new S3Signature();
141
+            default:
142
+                return null;
143
+        }
144
+    }
145 145
 }
Please login to merge, or discard this patch.