Completed
Pull Request — master (#4873)
by Joas
35:54 queued 19:42
created
lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php 2 patches
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -63,206 +63,206 @@
 block discarded – undo
63 63
  * check fails
64 64
  */
65 65
 class SecurityMiddleware extends Middleware {
66
-	/** @var INavigationManager */
67
-	private $navigationManager;
68
-	/** @var IRequest */
69
-	private $request;
70
-	/** @var ControllerMethodReflector */
71
-	private $reflector;
72
-	/** @var string */
73
-	private $appName;
74
-	/** @var IURLGenerator */
75
-	private $urlGenerator;
76
-	/** @var ILogger */
77
-	private $logger;
78
-	/** @var ISession */
79
-	private $session;
80
-	/** @var bool */
81
-	private $isLoggedIn;
82
-	/** @var bool */
83
-	private $isAdminUser;
84
-	/** @var ContentSecurityPolicyManager */
85
-	private $contentSecurityPolicyManager;
86
-	/** @var CsrfTokenManager */
87
-	private $csrfTokenManager;
88
-	/** @var ContentSecurityPolicyNonceManager */
89
-	private $cspNonceManager;
66
+    /** @var INavigationManager */
67
+    private $navigationManager;
68
+    /** @var IRequest */
69
+    private $request;
70
+    /** @var ControllerMethodReflector */
71
+    private $reflector;
72
+    /** @var string */
73
+    private $appName;
74
+    /** @var IURLGenerator */
75
+    private $urlGenerator;
76
+    /** @var ILogger */
77
+    private $logger;
78
+    /** @var ISession */
79
+    private $session;
80
+    /** @var bool */
81
+    private $isLoggedIn;
82
+    /** @var bool */
83
+    private $isAdminUser;
84
+    /** @var ContentSecurityPolicyManager */
85
+    private $contentSecurityPolicyManager;
86
+    /** @var CsrfTokenManager */
87
+    private $csrfTokenManager;
88
+    /** @var ContentSecurityPolicyNonceManager */
89
+    private $cspNonceManager;
90 90
 
91
-	/**
92
-	 * @param IRequest $request
93
-	 * @param ControllerMethodReflector $reflector
94
-	 * @param INavigationManager $navigationManager
95
-	 * @param IURLGenerator $urlGenerator
96
-	 * @param ILogger $logger
97
-	 * @param ISession $session
98
-	 * @param string $appName
99
-	 * @param bool $isLoggedIn
100
-	 * @param bool $isAdminUser
101
-	 * @param ContentSecurityPolicyManager $contentSecurityPolicyManager
102
-	 * @param CSRFTokenManager $csrfTokenManager
103
-	 * @param ContentSecurityPolicyNonceManager $cspNonceManager
104
-	 */
105
-	public function __construct(IRequest $request,
106
-								ControllerMethodReflector $reflector,
107
-								INavigationManager $navigationManager,
108
-								IURLGenerator $urlGenerator,
109
-								ILogger $logger,
110
-								ISession $session,
111
-								$appName,
112
-								$isLoggedIn,
113
-								$isAdminUser,
114
-								ContentSecurityPolicyManager $contentSecurityPolicyManager,
115
-								CsrfTokenManager $csrfTokenManager,
116
-								ContentSecurityPolicyNonceManager $cspNonceManager) {
117
-		$this->navigationManager = $navigationManager;
118
-		$this->request = $request;
119
-		$this->reflector = $reflector;
120
-		$this->appName = $appName;
121
-		$this->urlGenerator = $urlGenerator;
122
-		$this->logger = $logger;
123
-		$this->session = $session;
124
-		$this->isLoggedIn = $isLoggedIn;
125
-		$this->isAdminUser = $isAdminUser;
126
-		$this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
127
-		$this->csrfTokenManager = $csrfTokenManager;
128
-		$this->cspNonceManager = $cspNonceManager;
129
-	}
91
+    /**
92
+     * @param IRequest $request
93
+     * @param ControllerMethodReflector $reflector
94
+     * @param INavigationManager $navigationManager
95
+     * @param IURLGenerator $urlGenerator
96
+     * @param ILogger $logger
97
+     * @param ISession $session
98
+     * @param string $appName
99
+     * @param bool $isLoggedIn
100
+     * @param bool $isAdminUser
101
+     * @param ContentSecurityPolicyManager $contentSecurityPolicyManager
102
+     * @param CSRFTokenManager $csrfTokenManager
103
+     * @param ContentSecurityPolicyNonceManager $cspNonceManager
104
+     */
105
+    public function __construct(IRequest $request,
106
+                                ControllerMethodReflector $reflector,
107
+                                INavigationManager $navigationManager,
108
+                                IURLGenerator $urlGenerator,
109
+                                ILogger $logger,
110
+                                ISession $session,
111
+                                $appName,
112
+                                $isLoggedIn,
113
+                                $isAdminUser,
114
+                                ContentSecurityPolicyManager $contentSecurityPolicyManager,
115
+                                CsrfTokenManager $csrfTokenManager,
116
+                                ContentSecurityPolicyNonceManager $cspNonceManager) {
117
+        $this->navigationManager = $navigationManager;
118
+        $this->request = $request;
119
+        $this->reflector = $reflector;
120
+        $this->appName = $appName;
121
+        $this->urlGenerator = $urlGenerator;
122
+        $this->logger = $logger;
123
+        $this->session = $session;
124
+        $this->isLoggedIn = $isLoggedIn;
125
+        $this->isAdminUser = $isAdminUser;
126
+        $this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
127
+        $this->csrfTokenManager = $csrfTokenManager;
128
+        $this->cspNonceManager = $cspNonceManager;
129
+    }
130 130
 
131
-	/**
132
-	 * This runs all the security checks before a method call. The
133
-	 * security checks are determined by inspecting the controller method
134
-	 * annotations
135
-	 * @param Controller $controller the controller
136
-	 * @param string $methodName the name of the method
137
-	 * @throws SecurityException when a security check fails
138
-	 */
139
-	public function beforeController($controller, $methodName) {
131
+    /**
132
+     * This runs all the security checks before a method call. The
133
+     * security checks are determined by inspecting the controller method
134
+     * annotations
135
+     * @param Controller $controller the controller
136
+     * @param string $methodName the name of the method
137
+     * @throws SecurityException when a security check fails
138
+     */
139
+    public function beforeController($controller, $methodName) {
140 140
 
141
-		// this will set the current navigation entry of the app, use this only
142
-		// for normal HTML requests and not for AJAX requests
143
-		$this->navigationManager->setActiveEntry($this->appName);
141
+        // this will set the current navigation entry of the app, use this only
142
+        // for normal HTML requests and not for AJAX requests
143
+        $this->navigationManager->setActiveEntry($this->appName);
144 144
 
145
-		// security checks
146
-		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
147
-		if(!$isPublicPage) {
148
-			if(!$this->isLoggedIn) {
149
-				throw new NotLoggedInException();
150
-			}
145
+        // security checks
146
+        $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
147
+        if(!$isPublicPage) {
148
+            if(!$this->isLoggedIn) {
149
+                throw new NotLoggedInException();
150
+            }
151 151
 
152
-			if(!$this->reflector->hasAnnotation('NoAdminRequired')) {
153
-				if(!$this->isAdminUser) {
154
-					throw new NotAdminException();
155
-				}
156
-			}
157
-		}
152
+            if(!$this->reflector->hasAnnotation('NoAdminRequired')) {
153
+                if(!$this->isAdminUser) {
154
+                    throw new NotAdminException();
155
+                }
156
+            }
157
+        }
158 158
 
159
-		if ($this->reflector->hasAnnotation('PasswordConfirmationRequired')) {
160
-			$lastConfirm = (int) $this->session->get('last-password-confirm');
161
-			if ($lastConfirm < (time() - (30 * 60 + 15))) { // allow 15 seconds delay
162
-				throw new NotConfirmedException();
163
-			}
164
-		}
159
+        if ($this->reflector->hasAnnotation('PasswordConfirmationRequired')) {
160
+            $lastConfirm = (int) $this->session->get('last-password-confirm');
161
+            if ($lastConfirm < (time() - (30 * 60 + 15))) { // allow 15 seconds delay
162
+                throw new NotConfirmedException();
163
+            }
164
+        }
165 165
 
166
-		// Check for strict cookie requirement
167
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
168
-			if(!$this->request->passesStrictCookieCheck()) {
169
-				throw new StrictCookieMissingException();
170
-			}
171
-		}
172
-		// CSRF check - also registers the CSRF token since the session may be closed later
173
-		Util::callRegister();
174
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
175
-			/*
166
+        // Check for strict cookie requirement
167
+        if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
168
+            if(!$this->request->passesStrictCookieCheck()) {
169
+                throw new StrictCookieMissingException();
170
+            }
171
+        }
172
+        // CSRF check - also registers the CSRF token since the session may be closed later
173
+        Util::callRegister();
174
+        if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
175
+            /*
176 176
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
177 177
 			 * hacks around that we have no full token auth in place yet and we
178 178
 			 * do want to offer CSRF checks for web requests.
179 179
 			 */
180
-			if(!$this->request->passesCSRFCheck() && !(
181
-					$controller instanceof OCSController &&
182
-					$this->request->getHeader('OCS-APIREQUEST') === 'true')) {
183
-				throw new CrossSiteRequestForgeryException();
184
-			}
185
-		}
180
+            if(!$this->request->passesCSRFCheck() && !(
181
+                    $controller instanceof OCSController &&
182
+                    $this->request->getHeader('OCS-APIREQUEST') === 'true')) {
183
+                throw new CrossSiteRequestForgeryException();
184
+            }
185
+        }
186 186
 
187
-		/**
188
-		 * FIXME: Use DI once available
189
-		 * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
190
-		 * The getAppPath() check is here since components such as settings also use the AppFramework and
191
-		 * therefore won't pass this check.
192
-		 */
193
-		if(\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) {
194
-			throw new AppNotEnabledException();
195
-		}
187
+        /**
188
+         * FIXME: Use DI once available
189
+         * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
190
+         * The getAppPath() check is here since components such as settings also use the AppFramework and
191
+         * therefore won't pass this check.
192
+         */
193
+        if(\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) {
194
+            throw new AppNotEnabledException();
195
+        }
196 196
 
197
-	}
197
+    }
198 198
 
199
-	/**
200
-	 * Performs the default CSP modifications that may be injected by other
201
-	 * applications
202
-	 *
203
-	 * @param Controller $controller
204
-	 * @param string $methodName
205
-	 * @param Response $response
206
-	 * @return Response
207
-	 */
208
-	public function afterController($controller, $methodName, Response $response) {
209
-		$policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
199
+    /**
200
+     * Performs the default CSP modifications that may be injected by other
201
+     * applications
202
+     *
203
+     * @param Controller $controller
204
+     * @param string $methodName
205
+     * @param Response $response
206
+     * @return Response
207
+     */
208
+    public function afterController($controller, $methodName, Response $response) {
209
+        $policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
210 210
 
211
-		if (get_class($policy) === EmptyContentSecurityPolicy::class) {
212
-			return $response;
213
-		}
211
+        if (get_class($policy) === EmptyContentSecurityPolicy::class) {
212
+            return $response;
213
+        }
214 214
 
215
-		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
216
-		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
215
+        $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
216
+        $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
217 217
 
218
-		if($this->cspNonceManager->browserSupportsCspV3()) {
219
-			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
220
-		}
218
+        if($this->cspNonceManager->browserSupportsCspV3()) {
219
+            $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
220
+        }
221 221
 
222
-		$response->setContentSecurityPolicy($defaultPolicy);
222
+        $response->setContentSecurityPolicy($defaultPolicy);
223 223
 
224
-		return $response;
225
-	}
224
+        return $response;
225
+    }
226 226
 
227
-	/**
228
-	 * If an SecurityException is being caught, ajax requests return a JSON error
229
-	 * response and non ajax requests redirect to the index
230
-	 * @param Controller $controller the controller that is being called
231
-	 * @param string $methodName the name of the method that will be called on
232
-	 *                           the controller
233
-	 * @param \Exception $exception the thrown exception
234
-	 * @throws \Exception the passed in exception if it can't handle it
235
-	 * @return Response a Response object or null in case that the exception could not be handled
236
-	 */
237
-	public function afterException($controller, $methodName, \Exception $exception) {
238
-		if($exception instanceof SecurityException) {
239
-			if($exception instanceof StrictCookieMissingException) {
240
-				return new RedirectResponse(\OC::$WEBROOT);
241
- 			}
242
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
243
-				$response = new JSONResponse(
244
-					array('message' => $exception->getMessage()),
245
-					$exception->getCode()
246
-				);
247
-			} else {
248
-				if($exception instanceof NotLoggedInException) {
249
-					$params = [];
250
-					if (isset($this->request->server['REQUEST_URI'])) {
251
-						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
252
-					}
253
-					$url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
254
-					$response = new RedirectResponse($url);
255
-				} else {
256
-					$response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
257
-					$response->setStatus($exception->getCode());
258
-				}
259
-			}
227
+    /**
228
+     * If an SecurityException is being caught, ajax requests return a JSON error
229
+     * response and non ajax requests redirect to the index
230
+     * @param Controller $controller the controller that is being called
231
+     * @param string $methodName the name of the method that will be called on
232
+     *                           the controller
233
+     * @param \Exception $exception the thrown exception
234
+     * @throws \Exception the passed in exception if it can't handle it
235
+     * @return Response a Response object or null in case that the exception could not be handled
236
+     */
237
+    public function afterException($controller, $methodName, \Exception $exception) {
238
+        if($exception instanceof SecurityException) {
239
+            if($exception instanceof StrictCookieMissingException) {
240
+                return new RedirectResponse(\OC::$WEBROOT);
241
+                }
242
+            if (stripos($this->request->getHeader('Accept'),'html') === false) {
243
+                $response = new JSONResponse(
244
+                    array('message' => $exception->getMessage()),
245
+                    $exception->getCode()
246
+                );
247
+            } else {
248
+                if($exception instanceof NotLoggedInException) {
249
+                    $params = [];
250
+                    if (isset($this->request->server['REQUEST_URI'])) {
251
+                        $params['redirect_url'] = $this->request->server['REQUEST_URI'];
252
+                    }
253
+                    $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
254
+                    $response = new RedirectResponse($url);
255
+                } else {
256
+                    $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
257
+                    $response->setStatus($exception->getCode());
258
+                }
259
+            }
260 260
 
261
-			$this->logger->debug($exception->getMessage());
262
-			return $response;
263
-		}
261
+            $this->logger->debug($exception->getMessage());
262
+            return $response;
263
+        }
264 264
 
265
-		throw $exception;
266
-	}
265
+        throw $exception;
266
+    }
267 267
 
268 268
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
 
145 145
 		// security checks
146 146
 		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
147
-		if(!$isPublicPage) {
148
-			if(!$this->isLoggedIn) {
147
+		if (!$isPublicPage) {
148
+			if (!$this->isLoggedIn) {
149 149
 				throw new NotLoggedInException();
150 150
 			}
151 151
 
152
-			if(!$this->reflector->hasAnnotation('NoAdminRequired')) {
153
-				if(!$this->isAdminUser) {
152
+			if (!$this->reflector->hasAnnotation('NoAdminRequired')) {
153
+				if (!$this->isAdminUser) {
154 154
 					throw new NotAdminException();
155 155
 				}
156 156
 			}
@@ -164,20 +164,20 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 
166 166
 		// Check for strict cookie requirement
167
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
168
-			if(!$this->request->passesStrictCookieCheck()) {
167
+		if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
168
+			if (!$this->request->passesStrictCookieCheck()) {
169 169
 				throw new StrictCookieMissingException();
170 170
 			}
171 171
 		}
172 172
 		// CSRF check - also registers the CSRF token since the session may be closed later
173 173
 		Util::callRegister();
174
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
174
+		if (!$this->reflector->hasAnnotation('NoCSRFRequired')) {
175 175
 			/*
176 176
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
177 177
 			 * hacks around that we have no full token auth in place yet and we
178 178
 			 * do want to offer CSRF checks for web requests.
179 179
 			 */
180
-			if(!$this->request->passesCSRFCheck() && !(
180
+			if (!$this->request->passesCSRFCheck() && !(
181 181
 					$controller instanceof OCSController &&
182 182
 					$this->request->getHeader('OCS-APIREQUEST') === 'true')) {
183 183
 				throw new CrossSiteRequestForgeryException();
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 		 * The getAppPath() check is here since components such as settings also use the AppFramework and
191 191
 		 * therefore won't pass this check.
192 192
 		 */
193
-		if(\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) {
193
+		if (\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) {
194 194
 			throw new AppNotEnabledException();
195 195
 		}
196 196
 
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
 		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
216 216
 		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
217 217
 
218
-		if($this->cspNonceManager->browserSupportsCspV3()) {
218
+		if ($this->cspNonceManager->browserSupportsCspV3()) {
219 219
 			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
220 220
 		}
221 221
 
@@ -235,17 +235,17 @@  discard block
 block discarded – undo
235 235
 	 * @return Response a Response object or null in case that the exception could not be handled
236 236
 	 */
237 237
 	public function afterException($controller, $methodName, \Exception $exception) {
238
-		if($exception instanceof SecurityException) {
239
-			if($exception instanceof StrictCookieMissingException) {
238
+		if ($exception instanceof SecurityException) {
239
+			if ($exception instanceof StrictCookieMissingException) {
240 240
 				return new RedirectResponse(\OC::$WEBROOT);
241 241
  			}
242
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
242
+			if (stripos($this->request->getHeader('Accept'), 'html') === false) {
243 243
 				$response = new JSONResponse(
244 244
 					array('message' => $exception->getMessage()),
245 245
 					$exception->getCode()
246 246
 				);
247 247
 			} else {
248
-				if($exception instanceof NotLoggedInException) {
248
+				if ($exception instanceof NotLoggedInException) {
249 249
 					$params = [];
250 250
 					if (isset($this->request->server['REQUEST_URI'])) {
251 251
 						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
Please login to merge, or discard this patch.
lib/private/Route/Router.php 2 patches
Indentation   +309 added lines, -309 removed lines patch added patch discarded remove patch
@@ -45,339 +45,339 @@
 block discarded – undo
45 45
 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
46 46
 
47 47
 class Router implements IRouter {
48
-	/** @var RouteCollection[] */
49
-	protected $collections = [];
50
-	/** @var null|RouteCollection */
51
-	protected $collection = null;
52
-	/** @var null|string */
53
-	protected $collectionName = null;
54
-	/** @var null|RouteCollection */
55
-	protected $root = null;
56
-	/** @var null|UrlGenerator */
57
-	protected $generator = null;
58
-	/** @var string[] */
59
-	protected $routingFiles;
60
-	/** @var bool */
61
-	protected $loaded = false;
62
-	/** @var array */
63
-	protected $loadedApps = [];
64
-	/** @var ILogger */
65
-	protected $logger;
66
-	/** @var RequestContext */
67
-	protected $context;
48
+    /** @var RouteCollection[] */
49
+    protected $collections = [];
50
+    /** @var null|RouteCollection */
51
+    protected $collection = null;
52
+    /** @var null|string */
53
+    protected $collectionName = null;
54
+    /** @var null|RouteCollection */
55
+    protected $root = null;
56
+    /** @var null|UrlGenerator */
57
+    protected $generator = null;
58
+    /** @var string[] */
59
+    protected $routingFiles;
60
+    /** @var bool */
61
+    protected $loaded = false;
62
+    /** @var array */
63
+    protected $loadedApps = [];
64
+    /** @var ILogger */
65
+    protected $logger;
66
+    /** @var RequestContext */
67
+    protected $context;
68 68
 
69
-	/**
70
-	 * @param ILogger $logger
71
-	 */
72
-	public function __construct(ILogger $logger) {
73
-		$this->logger = $logger;
74
-		$baseUrl = \OC::$WEBROOT;
75
-		if(!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) {
76
-			$baseUrl = \OC::$server->getURLGenerator()->linkTo('', 'index.php');
77
-		}
78
-		if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) {
79
-			$method = $_SERVER['REQUEST_METHOD'];
80
-		} else {
81
-			$method = 'GET';
82
-		}
83
-		$request = \OC::$server->getRequest();
84
-		$host = $request->getServerHost();
85
-		$schema = $request->getServerProtocol();
86
-		$this->context = new RequestContext($baseUrl, $method, $host, $schema);
87
-		// TODO cache
88
-		$this->root = $this->getCollection('root');
89
-	}
69
+    /**
70
+     * @param ILogger $logger
71
+     */
72
+    public function __construct(ILogger $logger) {
73
+        $this->logger = $logger;
74
+        $baseUrl = \OC::$WEBROOT;
75
+        if(!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) {
76
+            $baseUrl = \OC::$server->getURLGenerator()->linkTo('', 'index.php');
77
+        }
78
+        if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) {
79
+            $method = $_SERVER['REQUEST_METHOD'];
80
+        } else {
81
+            $method = 'GET';
82
+        }
83
+        $request = \OC::$server->getRequest();
84
+        $host = $request->getServerHost();
85
+        $schema = $request->getServerProtocol();
86
+        $this->context = new RequestContext($baseUrl, $method, $host, $schema);
87
+        // TODO cache
88
+        $this->root = $this->getCollection('root');
89
+    }
90 90
 
91
-	/**
92
-	 * Get the files to load the routes from
93
-	 *
94
-	 * @return string[]
95
-	 */
96
-	public function getRoutingFiles() {
97
-		if (!isset($this->routingFiles)) {
98
-			$this->routingFiles = [];
99
-			foreach (\OC_APP::getEnabledApps() as $app) {
100
-				$appPath = \OC_App::getAppPath($app);
101
-				if($appPath !== false) {
102
-					$file = $appPath . '/appinfo/routes.php';
103
-					if (file_exists($file)) {
104
-						$this->routingFiles[$app] = $file;
105
-					}
106
-				}
107
-			}
108
-		}
109
-		return $this->routingFiles;
110
-	}
91
+    /**
92
+     * Get the files to load the routes from
93
+     *
94
+     * @return string[]
95
+     */
96
+    public function getRoutingFiles() {
97
+        if (!isset($this->routingFiles)) {
98
+            $this->routingFiles = [];
99
+            foreach (\OC_APP::getEnabledApps() as $app) {
100
+                $appPath = \OC_App::getAppPath($app);
101
+                if($appPath !== false) {
102
+                    $file = $appPath . '/appinfo/routes.php';
103
+                    if (file_exists($file)) {
104
+                        $this->routingFiles[$app] = $file;
105
+                    }
106
+                }
107
+            }
108
+        }
109
+        return $this->routingFiles;
110
+    }
111 111
 
112
-	/**
113
-	 * Loads the routes
114
-	 *
115
-	 * @param null|string $app
116
-	 */
117
-	public function loadRoutes($app = null) {
118
-		if(is_string($app)) {
119
-			$app = \OC_App::cleanAppId($app);
120
-		}
112
+    /**
113
+     * Loads the routes
114
+     *
115
+     * @param null|string $app
116
+     */
117
+    public function loadRoutes($app = null) {
118
+        if(is_string($app)) {
119
+            $app = \OC_App::cleanAppId($app);
120
+        }
121 121
 
122
-		$requestedApp = $app;
123
-		if ($this->loaded) {
124
-			return;
125
-		}
126
-		if (is_null($app)) {
127
-			$this->loaded = true;
128
-			$routingFiles = $this->getRoutingFiles();
129
-		} else {
130
-			if (isset($this->loadedApps[$app])) {
131
-				return;
132
-			}
133
-			$file = \OC_App::getAppPath($app) . '/appinfo/routes.php';
134
-			if ($file !== false && file_exists($file)) {
135
-				$routingFiles = [$app => $file];
136
-			} else {
137
-				$routingFiles = [];
138
-			}
139
-		}
140
-		\OC::$server->getEventLogger()->start('loadroutes' . $requestedApp, 'Loading Routes');
141
-		foreach ($routingFiles as $app => $file) {
142
-			if (!isset($this->loadedApps[$app])) {
143
-				if (!\OC_App::isAppLoaded($app)) {
144
-					// app MUST be loaded before app routes
145
-					// try again next time loadRoutes() is called
146
-					$this->loaded = false;
147
-					continue;
148
-				}
149
-				$this->loadedApps[$app] = true;
150
-				$this->useCollection($app);
151
-				$this->requireRouteFile($file, $app);
152
-				$collection = $this->getCollection($app);
153
-				$collection->addPrefix('/apps/' . $app);
154
-				$this->root->addCollection($collection);
122
+        $requestedApp = $app;
123
+        if ($this->loaded) {
124
+            return;
125
+        }
126
+        if (is_null($app)) {
127
+            $this->loaded = true;
128
+            $routingFiles = $this->getRoutingFiles();
129
+        } else {
130
+            if (isset($this->loadedApps[$app])) {
131
+                return;
132
+            }
133
+            $file = \OC_App::getAppPath($app) . '/appinfo/routes.php';
134
+            if ($file !== false && file_exists($file)) {
135
+                $routingFiles = [$app => $file];
136
+            } else {
137
+                $routingFiles = [];
138
+            }
139
+        }
140
+        \OC::$server->getEventLogger()->start('loadroutes' . $requestedApp, 'Loading Routes');
141
+        foreach ($routingFiles as $app => $file) {
142
+            if (!isset($this->loadedApps[$app])) {
143
+                if (!\OC_App::isAppLoaded($app)) {
144
+                    // app MUST be loaded before app routes
145
+                    // try again next time loadRoutes() is called
146
+                    $this->loaded = false;
147
+                    continue;
148
+                }
149
+                $this->loadedApps[$app] = true;
150
+                $this->useCollection($app);
151
+                $this->requireRouteFile($file, $app);
152
+                $collection = $this->getCollection($app);
153
+                $collection->addPrefix('/apps/' . $app);
154
+                $this->root->addCollection($collection);
155 155
 
156
-				// Also add the OCS collection
157
-				$collection = $this->getCollection($app.'.ocs');
158
-				$collection->addPrefix('/ocsapp');
159
-				$this->root->addCollection($collection);
160
-			}
161
-		}
162
-		if (!isset($this->loadedApps['core'])) {
163
-			$this->loadedApps['core'] = true;
164
-			$this->useCollection('root');
165
-			require_once __DIR__ . '/../../../settings/routes.php';
166
-			require_once __DIR__ . '/../../../core/routes.php';
156
+                // Also add the OCS collection
157
+                $collection = $this->getCollection($app.'.ocs');
158
+                $collection->addPrefix('/ocsapp');
159
+                $this->root->addCollection($collection);
160
+            }
161
+        }
162
+        if (!isset($this->loadedApps['core'])) {
163
+            $this->loadedApps['core'] = true;
164
+            $this->useCollection('root');
165
+            require_once __DIR__ . '/../../../settings/routes.php';
166
+            require_once __DIR__ . '/../../../core/routes.php';
167 167
 
168
-			// Also add the OCS collection
169
-			$collection = $this->getCollection('root.ocs');
170
-			$collection->addPrefix('/ocsapp');
171
-			$this->root->addCollection($collection);
172
-		}
173
-		if ($this->loaded) {
174
-			// include ocs routes, must be loaded last for /ocs prefix
175
-			require_once __DIR__ . '/../../../ocs/routes.php';
176
-			$collection = $this->getCollection('ocs');
177
-			$collection->addPrefix('/ocs');
178
-			$this->root->addCollection($collection);
179
-		}
180
-		\OC::$server->getEventLogger()->end('loadroutes' . $requestedApp);
181
-	}
168
+            // Also add the OCS collection
169
+            $collection = $this->getCollection('root.ocs');
170
+            $collection->addPrefix('/ocsapp');
171
+            $this->root->addCollection($collection);
172
+        }
173
+        if ($this->loaded) {
174
+            // include ocs routes, must be loaded last for /ocs prefix
175
+            require_once __DIR__ . '/../../../ocs/routes.php';
176
+            $collection = $this->getCollection('ocs');
177
+            $collection->addPrefix('/ocs');
178
+            $this->root->addCollection($collection);
179
+        }
180
+        \OC::$server->getEventLogger()->end('loadroutes' . $requestedApp);
181
+    }
182 182
 
183
-	/**
184
-	 * @return string
185
-	 * @deprecated
186
-	 */
187
-	public function getCacheKey() {
188
-		return '';
189
-	}
183
+    /**
184
+     * @return string
185
+     * @deprecated
186
+     */
187
+    public function getCacheKey() {
188
+        return '';
189
+    }
190 190
 
191
-	/**
192
-	 * @param string $name
193
-	 * @return \Symfony\Component\Routing\RouteCollection
194
-	 */
195
-	protected function getCollection($name) {
196
-		if (!isset($this->collections[$name])) {
197
-			$this->collections[$name] = new RouteCollection();
198
-		}
199
-		return $this->collections[$name];
200
-	}
191
+    /**
192
+     * @param string $name
193
+     * @return \Symfony\Component\Routing\RouteCollection
194
+     */
195
+    protected function getCollection($name) {
196
+        if (!isset($this->collections[$name])) {
197
+            $this->collections[$name] = new RouteCollection();
198
+        }
199
+        return $this->collections[$name];
200
+    }
201 201
 
202
-	/**
203
-	 * Sets the collection to use for adding routes
204
-	 *
205
-	 * @param string $name Name of the collection to use.
206
-	 * @return void
207
-	 */
208
-	public function useCollection($name) {
209
-		$this->collection = $this->getCollection($name);
210
-		$this->collectionName = $name;
211
-	}
202
+    /**
203
+     * Sets the collection to use for adding routes
204
+     *
205
+     * @param string $name Name of the collection to use.
206
+     * @return void
207
+     */
208
+    public function useCollection($name) {
209
+        $this->collection = $this->getCollection($name);
210
+        $this->collectionName = $name;
211
+    }
212 212
 
213
-	/**
214
-	 * returns the current collection name in use for adding routes
215
-	 *
216
-	 * @return string the collection name
217
-	 */
218
-	public function getCurrentCollection() {
219
-		return $this->collectionName;
220
-	}
213
+    /**
214
+     * returns the current collection name in use for adding routes
215
+     *
216
+     * @return string the collection name
217
+     */
218
+    public function getCurrentCollection() {
219
+        return $this->collectionName;
220
+    }
221 221
 
222 222
 
223
-	/**
224
-	 * Create a \OC\Route\Route.
225
-	 *
226
-	 * @param string $name Name of the route to create.
227
-	 * @param string $pattern The pattern to match
228
-	 * @param array $defaults An array of default parameter values
229
-	 * @param array $requirements An array of requirements for parameters (regexes)
230
-	 * @return \OC\Route\Route
231
-	 */
232
-	public function create($name,
233
-						   $pattern,
234
-						   array $defaults = [],
235
-						   array $requirements = []) {
236
-		$route = new Route($pattern, $defaults, $requirements);
237
-		$this->collection->add($name, $route);
238
-		return $route;
239
-	}
223
+    /**
224
+     * Create a \OC\Route\Route.
225
+     *
226
+     * @param string $name Name of the route to create.
227
+     * @param string $pattern The pattern to match
228
+     * @param array $defaults An array of default parameter values
229
+     * @param array $requirements An array of requirements for parameters (regexes)
230
+     * @return \OC\Route\Route
231
+     */
232
+    public function create($name,
233
+                            $pattern,
234
+                            array $defaults = [],
235
+                            array $requirements = []) {
236
+        $route = new Route($pattern, $defaults, $requirements);
237
+        $this->collection->add($name, $route);
238
+        return $route;
239
+    }
240 240
 
241
-	/**
242
-	 * Find the route matching $url
243
-	 *
244
-	 * @param string $url The url to find
245
-	 * @throws \Exception
246
-	 * @return void
247
-	 */
248
-	public function match($url) {
249
-		if (substr($url, 0, 6) === '/apps/') {
250
-			// empty string / 'apps' / $app / rest of the route
251
-			list(, , $app,) = explode('/', $url, 4);
241
+    /**
242
+     * Find the route matching $url
243
+     *
244
+     * @param string $url The url to find
245
+     * @throws \Exception
246
+     * @return void
247
+     */
248
+    public function match($url) {
249
+        if (substr($url, 0, 6) === '/apps/') {
250
+            // empty string / 'apps' / $app / rest of the route
251
+            list(, , $app,) = explode('/', $url, 4);
252 252
 
253
-			$app = \OC_App::cleanAppId($app);
254
-			\OC::$REQUESTEDAPP = $app;
255
-			$this->loadRoutes($app);
256
-		} else if (substr($url, 0, 13) === '/ocsapp/apps/') {
257
-			// empty string / 'ocsapp' / 'apps' / $app / rest of the route
258
-			list(, , , $app,) = explode('/', $url, 5);
253
+            $app = \OC_App::cleanAppId($app);
254
+            \OC::$REQUESTEDAPP = $app;
255
+            $this->loadRoutes($app);
256
+        } else if (substr($url, 0, 13) === '/ocsapp/apps/') {
257
+            // empty string / 'ocsapp' / 'apps' / $app / rest of the route
258
+            list(, , , $app,) = explode('/', $url, 5);
259 259
 
260
-			$app = \OC_App::cleanAppId($app);
261
-			\OC::$REQUESTEDAPP = $app;
262
-			$this->loadRoutes($app);
263
-		} else if (substr($url, 0, 6) === '/core/' or substr($url, 0, 10) === '/settings/') {
264
-			\OC::$REQUESTEDAPP = $url;
265
-			if (!\OC::$server->getConfig()->getSystemValue('maintenance', false) && !Util::needUpgrade()) {
266
-				\OC_App::loadApps();
267
-			}
268
-			$this->loadRoutes('core');
269
-		} else {
270
-			$this->loadRoutes();
271
-		}
260
+            $app = \OC_App::cleanAppId($app);
261
+            \OC::$REQUESTEDAPP = $app;
262
+            $this->loadRoutes($app);
263
+        } else if (substr($url, 0, 6) === '/core/' or substr($url, 0, 10) === '/settings/') {
264
+            \OC::$REQUESTEDAPP = $url;
265
+            if (!\OC::$server->getConfig()->getSystemValue('maintenance', false) && !Util::needUpgrade()) {
266
+                \OC_App::loadApps();
267
+            }
268
+            $this->loadRoutes('core');
269
+        } else {
270
+            $this->loadRoutes();
271
+        }
272 272
 
273
-		$matcher = new UrlMatcher($this->root, $this->context);
274
-		try {
275
-			$parameters = $matcher->match($url);
276
-		} catch (ResourceNotFoundException $e) {
277
-			if (substr($url, -1) !== '/') {
278
-				// We allow links to apps/files? for backwards compatibility reasons
279
-				// However, since Symfony does not allow empty route names, the route
280
-				// we need to match is '/', so we need to append the '/' here.
281
-				try {
282
-					$parameters = $matcher->match($url . '/');
283
-				} catch (ResourceNotFoundException $newException) {
284
-					// If we still didn't match a route, we throw the original exception
285
-					throw $e;
286
-				}
287
-			} else {
288
-				throw $e;
289
-			}
290
-		}
273
+        $matcher = new UrlMatcher($this->root, $this->context);
274
+        try {
275
+            $parameters = $matcher->match($url);
276
+        } catch (ResourceNotFoundException $e) {
277
+            if (substr($url, -1) !== '/') {
278
+                // We allow links to apps/files? for backwards compatibility reasons
279
+                // However, since Symfony does not allow empty route names, the route
280
+                // we need to match is '/', so we need to append the '/' here.
281
+                try {
282
+                    $parameters = $matcher->match($url . '/');
283
+                } catch (ResourceNotFoundException $newException) {
284
+                    // If we still didn't match a route, we throw the original exception
285
+                    throw $e;
286
+                }
287
+            } else {
288
+                throw $e;
289
+            }
290
+        }
291 291
 
292
-		\OC::$server->getEventLogger()->start('run_route', 'Run route');
293
-		if (isset($parameters['action'])) {
294
-			$action = $parameters['action'];
295
-			if (!is_callable($action)) {
296
-				throw new \Exception('not a callable action');
297
-			}
298
-			unset($parameters['action']);
299
-			call_user_func($action, $parameters);
300
-		} elseif (isset($parameters['file'])) {
301
-			include $parameters['file'];
302
-		} else {
303
-			throw new \Exception('no action available');
304
-		}
305
-		\OC::$server->getEventLogger()->end('run_route');
306
-	}
292
+        \OC::$server->getEventLogger()->start('run_route', 'Run route');
293
+        if (isset($parameters['action'])) {
294
+            $action = $parameters['action'];
295
+            if (!is_callable($action)) {
296
+                throw new \Exception('not a callable action');
297
+            }
298
+            unset($parameters['action']);
299
+            call_user_func($action, $parameters);
300
+        } elseif (isset($parameters['file'])) {
301
+            include $parameters['file'];
302
+        } else {
303
+            throw new \Exception('no action available');
304
+        }
305
+        \OC::$server->getEventLogger()->end('run_route');
306
+    }
307 307
 
308
-	/**
309
-	 * Get the url generator
310
-	 *
311
-	 * @return \Symfony\Component\Routing\Generator\UrlGenerator
312
-	 *
313
-	 */
314
-	public function getGenerator() {
315
-		if (null !== $this->generator) {
316
-			return $this->generator;
317
-		}
308
+    /**
309
+     * Get the url generator
310
+     *
311
+     * @return \Symfony\Component\Routing\Generator\UrlGenerator
312
+     *
313
+     */
314
+    public function getGenerator() {
315
+        if (null !== $this->generator) {
316
+            return $this->generator;
317
+        }
318 318
 
319
-		return $this->generator = new UrlGenerator($this->root, $this->context);
320
-	}
319
+        return $this->generator = new UrlGenerator($this->root, $this->context);
320
+    }
321 321
 
322
-	/**
323
-	 * Generate url based on $name and $parameters
324
-	 *
325
-	 * @param string $name Name of the route to use.
326
-	 * @param array $parameters Parameters for the route
327
-	 * @param bool $absolute
328
-	 * @return string
329
-	 */
330
-	public function generate($name,
331
-							 $parameters = [],
332
-							 $absolute = false) {
333
-		$this->loadRoutes();
334
-		try {
335
-			$referenceType = UrlGenerator::ABSOLUTE_URL;
336
-			if ($absolute === false) {
337
-				$referenceType = UrlGenerator::ABSOLUTE_PATH;
338
-			}
339
-			return $this->getGenerator()->generate($name, $parameters, $referenceType);
340
-		} catch (RouteNotFoundException $e) {
341
-			$this->logger->logException($e);
342
-			return '';
343
-		}
344
-	}
322
+    /**
323
+     * Generate url based on $name and $parameters
324
+     *
325
+     * @param string $name Name of the route to use.
326
+     * @param array $parameters Parameters for the route
327
+     * @param bool $absolute
328
+     * @return string
329
+     */
330
+    public function generate($name,
331
+                                $parameters = [],
332
+                                $absolute = false) {
333
+        $this->loadRoutes();
334
+        try {
335
+            $referenceType = UrlGenerator::ABSOLUTE_URL;
336
+            if ($absolute === false) {
337
+                $referenceType = UrlGenerator::ABSOLUTE_PATH;
338
+            }
339
+            return $this->getGenerator()->generate($name, $parameters, $referenceType);
340
+        } catch (RouteNotFoundException $e) {
341
+            $this->logger->logException($e);
342
+            return '';
343
+        }
344
+    }
345 345
 
346
-	/**
347
-	 * To isolate the variable scope used inside the $file it is required in it's own method
348
-	 *
349
-	 * @param string $file the route file location to include
350
-	 * @param string $appName
351
-	 */
352
-	private function requireRouteFile($file, $appName) {
353
-		$this->setupRoutes(include_once $file, $appName);
354
-	}
346
+    /**
347
+     * To isolate the variable scope used inside the $file it is required in it's own method
348
+     *
349
+     * @param string $file the route file location to include
350
+     * @param string $appName
351
+     */
352
+    private function requireRouteFile($file, $appName) {
353
+        $this->setupRoutes(include_once $file, $appName);
354
+    }
355 355
 
356 356
 
357
-	/**
358
-	 * If a routes.php file returns an array, try to set up the application and
359
-	 * register the routes for the app. The application class will be chosen by
360
-	 * camelcasing the appname, e.g.: my_app will be turned into
361
-	 * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
362
-	 * App will be intialized. This makes it optional to ship an
363
-	 * appinfo/application.php by using the built in query resolver
364
-	 *
365
-	 * @param array $routes the application routes
366
-	 * @param string $appName the name of the app.
367
-	 */
368
-	private function setupRoutes($routes, $appName) {
369
-		if (is_array($routes)) {
370
-			$appNameSpace = App::buildAppNamespace($appName);
357
+    /**
358
+     * If a routes.php file returns an array, try to set up the application and
359
+     * register the routes for the app. The application class will be chosen by
360
+     * camelcasing the appname, e.g.: my_app will be turned into
361
+     * \OCA\MyApp\AppInfo\Application. If that class does not exist, a default
362
+     * App will be intialized. This makes it optional to ship an
363
+     * appinfo/application.php by using the built in query resolver
364
+     *
365
+     * @param array $routes the application routes
366
+     * @param string $appName the name of the app.
367
+     */
368
+    private function setupRoutes($routes, $appName) {
369
+        if (is_array($routes)) {
370
+            $appNameSpace = App::buildAppNamespace($appName);
371 371
 
372
-			$applicationClassName = $appNameSpace . '\\AppInfo\\Application';
372
+            $applicationClassName = $appNameSpace . '\\AppInfo\\Application';
373 373
 
374
-			if (class_exists($applicationClassName)) {
375
-				$application = new $applicationClassName();
376
-			} else {
377
-				$application = new App($appName);
378
-			}
374
+            if (class_exists($applicationClassName)) {
375
+                $application = new $applicationClassName();
376
+            } else {
377
+                $application = new App($appName);
378
+            }
379 379
 
380
-			$application->registerRoutes($this, $routes);
381
-		}
382
-	}
380
+            $application->registerRoutes($this, $routes);
381
+        }
382
+    }
383 383
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	public function __construct(ILogger $logger) {
73 73
 		$this->logger = $logger;
74 74
 		$baseUrl = \OC::$WEBROOT;
75
-		if(!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) {
75
+		if (!(\OC::$server->getConfig()->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true')) {
76 76
 			$baseUrl = \OC::$server->getURLGenerator()->linkTo('', 'index.php');
77 77
 		}
78 78
 		if (!\OC::$CLI && isset($_SERVER['REQUEST_METHOD'])) {
@@ -98,8 +98,8 @@  discard block
 block discarded – undo
98 98
 			$this->routingFiles = [];
99 99
 			foreach (\OC_APP::getEnabledApps() as $app) {
100 100
 				$appPath = \OC_App::getAppPath($app);
101
-				if($appPath !== false) {
102
-					$file = $appPath . '/appinfo/routes.php';
101
+				if ($appPath !== false) {
102
+					$file = $appPath.'/appinfo/routes.php';
103 103
 					if (file_exists($file)) {
104 104
 						$this->routingFiles[$app] = $file;
105 105
 					}
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 	 * @param null|string $app
116 116
 	 */
117 117
 	public function loadRoutes($app = null) {
118
-		if(is_string($app)) {
118
+		if (is_string($app)) {
119 119
 			$app = \OC_App::cleanAppId($app);
120 120
 		}
121 121
 
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
 			if (isset($this->loadedApps[$app])) {
131 131
 				return;
132 132
 			}
133
-			$file = \OC_App::getAppPath($app) . '/appinfo/routes.php';
133
+			$file = \OC_App::getAppPath($app).'/appinfo/routes.php';
134 134
 			if ($file !== false && file_exists($file)) {
135 135
 				$routingFiles = [$app => $file];
136 136
 			} else {
137 137
 				$routingFiles = [];
138 138
 			}
139 139
 		}
140
-		\OC::$server->getEventLogger()->start('loadroutes' . $requestedApp, 'Loading Routes');
140
+		\OC::$server->getEventLogger()->start('loadroutes'.$requestedApp, 'Loading Routes');
141 141
 		foreach ($routingFiles as $app => $file) {
142 142
 			if (!isset($this->loadedApps[$app])) {
143 143
 				if (!\OC_App::isAppLoaded($app)) {
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 				$this->useCollection($app);
151 151
 				$this->requireRouteFile($file, $app);
152 152
 				$collection = $this->getCollection($app);
153
-				$collection->addPrefix('/apps/' . $app);
153
+				$collection->addPrefix('/apps/'.$app);
154 154
 				$this->root->addCollection($collection);
155 155
 
156 156
 				// Also add the OCS collection
@@ -162,8 +162,8 @@  discard block
 block discarded – undo
162 162
 		if (!isset($this->loadedApps['core'])) {
163 163
 			$this->loadedApps['core'] = true;
164 164
 			$this->useCollection('root');
165
-			require_once __DIR__ . '/../../../settings/routes.php';
166
-			require_once __DIR__ . '/../../../core/routes.php';
165
+			require_once __DIR__.'/../../../settings/routes.php';
166
+			require_once __DIR__.'/../../../core/routes.php';
167 167
 
168 168
 			// Also add the OCS collection
169 169
 			$collection = $this->getCollection('root.ocs');
@@ -172,12 +172,12 @@  discard block
 block discarded – undo
172 172
 		}
173 173
 		if ($this->loaded) {
174 174
 			// include ocs routes, must be loaded last for /ocs prefix
175
-			require_once __DIR__ . '/../../../ocs/routes.php';
175
+			require_once __DIR__.'/../../../ocs/routes.php';
176 176
 			$collection = $this->getCollection('ocs');
177 177
 			$collection->addPrefix('/ocs');
178 178
 			$this->root->addCollection($collection);
179 179
 		}
180
-		\OC::$server->getEventLogger()->end('loadroutes' . $requestedApp);
180
+		\OC::$server->getEventLogger()->end('loadroutes'.$requestedApp);
181 181
 	}
182 182
 
183 183
 	/**
@@ -248,14 +248,14 @@  discard block
 block discarded – undo
248 248
 	public function match($url) {
249 249
 		if (substr($url, 0, 6) === '/apps/') {
250 250
 			// empty string / 'apps' / $app / rest of the route
251
-			list(, , $app,) = explode('/', $url, 4);
251
+			list(,, $app,) = explode('/', $url, 4);
252 252
 
253 253
 			$app = \OC_App::cleanAppId($app);
254 254
 			\OC::$REQUESTEDAPP = $app;
255 255
 			$this->loadRoutes($app);
256 256
 		} else if (substr($url, 0, 13) === '/ocsapp/apps/') {
257 257
 			// empty string / 'ocsapp' / 'apps' / $app / rest of the route
258
-			list(, , , $app,) = explode('/', $url, 5);
258
+			list(,,, $app,) = explode('/', $url, 5);
259 259
 
260 260
 			$app = \OC_App::cleanAppId($app);
261 261
 			\OC::$REQUESTEDAPP = $app;
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 				// However, since Symfony does not allow empty route names, the route
280 280
 				// we need to match is '/', so we need to append the '/' here.
281 281
 				try {
282
-					$parameters = $matcher->match($url . '/');
282
+					$parameters = $matcher->match($url.'/');
283 283
 				} catch (ResourceNotFoundException $newException) {
284 284
 					// If we still didn't match a route, we throw the original exception
285 285
 					throw $e;
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 		if (is_array($routes)) {
370 370
 			$appNameSpace = App::buildAppNamespace($appName);
371 371
 
372
-			$applicationClassName = $appNameSpace . '\\AppInfo\\Application';
372
+			$applicationClassName = $appNameSpace.'\\AppInfo\\Application';
373 373
 
374 374
 			if (class_exists($applicationClassName)) {
375 375
 				$application = new $applicationClassName();
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +1018 added lines, -1018 removed lines patch added patch discarded remove patch
@@ -59,1024 +59,1024 @@
 block discarded – undo
59 59
  * OC_autoload!
60 60
  */
61 61
 class OC {
62
-	/**
63
-	 * Associative array for autoloading. classname => filename
64
-	 */
65
-	public static $CLASSPATH = array();
66
-	/**
67
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
68
-	 */
69
-	public static $SERVERROOT = '';
70
-	/**
71
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
72
-	 */
73
-	private static $SUBURI = '';
74
-	/**
75
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
76
-	 */
77
-	public static $WEBROOT = '';
78
-	/**
79
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
80
-	 * web path in 'url'
81
-	 */
82
-	public static $APPSROOTS = array();
83
-
84
-	/**
85
-	 * @var string
86
-	 */
87
-	public static $configDir;
88
-
89
-	/**
90
-	 * requested app
91
-	 */
92
-	public static $REQUESTEDAPP = '';
93
-
94
-	/**
95
-	 * check if Nextcloud runs in cli mode
96
-	 */
97
-	public static $CLI = false;
98
-
99
-	/**
100
-	 * @var \OC\Autoloader $loader
101
-	 */
102
-	public static $loader = null;
103
-
104
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
105
-	public static $composerAutoloader = null;
106
-
107
-	/**
108
-	 * @var \OC\Server
109
-	 */
110
-	public static $server = null;
111
-
112
-	/**
113
-	 * @var \OC\Config
114
-	 */
115
-	private static $config = null;
116
-
117
-	/**
118
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
119
-	 * the app path list is empty or contains an invalid path
120
-	 */
121
-	public static function initPaths() {
122
-		if(defined('PHPUNIT_CONFIG_DIR')) {
123
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
-			self::$configDir = rtrim($dir, '/') . '/';
128
-		} else {
129
-			self::$configDir = OC::$SERVERROOT . '/config/';
130
-		}
131
-		self::$config = new \OC\Config(self::$configDir);
132
-
133
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
134
-		/**
135
-		 * FIXME: The following lines are required because we can't yet instantiate
136
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
137
-		 */
138
-		$params = [
139
-			'server' => [
140
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
141
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
142
-			],
143
-		];
144
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
145
-		$scriptName = $fakeRequest->getScriptName();
146
-		if (substr($scriptName, -1) == '/') {
147
-			$scriptName .= 'index.php';
148
-			//make sure suburi follows the same rules as scriptName
149
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
150
-				if (substr(OC::$SUBURI, -1) != '/') {
151
-					OC::$SUBURI = OC::$SUBURI . '/';
152
-				}
153
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
154
-			}
155
-		}
156
-
157
-
158
-		if (OC::$CLI) {
159
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
160
-		} else {
161
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
162
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163
-
164
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
166
-				}
167
-			} else {
168
-				// The scriptName is not ending with OC::$SUBURI
169
-				// This most likely means that we are calling from CLI.
170
-				// However some cron jobs still need to generate
171
-				// a web URL, so we use overwritewebroot as a fallback.
172
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
173
-			}
174
-
175
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
176
-			// slash which is required by URL generation.
177
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
178
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
179
-				header('Location: '.\OC::$WEBROOT.'/');
180
-				exit();
181
-			}
182
-		}
183
-
184
-		// search the apps folder
185
-		$config_paths = self::$config->getValue('apps_paths', array());
186
-		if (!empty($config_paths)) {
187
-			foreach ($config_paths as $paths) {
188
-				if (isset($paths['url']) && isset($paths['path'])) {
189
-					$paths['url'] = rtrim($paths['url'], '/');
190
-					$paths['path'] = rtrim($paths['path'], '/');
191
-					OC::$APPSROOTS[] = $paths;
192
-				}
193
-			}
194
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
-			OC::$APPSROOTS[] = array(
198
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
199
-				'url' => '/apps',
200
-				'writable' => true
201
-			);
202
-		}
203
-
204
-		if (empty(OC::$APPSROOTS)) {
205
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
206
-				. ' or the folder above. You can also configure the location in the config.php file.');
207
-		}
208
-		$paths = array();
209
-		foreach (OC::$APPSROOTS as $path) {
210
-			$paths[] = $path['path'];
211
-			if (!is_dir($path['path'])) {
212
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
213
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
214
-					. ' config.php file.', $path['path']));
215
-			}
216
-		}
217
-
218
-		// set the right include path
219
-		set_include_path(
220
-			implode(PATH_SEPARATOR, $paths)
221
-		);
222
-	}
223
-
224
-	public static function checkConfig() {
225
-		$l = \OC::$server->getL10N('lib');
226
-
227
-		// Create config if it does not already exist
228
-		$configFilePath = self::$configDir .'/config.php';
229
-		if(!file_exists($configFilePath)) {
230
-			@touch($configFilePath);
231
-		}
232
-
233
-		// Check if config is writable
234
-		$configFileWritable = is_writable($configFilePath);
235
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
236
-			|| !$configFileWritable && self::checkUpgrade(false)) {
237
-
238
-			$urlGenerator = \OC::$server->getURLGenerator();
239
-
240
-			if (self::$CLI) {
241
-				echo $l->t('Cannot write into "config" directory!')."\n";
242
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243
-				echo "\n";
244
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
245
-				exit;
246
-			} else {
247
-				OC_Template::printErrorPage(
248
-					$l->t('Cannot write into "config" directory!'),
249
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
250
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
251
-				);
252
-			}
253
-		}
254
-	}
255
-
256
-	public static function checkInstalled() {
257
-		if (defined('OC_CONSOLE')) {
258
-			return;
259
-		}
260
-		// Redirect to installer if not installed
261
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
262
-			if (OC::$CLI) {
263
-				throw new Exception('Not installed');
264
-			} else {
265
-				$url = OC::$WEBROOT . '/index.php';
266
-				header('Location: ' . $url);
267
-			}
268
-			exit();
269
-		}
270
-	}
271
-
272
-	public static function checkMaintenanceMode() {
273
-		// Allow ajax update script to execute without being stopped
274
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
275
-			// send http status 503
276
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
277
-			header('Status: 503 Service Temporarily Unavailable');
278
-			header('Retry-After: 120');
279
-
280
-			// render error page
281
-			$template = new OC_Template('', 'update.user', 'guest');
282
-			OC_Util::addScript('maintenance-check');
283
-			$template->printPage();
284
-			die();
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * Checks if the version requires an update and shows
290
-	 * @param bool $showTemplate Whether an update screen should get shown
291
-	 * @return bool|void
292
-	 */
293
-	public static function checkUpgrade($showTemplate = true) {
294
-		if (\OCP\Util::needUpgrade()) {
295
-			$systemConfig = \OC::$server->getSystemConfig();
296
-			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
297
-				self::printUpgradePage();
298
-				exit();
299
-			} else {
300
-				return true;
301
-			}
302
-		}
303
-		return false;
304
-	}
305
-
306
-	/**
307
-	 * Prints the upgrade page
308
-	 */
309
-	private static function printUpgradePage() {
310
-		$systemConfig = \OC::$server->getSystemConfig();
311
-
312
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
313
-		$tooBig = false;
314
-		if (!$disableWebUpdater) {
315
-			$apps = \OC::$server->getAppManager();
316
-			$tooBig = false;
317
-			if ($apps->isInstalled('user_ldap')) {
318
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
-
320
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
321
-					->from('ldap_user_mapping')
322
-					->execute();
323
-				$row = $result->fetch();
324
-				$result->closeCursor();
325
-
326
-				$tooBig = ($row['user_count'] > 50);
327
-			}
328
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
329
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
-
331
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
332
-					->from('user_saml_users')
333
-					->execute();
334
-				$row = $result->fetch();
335
-				$result->closeCursor();
336
-
337
-				$tooBig = ($row['user_count'] > 50);
338
-			}
339
-			if (!$tooBig) {
340
-				// count users
341
-				$stats = \OC::$server->getUserManager()->countUsers();
342
-				$totalUsers = array_sum($stats);
343
-				$tooBig = ($totalUsers > 50);
344
-			}
345
-		}
346
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
-
349
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
-			// send http status 503
351
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
352
-			header('Status: 503 Service Temporarily Unavailable');
353
-			header('Retry-After: 120');
354
-
355
-			// render error page
356
-			$template = new OC_Template('', 'update.use-cli', 'guest');
357
-			$template->assign('productName', 'nextcloud'); // for now
358
-			$template->assign('version', OC_Util::getVersionString());
359
-			$template->assign('tooBig', $tooBig);
360
-
361
-			$template->printPage();
362
-			die();
363
-		}
364
-
365
-		// check whether this is a core update or apps update
366
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
367
-		$currentVersion = implode('.', \OCP\Util::getVersion());
368
-
369
-		// if not a core upgrade, then it's apps upgrade
370
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
371
-
372
-		$oldTheme = $systemConfig->getValue('theme');
373
-		$systemConfig->setValue('theme', '');
374
-		OC_Util::addScript('config'); // needed for web root
375
-		OC_Util::addScript('update');
376
-
377
-		/** @var \OC\App\AppManager $appManager */
378
-		$appManager = \OC::$server->getAppManager();
379
-
380
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
381
-		$tmpl->assign('version', OC_Util::getVersionString());
382
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
383
-
384
-		// get third party apps
385
-		$ocVersion = \OCP\Util::getVersion();
386
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
-		$incompatibleShippedApps = [];
388
-		foreach ($incompatibleApps as $appInfo) {
389
-			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
-			}
392
-		}
393
-
394
-		if (!empty($incompatibleShippedApps)) {
395
-			$l = \OC::$server->getL10N('core');
396
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
-		}
399
-
400
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
-		$tmpl->assign('productName', 'Nextcloud'); // for now
403
-		$tmpl->assign('oldTheme', $oldTheme);
404
-		$tmpl->printPage();
405
-	}
406
-
407
-	public static function initSession() {
408
-		// prevents javascript from accessing php session cookies
409
-		ini_set('session.cookie_httponly', true);
410
-
411
-		// set the cookie path to the Nextcloud directory
412
-		$cookie_path = OC::$WEBROOT ? : '/';
413
-		ini_set('session.cookie_path', $cookie_path);
414
-
415
-		// Let the session name be changed in the initSession Hook
416
-		$sessionName = OC_Util::getInstanceId();
417
-
418
-		try {
419
-			// Allow session apps to create a custom session object
420
-			$useCustomSession = false;
421
-			$session = self::$server->getSession();
422
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
423
-			if (!$useCustomSession) {
424
-				// set the session name to the instance id - which is unique
425
-				$session = new \OC\Session\Internal($sessionName);
426
-			}
427
-
428
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
429
-			$session = $cryptoWrapper->wrapSession($session);
430
-			self::$server->setSession($session);
431
-
432
-			// if session can't be started break with http 500 error
433
-		} catch (Exception $e) {
434
-			\OCP\Util::logException('base', $e);
435
-			//show the user a detailed error page
436
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
437
-			OC_Template::printExceptionErrorPage($e);
438
-			die();
439
-		}
440
-
441
-		$sessionLifeTime = self::getSessionLifeTime();
442
-
443
-		// session timeout
444
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
445
-			if (isset($_COOKIE[session_name()])) {
446
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
447
-			}
448
-			\OC::$server->getUserSession()->logout();
449
-		}
450
-
451
-		$session->set('LAST_ACTIVITY', time());
452
-	}
453
-
454
-	/**
455
-	 * @return string
456
-	 */
457
-	private static function getSessionLifeTime() {
458
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
459
-	}
460
-
461
-	public static function loadAppClassPaths() {
462
-		foreach (OC_App::getEnabledApps() as $app) {
463
-			$appPath = OC_App::getAppPath($app);
464
-			if ($appPath === false) {
465
-				continue;
466
-			}
467
-
468
-			$file = $appPath . '/appinfo/classpath.php';
469
-			if (file_exists($file)) {
470
-				require_once $file;
471
-			}
472
-		}
473
-	}
474
-
475
-	/**
476
-	 * Try to set some values to the required Nextcloud default
477
-	 */
478
-	public static function setRequiredIniValues() {
479
-		@ini_set('default_charset', 'UTF-8');
480
-		@ini_set('gd.jpeg_ignore_warning', 1);
481
-	}
482
-
483
-	/**
484
-	 * Send the same site cookies
485
-	 */
486
-	private static function sendSameSiteCookies() {
487
-		$cookieParams = session_get_cookie_params();
488
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
489
-		$policies = [
490
-			'lax',
491
-			'strict',
492
-		];
493
-
494
-		// Append __Host to the cookie if it meets the requirements
495
-		$cookiePrefix = '';
496
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
497
-			$cookiePrefix = '__Host-';
498
-		}
499
-
500
-		foreach($policies as $policy) {
501
-			header(
502
-				sprintf(
503
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
504
-					$cookiePrefix,
505
-					$policy,
506
-					$cookieParams['path'],
507
-					$policy
508
-				),
509
-				false
510
-			);
511
-		}
512
-	}
513
-
514
-	/**
515
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
516
-	 * be set in every request if cookies are sent to add a second level of
517
-	 * defense against CSRF.
518
-	 *
519
-	 * If the cookie is not sent this will set the cookie and reload the page.
520
-	 * We use an additional cookie since we want to protect logout CSRF and
521
-	 * also we can't directly interfere with PHP's session mechanism.
522
-	 */
523
-	private static function performSameSiteCookieProtection() {
524
-		$request = \OC::$server->getRequest();
525
-
526
-		// Some user agents are notorious and don't really properly follow HTTP
527
-		// specifications. For those, have an automated opt-out. Since the protection
528
-		// for remote.php is applied in base.php as starting point we need to opt out
529
-		// here.
530
-		$incompatibleUserAgents = [
531
-			// OS X Finder
532
-			'/^WebDAVFS/',
533
-		];
534
-		if($request->isUserAgent($incompatibleUserAgents)) {
535
-			return;
536
-		}
537
-
538
-		if(count($_COOKIE) > 0) {
539
-			$requestUri = $request->getScriptName();
540
-			$processingScript = explode('/', $requestUri);
541
-			$processingScript = $processingScript[count($processingScript)-1];
542
-			// FIXME: In a SAML scenario we don't get any strict or lax cookie
543
-			// send for the ACS endpoint. Since we have some legacy code in Nextcloud
544
-			// (direct PHP files) the enforcement of lax cookies is performed here
545
-			// instead of the middleware.
546
-			//
547
-			// This means we cannot exclude some routes from the cookie validation,
548
-			// which normally is not a problem but is a little bit cumbersome for
549
-			// this use-case.
550
-			// Once the old legacy PHP endpoints have been removed we can move
551
-			// the verification into a middleware and also adds some exemptions.
552
-			//
553
-			// Questions about this code? Ask Lukas ;-)
554
-			$currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
555
-			if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
556
-				return;
557
-			}
558
-			// For the "index.php" endpoint only a lax cookie is required.
559
-			if($processingScript === 'index.php') {
560
-				if(!$request->passesLaxCookieCheck()) {
561
-					self::sendSameSiteCookies();
562
-					header('Location: '.$_SERVER['REQUEST_URI']);
563
-					exit();
564
-				}
565
-			} else {
566
-				// All other endpoints require the lax and the strict cookie
567
-				if(!$request->passesStrictCookieCheck()) {
568
-					self::sendSameSiteCookies();
569
-					// Debug mode gets access to the resources without strict cookie
570
-					// due to the fact that the SabreDAV browser also lives there.
571
-					if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
572
-						http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
573
-						exit();
574
-					}
575
-				}
576
-			}
577
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578
-			self::sendSameSiteCookies();
579
-		}
580
-	}
581
-
582
-	public static function init() {
583
-		// calculate the root directories
584
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
585
-
586
-		// register autoloader
587
-		$loaderStart = microtime(true);
588
-		require_once __DIR__ . '/autoloader.php';
589
-		self::$loader = new \OC\Autoloader([
590
-			OC::$SERVERROOT . '/lib/private/legacy',
591
-		]);
592
-		if (defined('PHPUNIT_RUN')) {
593
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
594
-		}
595
-		spl_autoload_register(array(self::$loader, 'load'));
596
-		$loaderEnd = microtime(true);
597
-
598
-		self::$CLI = (php_sapi_name() == 'cli');
599
-
600
-		// Add default composer PSR-4 autoloader
601
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
602
-
603
-		try {
604
-			self::initPaths();
605
-			// setup 3rdparty autoloader
606
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
607
-			if (!file_exists($vendorAutoLoad)) {
608
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
609
-			}
610
-			require_once $vendorAutoLoad;
611
-
612
-		} catch (\RuntimeException $e) {
613
-			if (!self::$CLI) {
614
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
615
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
616
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
617
-			}
618
-			// we can't use the template error page here, because this needs the
619
-			// DI container which isn't available yet
620
-			print($e->getMessage());
621
-			exit();
622
-		}
623
-
624
-		// setup the basic server
625
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
626
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
627
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
628
-
629
-		// Don't display errors and log them
630
-		error_reporting(E_ALL | E_STRICT);
631
-		@ini_set('display_errors', 0);
632
-		@ini_set('log_errors', 1);
633
-
634
-		if(!date_default_timezone_set('UTC')) {
635
-			throw new \RuntimeException('Could not set timezone to UTC');
636
-		};
637
-
638
-		//try to configure php to enable big file uploads.
639
-		//this doesn´t work always depending on the webserver and php configuration.
640
-		//Let´s try to overwrite some defaults anyway
641
-
642
-		//try to set the maximum execution time to 60min
643
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
644
-			@set_time_limit(3600);
645
-		}
646
-		@ini_set('max_execution_time', 3600);
647
-		@ini_set('max_input_time', 3600);
648
-
649
-		//try to set the maximum filesize to 10G
650
-		@ini_set('upload_max_filesize', '10G');
651
-		@ini_set('post_max_size', '10G');
652
-		@ini_set('file_uploads', '50');
653
-
654
-		self::setRequiredIniValues();
655
-		self::handleAuthHeaders();
656
-		self::registerAutoloaderCache();
657
-
658
-		// initialize intl fallback is necessary
659
-		\Patchwork\Utf8\Bootup::initIntl();
660
-		OC_Util::isSetLocaleWorking();
661
-
662
-		if (!defined('PHPUNIT_RUN')) {
663
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
664
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
665
-			OC\Log\ErrorHandler::register($debug);
666
-		}
667
-
668
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
669
-		OC_App::loadApps(array('session'));
670
-		if (!self::$CLI) {
671
-			self::initSession();
672
-		}
673
-		\OC::$server->getEventLogger()->end('init_session');
674
-		self::checkConfig();
675
-		self::checkInstalled();
676
-
677
-		OC_Response::addSecurityHeaders();
678
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
679
-			ini_set('session.cookie_secure', true);
680
-		}
681
-
682
-		self::performSameSiteCookieProtection();
683
-
684
-		if (!defined('OC_CONSOLE')) {
685
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
686
-			if (count($errors) > 0) {
687
-				if (self::$CLI) {
688
-					// Convert l10n string into regular string for usage in database
689
-					$staticErrors = [];
690
-					foreach ($errors as $error) {
691
-						echo $error['error'] . "\n";
692
-						echo $error['hint'] . "\n\n";
693
-						$staticErrors[] = [
694
-							'error' => (string)$error['error'],
695
-							'hint' => (string)$error['hint'],
696
-						];
697
-					}
698
-
699
-					try {
700
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
701
-					} catch (\Exception $e) {
702
-						echo('Writing to database failed');
703
-					}
704
-					exit(1);
705
-				} else {
706
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
707
-					OC_Util::addStyle('guest');
708
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
709
-					exit;
710
-				}
711
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
712
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
713
-			}
714
-		}
715
-		//try to set the session lifetime
716
-		$sessionLifeTime = self::getSessionLifeTime();
717
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
718
-
719
-		$systemConfig = \OC::$server->getSystemConfig();
720
-
721
-		// User and Groups
722
-		if (!$systemConfig->getValue("installed", false)) {
723
-			self::$server->getSession()->set('user_id', '');
724
-		}
725
-
726
-		OC_User::useBackend(new \OC\User\Database());
727
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
728
-
729
-		// Subscribe to the hook
730
-		\OCP\Util::connectHook(
731
-			'\OCA\Files_Sharing\API\Server2Server',
732
-			'preLoginNameUsedAsUserName',
733
-			'\OC\User\Database',
734
-			'preLoginNameUsedAsUserName'
735
-		);
736
-
737
-		//setup extra user backends
738
-		if (!self::checkUpgrade(false)) {
739
-			OC_User::setupBackends();
740
-		} else {
741
-			// Run upgrades in incognito mode
742
-			OC_User::setIncognitoMode(true);
743
-		}
744
-
745
-		self::registerCacheHooks();
746
-		self::registerFilesystemHooks();
747
-		self::registerShareHooks();
748
-		self::registerLogRotate();
749
-		self::registerEncryptionWrapper();
750
-		self::registerEncryptionHooks();
751
-		self::registerAccountHooks();
752
-		self::registerSettingsHooks();
753
-
754
-		$settings = new \OC\Settings\Application();
755
-		$settings->register();
756
-
757
-		//make sure temporary files are cleaned up
758
-		$tmpManager = \OC::$server->getTempManager();
759
-		register_shutdown_function(array($tmpManager, 'clean'));
760
-		$lockProvider = \OC::$server->getLockingProvider();
761
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
762
-
763
-		// Check whether the sample configuration has been copied
764
-		if($systemConfig->getValue('copied_sample_config', false)) {
765
-			$l = \OC::$server->getL10N('lib');
766
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
767
-			header('Status: 503 Service Temporarily Unavailable');
768
-			OC_Template::printErrorPage(
769
-				$l->t('Sample configuration detected'),
770
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
771
-			);
772
-			return;
773
-		}
774
-
775
-		$request = \OC::$server->getRequest();
776
-		$host = $request->getInsecureServerHost();
777
-		/**
778
-		 * if the host passed in headers isn't trusted
779
-		 * FIXME: Should not be in here at all :see_no_evil:
780
-		 */
781
-		if (!OC::$CLI
782
-			// overwritehost is always trusted, workaround to not have to make
783
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
784
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
785
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
786
-			&& self::$server->getConfig()->getSystemValue('installed', false)
787
-		) {
788
-			// Allow access to CSS resources
789
-			$isScssRequest = false;
790
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
791
-				$isScssRequest = true;
792
-			}
793
-
794
-			if (!$isScssRequest) {
795
-				header('HTTP/1.1 400 Bad Request');
796
-				header('Status: 400 Bad Request');
797
-
798
-				\OC::$server->getLogger()->warning(
799
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
800
-					[
801
-						'app' => 'core',
802
-						'remoteAddress' => $request->getRemoteAddress(),
803
-						'host' => $host,
804
-					]
805
-				);
806
-
807
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
808
-				$tmpl->assign('domain', $host);
809
-				$tmpl->printPage();
810
-
811
-				exit();
812
-			}
813
-		}
814
-		\OC::$server->getEventLogger()->end('boot');
815
-	}
816
-
817
-	/**
818
-	 * register hooks for the cache
819
-	 */
820
-	public static function registerCacheHooks() {
821
-		//don't try to do this before we are properly setup
822
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
823
-
824
-			// NOTE: This will be replaced to use OCP
825
-			$userSession = self::$server->getUserSession();
826
-			$userSession->listen('\OC\User', 'postLogin', function () {
827
-				try {
828
-					$cache = new \OC\Cache\File();
829
-					$cache->gc();
830
-				} catch (\OC\ServerNotAvailableException $e) {
831
-					// not a GC exception, pass it on
832
-					throw $e;
833
-				} catch (\OC\ForbiddenException $e) {
834
-					// filesystem blocked for this request, ignore
835
-				} catch (\Exception $e) {
836
-					// a GC exception should not prevent users from using OC,
837
-					// so log the exception
838
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
839
-				}
840
-			});
841
-		}
842
-	}
843
-
844
-	public static function registerSettingsHooks() {
845
-		$dispatcher = \OC::$server->getEventDispatcher();
846
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
847
-			/** @var \OCP\App\ManagerEvent $event */
848
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
849
-		});
850
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
851
-			/** @var \OCP\App\ManagerEvent $event */
852
-			$jobList = \OC::$server->getJobList();
853
-			$job = 'OC\\Settings\\RemoveOrphaned';
854
-			if(!($jobList->has($job, null))) {
855
-				$jobList->add($job);
856
-			}
857
-		});
858
-	}
859
-
860
-	private static function registerEncryptionWrapper() {
861
-		$manager = self::$server->getEncryptionManager();
862
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
863
-	}
864
-
865
-	private static function registerEncryptionHooks() {
866
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
867
-		if ($enabled) {
868
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
869
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
870
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
871
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
872
-		}
873
-	}
874
-
875
-	private static function registerAccountHooks() {
876
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
877
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
878
-	}
879
-
880
-	/**
881
-	 * register hooks for the cache
882
-	 */
883
-	public static function registerLogRotate() {
884
-		$systemConfig = \OC::$server->getSystemConfig();
885
-		if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
886
-			//don't try to do this before we are properly setup
887
-			//use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
888
-			\OC::$server->getJobList()->add('OC\Log\Rotate');
889
-		}
890
-	}
891
-
892
-	/**
893
-	 * register hooks for the filesystem
894
-	 */
895
-	public static function registerFilesystemHooks() {
896
-		// Check for blacklisted files
897
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
898
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
899
-	}
900
-
901
-	/**
902
-	 * register hooks for sharing
903
-	 */
904
-	public static function registerShareHooks() {
905
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
907
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
908
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
909
-		}
910
-	}
911
-
912
-	protected static function registerAutoloaderCache() {
913
-		// The class loader takes an optional low-latency cache, which MUST be
914
-		// namespaced. The instanceid is used for namespacing, but might be
915
-		// unavailable at this point. Furthermore, it might not be possible to
916
-		// generate an instanceid via \OC_Util::getInstanceId() because the
917
-		// config file may not be writable. As such, we only register a class
918
-		// loader cache if instanceid is available without trying to create one.
919
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
-		if ($instanceId) {
921
-			try {
922
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
923
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
-			} catch (\Exception $ex) {
925
-			}
926
-		}
927
-	}
928
-
929
-	/**
930
-	 * Handle the request
931
-	 */
932
-	public static function handleRequest() {
933
-
934
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
-		$systemConfig = \OC::$server->getSystemConfig();
936
-		// load all the classpaths from the enabled apps so they are available
937
-		// in the routing files of each app
938
-		OC::loadAppClassPaths();
939
-
940
-		// Check if Nextcloud is installed or in maintenance (update) mode
941
-		if (!$systemConfig->getValue('installed', false)) {
942
-			\OC::$server->getSession()->clear();
943
-			$setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
944
-				\OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
945
-				\OC::$server->getSecureRandom());
946
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
947
-			$controller->run($_POST);
948
-			exit();
949
-		}
950
-
951
-		$request = \OC::$server->getRequest();
952
-		$requestPath = $request->getRawPathInfo();
953
-		if ($requestPath === '/heartbeat') {
954
-			return;
955
-		}
956
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
-			self::checkMaintenanceMode();
958
-			self::checkUpgrade();
959
-		}
960
-
961
-		// emergency app disabling
962
-		if ($requestPath === '/disableapp'
963
-			&& $request->getMethod() === 'POST'
964
-			&& ((array)$request->getParam('appid')) !== ''
965
-		) {
966
-			\OCP\JSON::callCheck();
967
-			\OCP\JSON::checkAdminUser();
968
-			$appIds = (array)$request->getParam('appid');
969
-			foreach($appIds as $appId) {
970
-				$appId = \OC_App::cleanAppId($appId);
971
-				\OC_App::disable($appId);
972
-			}
973
-			\OC_JSON::success();
974
-			exit();
975
-		}
976
-
977
-		// Always load authentication apps
978
-		OC_App::loadApps(['authentication']);
979
-
980
-		// Load minimum set of apps
981
-		if (!self::checkUpgrade(false)
982
-			&& !$systemConfig->getValue('maintenance', false)) {
983
-			// For logged-in users: Load everything
984
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
985
-				OC_App::loadApps();
986
-			} else {
987
-				// For guests: Load only filesystem and logging
988
-				OC_App::loadApps(array('filesystem', 'logging'));
989
-				self::handleLogin($request);
990
-			}
991
-		}
992
-
993
-		if (!self::$CLI) {
994
-			try {
995
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
996
-					OC_App::loadApps(array('filesystem', 'logging'));
997
-					OC_App::loadApps();
998
-				}
999
-				OC_Util::setupFS();
1000
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1001
-				return;
1002
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1003
-				//header('HTTP/1.0 404 Not Found');
1004
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1005
-				OC_Response::setStatus(405);
1006
-				return;
1007
-			}
1008
-		}
1009
-
1010
-		// Handle WebDAV
1011
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1012
-			// not allowed any more to prevent people
1013
-			// mounting this root directly.
1014
-			// Users need to mount remote.php/webdav instead.
1015
-			header('HTTP/1.1 405 Method Not Allowed');
1016
-			header('Status: 405 Method Not Allowed');
1017
-			return;
1018
-		}
1019
-
1020
-		// Someone is logged in
1021
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1022
-			OC_App::loadApps();
1023
-			OC_User::setupBackends();
1024
-			OC_Util::setupFS();
1025
-			// FIXME
1026
-			// Redirect to default application
1027
-			OC_Util::redirectToDefaultPage();
1028
-		} else {
1029
-			// Not handled and not logged in
1030
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1031
-		}
1032
-	}
1033
-
1034
-	/**
1035
-	 * Check login: apache auth, auth token, basic auth
1036
-	 *
1037
-	 * @param OCP\IRequest $request
1038
-	 * @return boolean
1039
-	 */
1040
-	static function handleLogin(OCP\IRequest $request) {
1041
-		$userSession = self::$server->getUserSession();
1042
-		if (OC_User::handleApacheAuth()) {
1043
-			return true;
1044
-		}
1045
-		if ($userSession->tryTokenLogin($request)) {
1046
-			return true;
1047
-		}
1048
-		if (isset($_COOKIE['nc_username'])
1049
-			&& isset($_COOKIE['nc_token'])
1050
-			&& isset($_COOKIE['nc_session_id'])
1051
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1052
-			return true;
1053
-		}
1054
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1055
-			return true;
1056
-		}
1057
-		return false;
1058
-	}
1059
-
1060
-	protected static function handleAuthHeaders() {
1061
-		//copy http auth headers for apache+php-fcgid work around
1062
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1063
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1064
-		}
1065
-
1066
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1067
-		$vars = array(
1068
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1069
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1070
-		);
1071
-		foreach ($vars as $var) {
1072
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1073
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1074
-				$_SERVER['PHP_AUTH_USER'] = $name;
1075
-				$_SERVER['PHP_AUTH_PW'] = $password;
1076
-				break;
1077
-			}
1078
-		}
1079
-	}
62
+    /**
63
+     * Associative array for autoloading. classname => filename
64
+     */
65
+    public static $CLASSPATH = array();
66
+    /**
67
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
68
+     */
69
+    public static $SERVERROOT = '';
70
+    /**
71
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
72
+     */
73
+    private static $SUBURI = '';
74
+    /**
75
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
76
+     */
77
+    public static $WEBROOT = '';
78
+    /**
79
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
80
+     * web path in 'url'
81
+     */
82
+    public static $APPSROOTS = array();
83
+
84
+    /**
85
+     * @var string
86
+     */
87
+    public static $configDir;
88
+
89
+    /**
90
+     * requested app
91
+     */
92
+    public static $REQUESTEDAPP = '';
93
+
94
+    /**
95
+     * check if Nextcloud runs in cli mode
96
+     */
97
+    public static $CLI = false;
98
+
99
+    /**
100
+     * @var \OC\Autoloader $loader
101
+     */
102
+    public static $loader = null;
103
+
104
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
105
+    public static $composerAutoloader = null;
106
+
107
+    /**
108
+     * @var \OC\Server
109
+     */
110
+    public static $server = null;
111
+
112
+    /**
113
+     * @var \OC\Config
114
+     */
115
+    private static $config = null;
116
+
117
+    /**
118
+     * @throws \RuntimeException when the 3rdparty directory is missing or
119
+     * the app path list is empty or contains an invalid path
120
+     */
121
+    public static function initPaths() {
122
+        if(defined('PHPUNIT_CONFIG_DIR')) {
123
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
+            self::$configDir = rtrim($dir, '/') . '/';
128
+        } else {
129
+            self::$configDir = OC::$SERVERROOT . '/config/';
130
+        }
131
+        self::$config = new \OC\Config(self::$configDir);
132
+
133
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
134
+        /**
135
+         * FIXME: The following lines are required because we can't yet instantiate
136
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
137
+         */
138
+        $params = [
139
+            'server' => [
140
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
141
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
142
+            ],
143
+        ];
144
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
145
+        $scriptName = $fakeRequest->getScriptName();
146
+        if (substr($scriptName, -1) == '/') {
147
+            $scriptName .= 'index.php';
148
+            //make sure suburi follows the same rules as scriptName
149
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
150
+                if (substr(OC::$SUBURI, -1) != '/') {
151
+                    OC::$SUBURI = OC::$SUBURI . '/';
152
+                }
153
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
154
+            }
155
+        }
156
+
157
+
158
+        if (OC::$CLI) {
159
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
160
+        } else {
161
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
162
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163
+
164
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
166
+                }
167
+            } else {
168
+                // The scriptName is not ending with OC::$SUBURI
169
+                // This most likely means that we are calling from CLI.
170
+                // However some cron jobs still need to generate
171
+                // a web URL, so we use overwritewebroot as a fallback.
172
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
173
+            }
174
+
175
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
176
+            // slash which is required by URL generation.
177
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
178
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
179
+                header('Location: '.\OC::$WEBROOT.'/');
180
+                exit();
181
+            }
182
+        }
183
+
184
+        // search the apps folder
185
+        $config_paths = self::$config->getValue('apps_paths', array());
186
+        if (!empty($config_paths)) {
187
+            foreach ($config_paths as $paths) {
188
+                if (isset($paths['url']) && isset($paths['path'])) {
189
+                    $paths['url'] = rtrim($paths['url'], '/');
190
+                    $paths['path'] = rtrim($paths['path'], '/');
191
+                    OC::$APPSROOTS[] = $paths;
192
+                }
193
+            }
194
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
+            OC::$APPSROOTS[] = array(
198
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
199
+                'url' => '/apps',
200
+                'writable' => true
201
+            );
202
+        }
203
+
204
+        if (empty(OC::$APPSROOTS)) {
205
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
206
+                . ' or the folder above. You can also configure the location in the config.php file.');
207
+        }
208
+        $paths = array();
209
+        foreach (OC::$APPSROOTS as $path) {
210
+            $paths[] = $path['path'];
211
+            if (!is_dir($path['path'])) {
212
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
213
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
214
+                    . ' config.php file.', $path['path']));
215
+            }
216
+        }
217
+
218
+        // set the right include path
219
+        set_include_path(
220
+            implode(PATH_SEPARATOR, $paths)
221
+        );
222
+    }
223
+
224
+    public static function checkConfig() {
225
+        $l = \OC::$server->getL10N('lib');
226
+
227
+        // Create config if it does not already exist
228
+        $configFilePath = self::$configDir .'/config.php';
229
+        if(!file_exists($configFilePath)) {
230
+            @touch($configFilePath);
231
+        }
232
+
233
+        // Check if config is writable
234
+        $configFileWritable = is_writable($configFilePath);
235
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
236
+            || !$configFileWritable && self::checkUpgrade(false)) {
237
+
238
+            $urlGenerator = \OC::$server->getURLGenerator();
239
+
240
+            if (self::$CLI) {
241
+                echo $l->t('Cannot write into "config" directory!')."\n";
242
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243
+                echo "\n";
244
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
245
+                exit;
246
+            } else {
247
+                OC_Template::printErrorPage(
248
+                    $l->t('Cannot write into "config" directory!'),
249
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
250
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
251
+                );
252
+            }
253
+        }
254
+    }
255
+
256
+    public static function checkInstalled() {
257
+        if (defined('OC_CONSOLE')) {
258
+            return;
259
+        }
260
+        // Redirect to installer if not installed
261
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
262
+            if (OC::$CLI) {
263
+                throw new Exception('Not installed');
264
+            } else {
265
+                $url = OC::$WEBROOT . '/index.php';
266
+                header('Location: ' . $url);
267
+            }
268
+            exit();
269
+        }
270
+    }
271
+
272
+    public static function checkMaintenanceMode() {
273
+        // Allow ajax update script to execute without being stopped
274
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
275
+            // send http status 503
276
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
277
+            header('Status: 503 Service Temporarily Unavailable');
278
+            header('Retry-After: 120');
279
+
280
+            // render error page
281
+            $template = new OC_Template('', 'update.user', 'guest');
282
+            OC_Util::addScript('maintenance-check');
283
+            $template->printPage();
284
+            die();
285
+        }
286
+    }
287
+
288
+    /**
289
+     * Checks if the version requires an update and shows
290
+     * @param bool $showTemplate Whether an update screen should get shown
291
+     * @return bool|void
292
+     */
293
+    public static function checkUpgrade($showTemplate = true) {
294
+        if (\OCP\Util::needUpgrade()) {
295
+            $systemConfig = \OC::$server->getSystemConfig();
296
+            if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
297
+                self::printUpgradePage();
298
+                exit();
299
+            } else {
300
+                return true;
301
+            }
302
+        }
303
+        return false;
304
+    }
305
+
306
+    /**
307
+     * Prints the upgrade page
308
+     */
309
+    private static function printUpgradePage() {
310
+        $systemConfig = \OC::$server->getSystemConfig();
311
+
312
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
313
+        $tooBig = false;
314
+        if (!$disableWebUpdater) {
315
+            $apps = \OC::$server->getAppManager();
316
+            $tooBig = false;
317
+            if ($apps->isInstalled('user_ldap')) {
318
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
+
320
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
321
+                    ->from('ldap_user_mapping')
322
+                    ->execute();
323
+                $row = $result->fetch();
324
+                $result->closeCursor();
325
+
326
+                $tooBig = ($row['user_count'] > 50);
327
+            }
328
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
329
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
+
331
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
332
+                    ->from('user_saml_users')
333
+                    ->execute();
334
+                $row = $result->fetch();
335
+                $result->closeCursor();
336
+
337
+                $tooBig = ($row['user_count'] > 50);
338
+            }
339
+            if (!$tooBig) {
340
+                // count users
341
+                $stats = \OC::$server->getUserManager()->countUsers();
342
+                $totalUsers = array_sum($stats);
343
+                $tooBig = ($totalUsers > 50);
344
+            }
345
+        }
346
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
+
349
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
+            // send http status 503
351
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
352
+            header('Status: 503 Service Temporarily Unavailable');
353
+            header('Retry-After: 120');
354
+
355
+            // render error page
356
+            $template = new OC_Template('', 'update.use-cli', 'guest');
357
+            $template->assign('productName', 'nextcloud'); // for now
358
+            $template->assign('version', OC_Util::getVersionString());
359
+            $template->assign('tooBig', $tooBig);
360
+
361
+            $template->printPage();
362
+            die();
363
+        }
364
+
365
+        // check whether this is a core update or apps update
366
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
367
+        $currentVersion = implode('.', \OCP\Util::getVersion());
368
+
369
+        // if not a core upgrade, then it's apps upgrade
370
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
371
+
372
+        $oldTheme = $systemConfig->getValue('theme');
373
+        $systemConfig->setValue('theme', '');
374
+        OC_Util::addScript('config'); // needed for web root
375
+        OC_Util::addScript('update');
376
+
377
+        /** @var \OC\App\AppManager $appManager */
378
+        $appManager = \OC::$server->getAppManager();
379
+
380
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
381
+        $tmpl->assign('version', OC_Util::getVersionString());
382
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
383
+
384
+        // get third party apps
385
+        $ocVersion = \OCP\Util::getVersion();
386
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
+        $incompatibleShippedApps = [];
388
+        foreach ($incompatibleApps as $appInfo) {
389
+            if ($appManager->isShipped($appInfo['id'])) {
390
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
+            }
392
+        }
393
+
394
+        if (!empty($incompatibleShippedApps)) {
395
+            $l = \OC::$server->getL10N('core');
396
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
+        }
399
+
400
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
+        $tmpl->assign('productName', 'Nextcloud'); // for now
403
+        $tmpl->assign('oldTheme', $oldTheme);
404
+        $tmpl->printPage();
405
+    }
406
+
407
+    public static function initSession() {
408
+        // prevents javascript from accessing php session cookies
409
+        ini_set('session.cookie_httponly', true);
410
+
411
+        // set the cookie path to the Nextcloud directory
412
+        $cookie_path = OC::$WEBROOT ? : '/';
413
+        ini_set('session.cookie_path', $cookie_path);
414
+
415
+        // Let the session name be changed in the initSession Hook
416
+        $sessionName = OC_Util::getInstanceId();
417
+
418
+        try {
419
+            // Allow session apps to create a custom session object
420
+            $useCustomSession = false;
421
+            $session = self::$server->getSession();
422
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
423
+            if (!$useCustomSession) {
424
+                // set the session name to the instance id - which is unique
425
+                $session = new \OC\Session\Internal($sessionName);
426
+            }
427
+
428
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
429
+            $session = $cryptoWrapper->wrapSession($session);
430
+            self::$server->setSession($session);
431
+
432
+            // if session can't be started break with http 500 error
433
+        } catch (Exception $e) {
434
+            \OCP\Util::logException('base', $e);
435
+            //show the user a detailed error page
436
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
437
+            OC_Template::printExceptionErrorPage($e);
438
+            die();
439
+        }
440
+
441
+        $sessionLifeTime = self::getSessionLifeTime();
442
+
443
+        // session timeout
444
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
445
+            if (isset($_COOKIE[session_name()])) {
446
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
447
+            }
448
+            \OC::$server->getUserSession()->logout();
449
+        }
450
+
451
+        $session->set('LAST_ACTIVITY', time());
452
+    }
453
+
454
+    /**
455
+     * @return string
456
+     */
457
+    private static function getSessionLifeTime() {
458
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
459
+    }
460
+
461
+    public static function loadAppClassPaths() {
462
+        foreach (OC_App::getEnabledApps() as $app) {
463
+            $appPath = OC_App::getAppPath($app);
464
+            if ($appPath === false) {
465
+                continue;
466
+            }
467
+
468
+            $file = $appPath . '/appinfo/classpath.php';
469
+            if (file_exists($file)) {
470
+                require_once $file;
471
+            }
472
+        }
473
+    }
474
+
475
+    /**
476
+     * Try to set some values to the required Nextcloud default
477
+     */
478
+    public static function setRequiredIniValues() {
479
+        @ini_set('default_charset', 'UTF-8');
480
+        @ini_set('gd.jpeg_ignore_warning', 1);
481
+    }
482
+
483
+    /**
484
+     * Send the same site cookies
485
+     */
486
+    private static function sendSameSiteCookies() {
487
+        $cookieParams = session_get_cookie_params();
488
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
489
+        $policies = [
490
+            'lax',
491
+            'strict',
492
+        ];
493
+
494
+        // Append __Host to the cookie if it meets the requirements
495
+        $cookiePrefix = '';
496
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
497
+            $cookiePrefix = '__Host-';
498
+        }
499
+
500
+        foreach($policies as $policy) {
501
+            header(
502
+                sprintf(
503
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
504
+                    $cookiePrefix,
505
+                    $policy,
506
+                    $cookieParams['path'],
507
+                    $policy
508
+                ),
509
+                false
510
+            );
511
+        }
512
+    }
513
+
514
+    /**
515
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
516
+     * be set in every request if cookies are sent to add a second level of
517
+     * defense against CSRF.
518
+     *
519
+     * If the cookie is not sent this will set the cookie and reload the page.
520
+     * We use an additional cookie since we want to protect logout CSRF and
521
+     * also we can't directly interfere with PHP's session mechanism.
522
+     */
523
+    private static function performSameSiteCookieProtection() {
524
+        $request = \OC::$server->getRequest();
525
+
526
+        // Some user agents are notorious and don't really properly follow HTTP
527
+        // specifications. For those, have an automated opt-out. Since the protection
528
+        // for remote.php is applied in base.php as starting point we need to opt out
529
+        // here.
530
+        $incompatibleUserAgents = [
531
+            // OS X Finder
532
+            '/^WebDAVFS/',
533
+        ];
534
+        if($request->isUserAgent($incompatibleUserAgents)) {
535
+            return;
536
+        }
537
+
538
+        if(count($_COOKIE) > 0) {
539
+            $requestUri = $request->getScriptName();
540
+            $processingScript = explode('/', $requestUri);
541
+            $processingScript = $processingScript[count($processingScript)-1];
542
+            // FIXME: In a SAML scenario we don't get any strict or lax cookie
543
+            // send for the ACS endpoint. Since we have some legacy code in Nextcloud
544
+            // (direct PHP files) the enforcement of lax cookies is performed here
545
+            // instead of the middleware.
546
+            //
547
+            // This means we cannot exclude some routes from the cookie validation,
548
+            // which normally is not a problem but is a little bit cumbersome for
549
+            // this use-case.
550
+            // Once the old legacy PHP endpoints have been removed we can move
551
+            // the verification into a middleware and also adds some exemptions.
552
+            //
553
+            // Questions about this code? Ask Lukas ;-)
554
+            $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
555
+            if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
556
+                return;
557
+            }
558
+            // For the "index.php" endpoint only a lax cookie is required.
559
+            if($processingScript === 'index.php') {
560
+                if(!$request->passesLaxCookieCheck()) {
561
+                    self::sendSameSiteCookies();
562
+                    header('Location: '.$_SERVER['REQUEST_URI']);
563
+                    exit();
564
+                }
565
+            } else {
566
+                // All other endpoints require the lax and the strict cookie
567
+                if(!$request->passesStrictCookieCheck()) {
568
+                    self::sendSameSiteCookies();
569
+                    // Debug mode gets access to the resources without strict cookie
570
+                    // due to the fact that the SabreDAV browser also lives there.
571
+                    if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
572
+                        http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
573
+                        exit();
574
+                    }
575
+                }
576
+            }
577
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578
+            self::sendSameSiteCookies();
579
+        }
580
+    }
581
+
582
+    public static function init() {
583
+        // calculate the root directories
584
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
585
+
586
+        // register autoloader
587
+        $loaderStart = microtime(true);
588
+        require_once __DIR__ . '/autoloader.php';
589
+        self::$loader = new \OC\Autoloader([
590
+            OC::$SERVERROOT . '/lib/private/legacy',
591
+        ]);
592
+        if (defined('PHPUNIT_RUN')) {
593
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
594
+        }
595
+        spl_autoload_register(array(self::$loader, 'load'));
596
+        $loaderEnd = microtime(true);
597
+
598
+        self::$CLI = (php_sapi_name() == 'cli');
599
+
600
+        // Add default composer PSR-4 autoloader
601
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
602
+
603
+        try {
604
+            self::initPaths();
605
+            // setup 3rdparty autoloader
606
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
607
+            if (!file_exists($vendorAutoLoad)) {
608
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
609
+            }
610
+            require_once $vendorAutoLoad;
611
+
612
+        } catch (\RuntimeException $e) {
613
+            if (!self::$CLI) {
614
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
615
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
616
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
617
+            }
618
+            // we can't use the template error page here, because this needs the
619
+            // DI container which isn't available yet
620
+            print($e->getMessage());
621
+            exit();
622
+        }
623
+
624
+        // setup the basic server
625
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
626
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
627
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
628
+
629
+        // Don't display errors and log them
630
+        error_reporting(E_ALL | E_STRICT);
631
+        @ini_set('display_errors', 0);
632
+        @ini_set('log_errors', 1);
633
+
634
+        if(!date_default_timezone_set('UTC')) {
635
+            throw new \RuntimeException('Could not set timezone to UTC');
636
+        };
637
+
638
+        //try to configure php to enable big file uploads.
639
+        //this doesn´t work always depending on the webserver and php configuration.
640
+        //Let´s try to overwrite some defaults anyway
641
+
642
+        //try to set the maximum execution time to 60min
643
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
644
+            @set_time_limit(3600);
645
+        }
646
+        @ini_set('max_execution_time', 3600);
647
+        @ini_set('max_input_time', 3600);
648
+
649
+        //try to set the maximum filesize to 10G
650
+        @ini_set('upload_max_filesize', '10G');
651
+        @ini_set('post_max_size', '10G');
652
+        @ini_set('file_uploads', '50');
653
+
654
+        self::setRequiredIniValues();
655
+        self::handleAuthHeaders();
656
+        self::registerAutoloaderCache();
657
+
658
+        // initialize intl fallback is necessary
659
+        \Patchwork\Utf8\Bootup::initIntl();
660
+        OC_Util::isSetLocaleWorking();
661
+
662
+        if (!defined('PHPUNIT_RUN')) {
663
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
664
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
665
+            OC\Log\ErrorHandler::register($debug);
666
+        }
667
+
668
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
669
+        OC_App::loadApps(array('session'));
670
+        if (!self::$CLI) {
671
+            self::initSession();
672
+        }
673
+        \OC::$server->getEventLogger()->end('init_session');
674
+        self::checkConfig();
675
+        self::checkInstalled();
676
+
677
+        OC_Response::addSecurityHeaders();
678
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
679
+            ini_set('session.cookie_secure', true);
680
+        }
681
+
682
+        self::performSameSiteCookieProtection();
683
+
684
+        if (!defined('OC_CONSOLE')) {
685
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
686
+            if (count($errors) > 0) {
687
+                if (self::$CLI) {
688
+                    // Convert l10n string into regular string for usage in database
689
+                    $staticErrors = [];
690
+                    foreach ($errors as $error) {
691
+                        echo $error['error'] . "\n";
692
+                        echo $error['hint'] . "\n\n";
693
+                        $staticErrors[] = [
694
+                            'error' => (string)$error['error'],
695
+                            'hint' => (string)$error['hint'],
696
+                        ];
697
+                    }
698
+
699
+                    try {
700
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
701
+                    } catch (\Exception $e) {
702
+                        echo('Writing to database failed');
703
+                    }
704
+                    exit(1);
705
+                } else {
706
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
707
+                    OC_Util::addStyle('guest');
708
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
709
+                    exit;
710
+                }
711
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
712
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
713
+            }
714
+        }
715
+        //try to set the session lifetime
716
+        $sessionLifeTime = self::getSessionLifeTime();
717
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
718
+
719
+        $systemConfig = \OC::$server->getSystemConfig();
720
+
721
+        // User and Groups
722
+        if (!$systemConfig->getValue("installed", false)) {
723
+            self::$server->getSession()->set('user_id', '');
724
+        }
725
+
726
+        OC_User::useBackend(new \OC\User\Database());
727
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
728
+
729
+        // Subscribe to the hook
730
+        \OCP\Util::connectHook(
731
+            '\OCA\Files_Sharing\API\Server2Server',
732
+            'preLoginNameUsedAsUserName',
733
+            '\OC\User\Database',
734
+            'preLoginNameUsedAsUserName'
735
+        );
736
+
737
+        //setup extra user backends
738
+        if (!self::checkUpgrade(false)) {
739
+            OC_User::setupBackends();
740
+        } else {
741
+            // Run upgrades in incognito mode
742
+            OC_User::setIncognitoMode(true);
743
+        }
744
+
745
+        self::registerCacheHooks();
746
+        self::registerFilesystemHooks();
747
+        self::registerShareHooks();
748
+        self::registerLogRotate();
749
+        self::registerEncryptionWrapper();
750
+        self::registerEncryptionHooks();
751
+        self::registerAccountHooks();
752
+        self::registerSettingsHooks();
753
+
754
+        $settings = new \OC\Settings\Application();
755
+        $settings->register();
756
+
757
+        //make sure temporary files are cleaned up
758
+        $tmpManager = \OC::$server->getTempManager();
759
+        register_shutdown_function(array($tmpManager, 'clean'));
760
+        $lockProvider = \OC::$server->getLockingProvider();
761
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
762
+
763
+        // Check whether the sample configuration has been copied
764
+        if($systemConfig->getValue('copied_sample_config', false)) {
765
+            $l = \OC::$server->getL10N('lib');
766
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
767
+            header('Status: 503 Service Temporarily Unavailable');
768
+            OC_Template::printErrorPage(
769
+                $l->t('Sample configuration detected'),
770
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
771
+            );
772
+            return;
773
+        }
774
+
775
+        $request = \OC::$server->getRequest();
776
+        $host = $request->getInsecureServerHost();
777
+        /**
778
+         * if the host passed in headers isn't trusted
779
+         * FIXME: Should not be in here at all :see_no_evil:
780
+         */
781
+        if (!OC::$CLI
782
+            // overwritehost is always trusted, workaround to not have to make
783
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
784
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
785
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
786
+            && self::$server->getConfig()->getSystemValue('installed', false)
787
+        ) {
788
+            // Allow access to CSS resources
789
+            $isScssRequest = false;
790
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
791
+                $isScssRequest = true;
792
+            }
793
+
794
+            if (!$isScssRequest) {
795
+                header('HTTP/1.1 400 Bad Request');
796
+                header('Status: 400 Bad Request');
797
+
798
+                \OC::$server->getLogger()->warning(
799
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
800
+                    [
801
+                        'app' => 'core',
802
+                        'remoteAddress' => $request->getRemoteAddress(),
803
+                        'host' => $host,
804
+                    ]
805
+                );
806
+
807
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
808
+                $tmpl->assign('domain', $host);
809
+                $tmpl->printPage();
810
+
811
+                exit();
812
+            }
813
+        }
814
+        \OC::$server->getEventLogger()->end('boot');
815
+    }
816
+
817
+    /**
818
+     * register hooks for the cache
819
+     */
820
+    public static function registerCacheHooks() {
821
+        //don't try to do this before we are properly setup
822
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
823
+
824
+            // NOTE: This will be replaced to use OCP
825
+            $userSession = self::$server->getUserSession();
826
+            $userSession->listen('\OC\User', 'postLogin', function () {
827
+                try {
828
+                    $cache = new \OC\Cache\File();
829
+                    $cache->gc();
830
+                } catch (\OC\ServerNotAvailableException $e) {
831
+                    // not a GC exception, pass it on
832
+                    throw $e;
833
+                } catch (\OC\ForbiddenException $e) {
834
+                    // filesystem blocked for this request, ignore
835
+                } catch (\Exception $e) {
836
+                    // a GC exception should not prevent users from using OC,
837
+                    // so log the exception
838
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
839
+                }
840
+            });
841
+        }
842
+    }
843
+
844
+    public static function registerSettingsHooks() {
845
+        $dispatcher = \OC::$server->getEventDispatcher();
846
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
847
+            /** @var \OCP\App\ManagerEvent $event */
848
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
849
+        });
850
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
851
+            /** @var \OCP\App\ManagerEvent $event */
852
+            $jobList = \OC::$server->getJobList();
853
+            $job = 'OC\\Settings\\RemoveOrphaned';
854
+            if(!($jobList->has($job, null))) {
855
+                $jobList->add($job);
856
+            }
857
+        });
858
+    }
859
+
860
+    private static function registerEncryptionWrapper() {
861
+        $manager = self::$server->getEncryptionManager();
862
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
863
+    }
864
+
865
+    private static function registerEncryptionHooks() {
866
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
867
+        if ($enabled) {
868
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
869
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
870
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
871
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
872
+        }
873
+    }
874
+
875
+    private static function registerAccountHooks() {
876
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
877
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
878
+    }
879
+
880
+    /**
881
+     * register hooks for the cache
882
+     */
883
+    public static function registerLogRotate() {
884
+        $systemConfig = \OC::$server->getSystemConfig();
885
+        if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
886
+            //don't try to do this before we are properly setup
887
+            //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
888
+            \OC::$server->getJobList()->add('OC\Log\Rotate');
889
+        }
890
+    }
891
+
892
+    /**
893
+     * register hooks for the filesystem
894
+     */
895
+    public static function registerFilesystemHooks() {
896
+        // Check for blacklisted files
897
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
898
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
899
+    }
900
+
901
+    /**
902
+     * register hooks for sharing
903
+     */
904
+    public static function registerShareHooks() {
905
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
907
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
908
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
909
+        }
910
+    }
911
+
912
+    protected static function registerAutoloaderCache() {
913
+        // The class loader takes an optional low-latency cache, which MUST be
914
+        // namespaced. The instanceid is used for namespacing, but might be
915
+        // unavailable at this point. Furthermore, it might not be possible to
916
+        // generate an instanceid via \OC_Util::getInstanceId() because the
917
+        // config file may not be writable. As such, we only register a class
918
+        // loader cache if instanceid is available without trying to create one.
919
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
+        if ($instanceId) {
921
+            try {
922
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
923
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
+            } catch (\Exception $ex) {
925
+            }
926
+        }
927
+    }
928
+
929
+    /**
930
+     * Handle the request
931
+     */
932
+    public static function handleRequest() {
933
+
934
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
+        $systemConfig = \OC::$server->getSystemConfig();
936
+        // load all the classpaths from the enabled apps so they are available
937
+        // in the routing files of each app
938
+        OC::loadAppClassPaths();
939
+
940
+        // Check if Nextcloud is installed or in maintenance (update) mode
941
+        if (!$systemConfig->getValue('installed', false)) {
942
+            \OC::$server->getSession()->clear();
943
+            $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
944
+                \OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
945
+                \OC::$server->getSecureRandom());
946
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
947
+            $controller->run($_POST);
948
+            exit();
949
+        }
950
+
951
+        $request = \OC::$server->getRequest();
952
+        $requestPath = $request->getRawPathInfo();
953
+        if ($requestPath === '/heartbeat') {
954
+            return;
955
+        }
956
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
+            self::checkMaintenanceMode();
958
+            self::checkUpgrade();
959
+        }
960
+
961
+        // emergency app disabling
962
+        if ($requestPath === '/disableapp'
963
+            && $request->getMethod() === 'POST'
964
+            && ((array)$request->getParam('appid')) !== ''
965
+        ) {
966
+            \OCP\JSON::callCheck();
967
+            \OCP\JSON::checkAdminUser();
968
+            $appIds = (array)$request->getParam('appid');
969
+            foreach($appIds as $appId) {
970
+                $appId = \OC_App::cleanAppId($appId);
971
+                \OC_App::disable($appId);
972
+            }
973
+            \OC_JSON::success();
974
+            exit();
975
+        }
976
+
977
+        // Always load authentication apps
978
+        OC_App::loadApps(['authentication']);
979
+
980
+        // Load minimum set of apps
981
+        if (!self::checkUpgrade(false)
982
+            && !$systemConfig->getValue('maintenance', false)) {
983
+            // For logged-in users: Load everything
984
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
985
+                OC_App::loadApps();
986
+            } else {
987
+                // For guests: Load only filesystem and logging
988
+                OC_App::loadApps(array('filesystem', 'logging'));
989
+                self::handleLogin($request);
990
+            }
991
+        }
992
+
993
+        if (!self::$CLI) {
994
+            try {
995
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
996
+                    OC_App::loadApps(array('filesystem', 'logging'));
997
+                    OC_App::loadApps();
998
+                }
999
+                OC_Util::setupFS();
1000
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1001
+                return;
1002
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1003
+                //header('HTTP/1.0 404 Not Found');
1004
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1005
+                OC_Response::setStatus(405);
1006
+                return;
1007
+            }
1008
+        }
1009
+
1010
+        // Handle WebDAV
1011
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1012
+            // not allowed any more to prevent people
1013
+            // mounting this root directly.
1014
+            // Users need to mount remote.php/webdav instead.
1015
+            header('HTTP/1.1 405 Method Not Allowed');
1016
+            header('Status: 405 Method Not Allowed');
1017
+            return;
1018
+        }
1019
+
1020
+        // Someone is logged in
1021
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1022
+            OC_App::loadApps();
1023
+            OC_User::setupBackends();
1024
+            OC_Util::setupFS();
1025
+            // FIXME
1026
+            // Redirect to default application
1027
+            OC_Util::redirectToDefaultPage();
1028
+        } else {
1029
+            // Not handled and not logged in
1030
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1031
+        }
1032
+    }
1033
+
1034
+    /**
1035
+     * Check login: apache auth, auth token, basic auth
1036
+     *
1037
+     * @param OCP\IRequest $request
1038
+     * @return boolean
1039
+     */
1040
+    static function handleLogin(OCP\IRequest $request) {
1041
+        $userSession = self::$server->getUserSession();
1042
+        if (OC_User::handleApacheAuth()) {
1043
+            return true;
1044
+        }
1045
+        if ($userSession->tryTokenLogin($request)) {
1046
+            return true;
1047
+        }
1048
+        if (isset($_COOKIE['nc_username'])
1049
+            && isset($_COOKIE['nc_token'])
1050
+            && isset($_COOKIE['nc_session_id'])
1051
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1052
+            return true;
1053
+        }
1054
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1055
+            return true;
1056
+        }
1057
+        return false;
1058
+    }
1059
+
1060
+    protected static function handleAuthHeaders() {
1061
+        //copy http auth headers for apache+php-fcgid work around
1062
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1063
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1064
+        }
1065
+
1066
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1067
+        $vars = array(
1068
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1069
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1070
+        );
1071
+        foreach ($vars as $var) {
1072
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1073
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1074
+                $_SERVER['PHP_AUTH_USER'] = $name;
1075
+                $_SERVER['PHP_AUTH_PW'] = $password;
1076
+                break;
1077
+            }
1078
+        }
1079
+    }
1080 1080
 }
1081 1081
 
1082 1082
 OC::init();
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -119,14 +119,14 @@  discard block
 block discarded – undo
119 119
 	 * the app path list is empty or contains an invalid path
120 120
 	 */
121 121
 	public static function initPaths() {
122
-		if(defined('PHPUNIT_CONFIG_DIR')) {
123
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
124
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
125
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
126
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
-			self::$configDir = rtrim($dir, '/') . '/';
122
+		if (defined('PHPUNIT_CONFIG_DIR')) {
123
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
124
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
125
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
126
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
127
+			self::$configDir = rtrim($dir, '/').'/';
128 128
 		} else {
129
-			self::$configDir = OC::$SERVERROOT . '/config/';
129
+			self::$configDir = OC::$SERVERROOT.'/config/';
130 130
 		}
131 131
 		self::$config = new \OC\Config(self::$configDir);
132 132
 
@@ -148,9 +148,9 @@  discard block
 block discarded – undo
148 148
 			//make sure suburi follows the same rules as scriptName
149 149
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
150 150
 				if (substr(OC::$SUBURI, -1) != '/') {
151
-					OC::$SUBURI = OC::$SUBURI . '/';
151
+					OC::$SUBURI = OC::$SUBURI.'/';
152 152
 				}
153
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
153
+				OC::$SUBURI = OC::$SUBURI.'index.php';
154 154
 			}
155 155
 		}
156 156
 
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
163 163
 
164 164
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
165
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
165
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
166 166
 				}
167 167
 			} else {
168 168
 				// The scriptName is not ending with OC::$SUBURI
@@ -191,11 +191,11 @@  discard block
 block discarded – undo
191 191
 					OC::$APPSROOTS[] = $paths;
192 192
 				}
193 193
 			}
194
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
195
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
196
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
194
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
195
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
196
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
197 197
 			OC::$APPSROOTS[] = array(
198
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
198
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
199 199
 				'url' => '/apps',
200 200
 				'writable' => true
201 201
 			);
@@ -225,8 +225,8 @@  discard block
 block discarded – undo
225 225
 		$l = \OC::$server->getL10N('lib');
226 226
 
227 227
 		// Create config if it does not already exist
228
-		$configFilePath = self::$configDir .'/config.php';
229
-		if(!file_exists($configFilePath)) {
228
+		$configFilePath = self::$configDir.'/config.php';
229
+		if (!file_exists($configFilePath)) {
230 230
 			@touch($configFilePath);
231 231
 		}
232 232
 
@@ -241,13 +241,13 @@  discard block
 block discarded – undo
241 241
 				echo $l->t('Cannot write into "config" directory!')."\n";
242 242
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
243 243
 				echo "\n";
244
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
244
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
245 245
 				exit;
246 246
 			} else {
247 247
 				OC_Template::printErrorPage(
248 248
 					$l->t('Cannot write into "config" directory!'),
249 249
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
250
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
250
+					 [$urlGenerator->linkToDocs('admin-dir_permissions')])
251 251
 				);
252 252
 			}
253 253
 		}
@@ -262,8 +262,8 @@  discard block
 block discarded – undo
262 262
 			if (OC::$CLI) {
263 263
 				throw new Exception('Not installed');
264 264
 			} else {
265
-				$url = OC::$WEBROOT . '/index.php';
266
-				header('Location: ' . $url);
265
+				$url = OC::$WEBROOT.'/index.php';
266
+				header('Location: '.$url);
267 267
 			}
268 268
 			exit();
269 269
 		}
@@ -387,14 +387,14 @@  discard block
 block discarded – undo
387 387
 		$incompatibleShippedApps = [];
388 388
 		foreach ($incompatibleApps as $appInfo) {
389 389
 			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
390
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
391 391
 			}
392 392
 		}
393 393
 
394 394
 		if (!empty($incompatibleShippedApps)) {
395 395
 			$l = \OC::$server->getL10N('core');
396 396
 			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
397
+			throw new \OC\HintException('The files of the app '.implode(', ', $incompatibleShippedApps).' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398 398
 		}
399 399
 
400 400
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 		ini_set('session.cookie_httponly', true);
410 410
 
411 411
 		// set the cookie path to the Nextcloud directory
412
-		$cookie_path = OC::$WEBROOT ? : '/';
412
+		$cookie_path = OC::$WEBROOT ?: '/';
413 413
 		ini_set('session.cookie_path', $cookie_path);
414 414
 
415 415
 		// Let the session name be changed in the initSession Hook
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 		// session timeout
444 444
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
445 445
 			if (isset($_COOKIE[session_name()])) {
446
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
446
+				setcookie(session_name(), null, -1, self::$WEBROOT ?: '/');
447 447
 			}
448 448
 			\OC::$server->getUserSession()->logout();
449 449
 		}
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
 				continue;
466 466
 			}
467 467
 
468
-			$file = $appPath . '/appinfo/classpath.php';
468
+			$file = $appPath.'/appinfo/classpath.php';
469 469
 			if (file_exists($file)) {
470 470
 				require_once $file;
471 471
 			}
@@ -493,14 +493,14 @@  discard block
 block discarded – undo
493 493
 
494 494
 		// Append __Host to the cookie if it meets the requirements
495 495
 		$cookiePrefix = '';
496
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
496
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
497 497
 			$cookiePrefix = '__Host-';
498 498
 		}
499 499
 
500
-		foreach($policies as $policy) {
500
+		foreach ($policies as $policy) {
501 501
 			header(
502 502
 				sprintf(
503
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
503
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
504 504
 					$cookiePrefix,
505 505
 					$policy,
506 506
 					$cookieParams['path'],
@@ -531,14 +531,14 @@  discard block
 block discarded – undo
531 531
 			// OS X Finder
532 532
 			'/^WebDAVFS/',
533 533
 		];
534
-		if($request->isUserAgent($incompatibleUserAgents)) {
534
+		if ($request->isUserAgent($incompatibleUserAgents)) {
535 535
 			return;
536 536
 		}
537 537
 
538
-		if(count($_COOKIE) > 0) {
538
+		if (count($_COOKIE) > 0) {
539 539
 			$requestUri = $request->getScriptName();
540 540
 			$processingScript = explode('/', $requestUri);
541
-			$processingScript = $processingScript[count($processingScript)-1];
541
+			$processingScript = $processingScript[count($processingScript) - 1];
542 542
 			// FIXME: In a SAML scenario we don't get any strict or lax cookie
543 543
 			// send for the ACS endpoint. Since we have some legacy code in Nextcloud
544 544
 			// (direct PHP files) the enforcement of lax cookies is performed here
@@ -551,30 +551,30 @@  discard block
 block discarded – undo
551 551
 			// the verification into a middleware and also adds some exemptions.
552 552
 			//
553 553
 			// Questions about this code? Ask Lukas ;-)
554
-			$currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
555
-			if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
554
+			$currentUrl = substr(explode('?', $request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
555
+			if ($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
556 556
 				return;
557 557
 			}
558 558
 			// For the "index.php" endpoint only a lax cookie is required.
559
-			if($processingScript === 'index.php') {
560
-				if(!$request->passesLaxCookieCheck()) {
559
+			if ($processingScript === 'index.php') {
560
+				if (!$request->passesLaxCookieCheck()) {
561 561
 					self::sendSameSiteCookies();
562 562
 					header('Location: '.$_SERVER['REQUEST_URI']);
563 563
 					exit();
564 564
 				}
565 565
 			} else {
566 566
 				// All other endpoints require the lax and the strict cookie
567
-				if(!$request->passesStrictCookieCheck()) {
567
+				if (!$request->passesStrictCookieCheck()) {
568 568
 					self::sendSameSiteCookies();
569 569
 					// Debug mode gets access to the resources without strict cookie
570 570
 					// due to the fact that the SabreDAV browser also lives there.
571
-					if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
571
+					if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
572 572
 						http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
573 573
 						exit();
574 574
 					}
575 575
 				}
576 576
 			}
577
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
577
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578 578
 			self::sendSameSiteCookies();
579 579
 		}
580 580
 	}
@@ -585,12 +585,12 @@  discard block
 block discarded – undo
585 585
 
586 586
 		// register autoloader
587 587
 		$loaderStart = microtime(true);
588
-		require_once __DIR__ . '/autoloader.php';
588
+		require_once __DIR__.'/autoloader.php';
589 589
 		self::$loader = new \OC\Autoloader([
590
-			OC::$SERVERROOT . '/lib/private/legacy',
590
+			OC::$SERVERROOT.'/lib/private/legacy',
591 591
 		]);
592 592
 		if (defined('PHPUNIT_RUN')) {
593
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
593
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
594 594
 		}
595 595
 		spl_autoload_register(array(self::$loader, 'load'));
596 596
 		$loaderEnd = microtime(true);
@@ -598,12 +598,12 @@  discard block
 block discarded – undo
598 598
 		self::$CLI = (php_sapi_name() == 'cli');
599 599
 
600 600
 		// Add default composer PSR-4 autoloader
601
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
601
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
602 602
 
603 603
 		try {
604 604
 			self::initPaths();
605 605
 			// setup 3rdparty autoloader
606
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
606
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
607 607
 			if (!file_exists($vendorAutoLoad)) {
608 608
 				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
609 609
 			}
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
 			if (!self::$CLI) {
614 614
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
615 615
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
616
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
616
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
617 617
 			}
618 618
 			// we can't use the template error page here, because this needs the
619 619
 			// DI container which isn't available yet
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 		@ini_set('display_errors', 0);
632 632
 		@ini_set('log_errors', 1);
633 633
 
634
-		if(!date_default_timezone_set('UTC')) {
634
+		if (!date_default_timezone_set('UTC')) {
635 635
 			throw new \RuntimeException('Could not set timezone to UTC');
636 636
 		};
637 637
 
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		self::checkInstalled();
676 676
 
677 677
 		OC_Response::addSecurityHeaders();
678
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
678
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
679 679
 			ini_set('session.cookie_secure', true);
680 680
 		}
681 681
 
@@ -688,11 +688,11 @@  discard block
 block discarded – undo
688 688
 					// Convert l10n string into regular string for usage in database
689 689
 					$staticErrors = [];
690 690
 					foreach ($errors as $error) {
691
-						echo $error['error'] . "\n";
692
-						echo $error['hint'] . "\n\n";
691
+						echo $error['error']."\n";
692
+						echo $error['hint']."\n\n";
693 693
 						$staticErrors[] = [
694
-							'error' => (string)$error['error'],
695
-							'hint' => (string)$error['hint'],
694
+							'error' => (string) $error['error'],
695
+							'hint' => (string) $error['hint'],
696 696
 						];
697 697
 					}
698 698
 
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 		}
715 715
 		//try to set the session lifetime
716 716
 		$sessionLifeTime = self::getSessionLifeTime();
717
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
717
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
718 718
 
719 719
 		$systemConfig = \OC::$server->getSystemConfig();
720 720
 
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
762 762
 
763 763
 		// Check whether the sample configuration has been copied
764
-		if($systemConfig->getValue('copied_sample_config', false)) {
764
+		if ($systemConfig->getValue('copied_sample_config', false)) {
765 765
 			$l = \OC::$server->getL10N('lib');
766 766
 			header('HTTP/1.1 503 Service Temporarily Unavailable');
767 767
 			header('Status: 503 Service Temporarily Unavailable');
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 		) {
788 788
 			// Allow access to CSS resources
789 789
 			$isScssRequest = false;
790
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
790
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
791 791
 				$isScssRequest = true;
792 792
 			}
793 793
 
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
 
824 824
 			// NOTE: This will be replaced to use OCP
825 825
 			$userSession = self::$server->getUserSession();
826
-			$userSession->listen('\OC\User', 'postLogin', function () {
826
+			$userSession->listen('\OC\User', 'postLogin', function() {
827 827
 				try {
828 828
 					$cache = new \OC\Cache\File();
829 829
 					$cache->gc();
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 				} catch (\Exception $e) {
836 836
 					// a GC exception should not prevent users from using OC,
837 837
 					// so log the exception
838
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
838
+					\OC::$server->getLogger()->warning('Exception when running cache gc: '.$e->getMessage(), array('app' => 'core'));
839 839
 				}
840 840
 			});
841 841
 		}
@@ -851,7 +851,7 @@  discard block
 block discarded – undo
851 851
 			/** @var \OCP\App\ManagerEvent $event */
852 852
 			$jobList = \OC::$server->getJobList();
853 853
 			$job = 'OC\\Settings\\RemoveOrphaned';
854
-			if(!($jobList->has($job, null))) {
854
+			if (!($jobList->has($job, null))) {
855 855
 				$jobList->add($job);
856 856
 			}
857 857
 		});
@@ -961,12 +961,12 @@  discard block
 block discarded – undo
961 961
 		// emergency app disabling
962 962
 		if ($requestPath === '/disableapp'
963 963
 			&& $request->getMethod() === 'POST'
964
-			&& ((array)$request->getParam('appid')) !== ''
964
+			&& ((array) $request->getParam('appid')) !== ''
965 965
 		) {
966 966
 			\OCP\JSON::callCheck();
967 967
 			\OCP\JSON::checkAdminUser();
968
-			$appIds = (array)$request->getParam('appid');
969
-			foreach($appIds as $appId) {
968
+			$appIds = (array) $request->getParam('appid');
969
+			foreach ($appIds as $appId) {
970 970
 				$appId = \OC_App::cleanAppId($appId);
971 971
 				\OC_App::disable($appId);
972 972
 			}
@@ -981,7 +981,7 @@  discard block
 block discarded – undo
981 981
 		if (!self::checkUpgrade(false)
982 982
 			&& !$systemConfig->getValue('maintenance', false)) {
983 983
 			// For logged-in users: Load everything
984
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
984
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
985 985
 				OC_App::loadApps();
986 986
 			} else {
987 987
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
core/Middleware/TwoFactorMiddleware.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -41,100 +41,100 @@
 block discarded – undo
41 41
 
42 42
 class TwoFactorMiddleware extends Middleware {
43 43
 
44
-	/** @var Manager */
45
-	private $twoFactorManager;
46
-
47
-	/** @var Session */
48
-	private $userSession;
49
-
50
-	/** @var ISession */
51
-	private $session;
52
-
53
-	/** @var IURLGenerator */
54
-	private $urlGenerator;
55
-
56
-	/** @var IControllerMethodReflector */
57
-	private $reflector;
58
-
59
-	/** @var IRequest */
60
-	private $request;
61
-
62
-	/**
63
-	 * @param Manager $twoFactorManager
64
-	 * @param Session $userSession
65
-	 * @param ISession $session
66
-	 * @param IURLGenerator $urlGenerator
67
-	 */
68
-	public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
69
-		IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
70
-		$this->twoFactorManager = $twoFactorManager;
71
-		$this->userSession = $userSession;
72
-		$this->session = $session;
73
-		$this->urlGenerator = $urlGenerator;
74
-		$this->reflector = $reflector;
75
-		$this->request = $request;
76
-	}
77
-
78
-	/**
79
-	 * @param Controller $controller
80
-	 * @param string $methodName
81
-	 */
82
-	public function beforeController($controller, $methodName) {
83
-		if ($this->reflector->hasAnnotation('PublicPage')) {
84
-			// Don't block public pages
85
-			return;
86
-		}
87
-
88
-		if ($controller instanceof LoginController && $methodName === 'logout') {
89
-			// Don't block the logout page, to allow canceling the 2FA
90
-			return;
91
-		}
92
-
93
-		if ($this->userSession->isLoggedIn()) {
94
-			$user = $this->userSession->getUser();
95
-
96
-			if ($this->twoFactorManager->isTwoFactorAuthenticated($user)) {
97
-				$this->checkTwoFactor($controller, $methodName, $user);
98
-			} else if ($controller instanceof TwoFactorChallengeController) {
99
-				// Allow access to the two-factor controllers only if two-factor authentication
100
-				// is in progress.
101
-				throw new UserAlreadyLoggedInException();
102
-			}
103
-		}
104
-		// TODO: dont check/enforce 2FA if a auth token is used
105
-	}
106
-
107
-	private function checkTwoFactor($controller, $methodName, IUser $user) {
108
-		// If two-factor auth is in progress disallow access to any controllers
109
-		// defined within "LoginController".
110
-		$needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
111
-		$twoFactor = $controller instanceof TwoFactorChallengeController;
112
-
113
-		// Disallow access to any controller if 2FA needs to be checked
114
-		if ($needsSecondFactor && !$twoFactor) {
115
-			throw new TwoFactorAuthRequiredException();
116
-		}
117
-
118
-		// Allow access to the two-factor controllers only if two-factor authentication
119
-		// is in progress.
120
-		if (!$needsSecondFactor && $twoFactor) {
121
-			throw new UserAlreadyLoggedInException();
122
-		}
123
-	}
124
-
125
-	public function afterException($controller, $methodName, Exception $exception) {
126
-		if ($exception instanceof TwoFactorAuthRequiredException) {
127
-			$params = [];
128
-			if (isset($this->request->server['REQUEST_URI'])) {
129
-				$params['redirect_url'] = $this->request->server['REQUEST_URI'];
130
-			}
131
-			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
132
-		}
133
-		if ($exception instanceof UserAlreadyLoggedInException) {
134
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
135
-		}
136
-
137
-		throw $exception;
138
-	}
44
+    /** @var Manager */
45
+    private $twoFactorManager;
46
+
47
+    /** @var Session */
48
+    private $userSession;
49
+
50
+    /** @var ISession */
51
+    private $session;
52
+
53
+    /** @var IURLGenerator */
54
+    private $urlGenerator;
55
+
56
+    /** @var IControllerMethodReflector */
57
+    private $reflector;
58
+
59
+    /** @var IRequest */
60
+    private $request;
61
+
62
+    /**
63
+     * @param Manager $twoFactorManager
64
+     * @param Session $userSession
65
+     * @param ISession $session
66
+     * @param IURLGenerator $urlGenerator
67
+     */
68
+    public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
69
+        IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
70
+        $this->twoFactorManager = $twoFactorManager;
71
+        $this->userSession = $userSession;
72
+        $this->session = $session;
73
+        $this->urlGenerator = $urlGenerator;
74
+        $this->reflector = $reflector;
75
+        $this->request = $request;
76
+    }
77
+
78
+    /**
79
+     * @param Controller $controller
80
+     * @param string $methodName
81
+     */
82
+    public function beforeController($controller, $methodName) {
83
+        if ($this->reflector->hasAnnotation('PublicPage')) {
84
+            // Don't block public pages
85
+            return;
86
+        }
87
+
88
+        if ($controller instanceof LoginController && $methodName === 'logout') {
89
+            // Don't block the logout page, to allow canceling the 2FA
90
+            return;
91
+        }
92
+
93
+        if ($this->userSession->isLoggedIn()) {
94
+            $user = $this->userSession->getUser();
95
+
96
+            if ($this->twoFactorManager->isTwoFactorAuthenticated($user)) {
97
+                $this->checkTwoFactor($controller, $methodName, $user);
98
+            } else if ($controller instanceof TwoFactorChallengeController) {
99
+                // Allow access to the two-factor controllers only if two-factor authentication
100
+                // is in progress.
101
+                throw new UserAlreadyLoggedInException();
102
+            }
103
+        }
104
+        // TODO: dont check/enforce 2FA if a auth token is used
105
+    }
106
+
107
+    private function checkTwoFactor($controller, $methodName, IUser $user) {
108
+        // If two-factor auth is in progress disallow access to any controllers
109
+        // defined within "LoginController".
110
+        $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
111
+        $twoFactor = $controller instanceof TwoFactorChallengeController;
112
+
113
+        // Disallow access to any controller if 2FA needs to be checked
114
+        if ($needsSecondFactor && !$twoFactor) {
115
+            throw new TwoFactorAuthRequiredException();
116
+        }
117
+
118
+        // Allow access to the two-factor controllers only if two-factor authentication
119
+        // is in progress.
120
+        if (!$needsSecondFactor && $twoFactor) {
121
+            throw new UserAlreadyLoggedInException();
122
+        }
123
+    }
124
+
125
+    public function afterException($controller, $methodName, Exception $exception) {
126
+        if ($exception instanceof TwoFactorAuthRequiredException) {
127
+            $params = [];
128
+            if (isset($this->request->server['REQUEST_URI'])) {
129
+                $params['redirect_url'] = $this->request->server['REQUEST_URI'];
130
+            }
131
+            return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
132
+        }
133
+        if ($exception instanceof UserAlreadyLoggedInException) {
134
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
135
+        }
136
+
137
+        throw $exception;
138
+    }
139 139
 
140 140
 }
Please login to merge, or discard this patch.