Completed
Push — master ( 684ee6...1bb552 )
by Morris
203:09 queued 174:55
created
public.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -32,62 +32,62 @@
 block discarded – undo
32 32
 
33 33
 try {
34 34
 
35
-	require_once __DIR__ . '/lib/base.php';
36
-	if (\OCP\Util::needUpgrade()) {
37
-		// since the behavior of apps or remotes are unpredictable during
38
-		// an upgrade, return a 503 directly
39
-		OC_Template::printErrorPage('Service unavailable', '', OC_Response::STATUS_SERVICE_UNAVAILABLE);
40
-		exit;
41
-	}
35
+    require_once __DIR__ . '/lib/base.php';
36
+    if (\OCP\Util::needUpgrade()) {
37
+        // since the behavior of apps or remotes are unpredictable during
38
+        // an upgrade, return a 503 directly
39
+        OC_Template::printErrorPage('Service unavailable', '', OC_Response::STATUS_SERVICE_UNAVAILABLE);
40
+        exit;
41
+    }
42 42
 
43
-	OC::checkMaintenanceMode();
44
-	$request = \OC::$server->getRequest();
45
-	$pathInfo = $request->getPathInfo();
43
+    OC::checkMaintenanceMode();
44
+    $request = \OC::$server->getRequest();
45
+    $pathInfo = $request->getPathInfo();
46 46
 
47
-	if (!$pathInfo && $request->getParam('service', '') === '') {
48
-		header('HTTP/1.0 404 Not Found');
49
-		exit;
50
-	} elseif ($request->getParam('service', '')) {
51
-		$service = $request->getParam('service', '');
52
-	} else {
53
-		$pathInfo = trim($pathInfo, '/');
54
-		list($service) = explode('/', $pathInfo);
55
-	}
56
-	$file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
57
-	if ($file === null) {
58
-		header('HTTP/1.0 404 Not Found');
59
-		exit;
60
-	}
47
+    if (!$pathInfo && $request->getParam('service', '') === '') {
48
+        header('HTTP/1.0 404 Not Found');
49
+        exit;
50
+    } elseif ($request->getParam('service', '')) {
51
+        $service = $request->getParam('service', '');
52
+    } else {
53
+        $pathInfo = trim($pathInfo, '/');
54
+        list($service) = explode('/', $pathInfo);
55
+    }
56
+    $file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
57
+    if ($file === null) {
58
+        header('HTTP/1.0 404 Not Found');
59
+        exit;
60
+    }
61 61
 
62
-	$parts = explode('/', $file, 2);
63
-	$app = $parts[0];
62
+    $parts = explode('/', $file, 2);
63
+    $app = $parts[0];
64 64
 
65
-	// Load all required applications
66
-	\OC::$REQUESTEDAPP = $app;
67
-	OC_App::loadApps(array('authentication'));
68
-	OC_App::loadApps(array('filesystem', 'logging'));
65
+    // Load all required applications
66
+    \OC::$REQUESTEDAPP = $app;
67
+    OC_App::loadApps(array('authentication'));
68
+    OC_App::loadApps(array('filesystem', 'logging'));
69 69
 
70
-	if (!\OC::$server->getAppManager()->isInstalled($app)) {
71
-		throw new Exception('App not installed: ' . $app);
72
-	}
73
-	OC_App::loadApp($app);
74
-	OC_User::setIncognitoMode(true);
70
+    if (!\OC::$server->getAppManager()->isInstalled($app)) {
71
+        throw new Exception('App not installed: ' . $app);
72
+    }
73
+    OC_App::loadApp($app);
74
+    OC_User::setIncognitoMode(true);
75 75
 
76
-	$baseuri = OC::$WEBROOT . '/public.php/' . $service . '/';
76
+    $baseuri = OC::$WEBROOT . '/public.php/' . $service . '/';
77 77
 
78
-	require_once OC_App::getAppPath($app) . '/' . $parts[1];
78
+    require_once OC_App::getAppPath($app) . '/' . $parts[1];
79 79
 
80 80
 } catch (Exception $ex) {
81
-	if ($ex instanceof \OC\ServiceUnavailableException) {
82
-		$status = OC_Response::STATUS_SERVICE_UNAVAILABLE;
83
-	} else {
84
-		$status = OC_Response::STATUS_INTERNAL_SERVER_ERROR;
85
-	}
86
-	//show the user a detailed error page
87
-	\OC::$server->getLogger()->logException($ex, ['app' => 'public']);
88
-	OC_Template::printExceptionErrorPage($ex, $status);
81
+    if ($ex instanceof \OC\ServiceUnavailableException) {
82
+        $status = OC_Response::STATUS_SERVICE_UNAVAILABLE;
83
+    } else {
84
+        $status = OC_Response::STATUS_INTERNAL_SERVER_ERROR;
85
+    }
86
+    //show the user a detailed error page
87
+    \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
88
+    OC_Template::printExceptionErrorPage($ex, $status);
89 89
 } catch (Error $ex) {
90
-	//show the user a detailed error page
91
-	\OC::$server->getLogger()->logException($ex, ['app' => 'public']);
92
-	OC_Template::printExceptionErrorPage($ex, OC_Response::STATUS_INTERNAL_SERVER_ERROR);
90
+    //show the user a detailed error page
91
+    \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
92
+    OC_Template::printExceptionErrorPage($ex, OC_Response::STATUS_INTERNAL_SERVER_ERROR);
93 93
 }
Please login to merge, or discard this patch.
index.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -37,56 +37,56 @@
 block discarded – undo
37 37
 
38 38
 try {
39 39
 
40
-	require_once __DIR__ . '/lib/base.php';
40
+    require_once __DIR__ . '/lib/base.php';
41 41
 
42
-	OC::handleRequest();
42
+    OC::handleRequest();
43 43
 
44 44
 } catch(\OC\ServiceUnavailableException $ex) {
45
-	\OC::$server->getLogger()->logException($ex, array('app' => 'index'));
45
+    \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
46 46
 
47
-	//show the user a detailed error page
48
-	OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_SERVICE_UNAVAILABLE);
47
+    //show the user a detailed error page
48
+    OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_SERVICE_UNAVAILABLE);
49 49
 } catch (\OC\HintException $ex) {
50
-	try {
51
-		OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), OC_Response::STATUS_SERVICE_UNAVAILABLE);
52
-	} catch (Exception $ex2) {
53
-		\OC::$server->getLogger()->logException($ex, array('app' => 'index'));
54
-		\OC::$server->getLogger()->logException($ex2, array('app' => 'index'));
50
+    try {
51
+        OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), OC_Response::STATUS_SERVICE_UNAVAILABLE);
52
+    } catch (Exception $ex2) {
53
+        \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
54
+        \OC::$server->getLogger()->logException($ex2, array('app' => 'index'));
55 55
 
56
-		//show the user a detailed error page
57
-		OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_INTERNAL_SERVER_ERROR);
58
-	}
56
+        //show the user a detailed error page
57
+        OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_INTERNAL_SERVER_ERROR);
58
+    }
59 59
 } catch (\OC\User\LoginException $ex) {
60
-	OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), OC_Response::STATUS_FORBIDDEN);
60
+    OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), OC_Response::STATUS_FORBIDDEN);
61 61
 } catch (Exception $ex) {
62
-	\OC::$server->getLogger()->logException($ex, array('app' => 'index'));
62
+    \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
63 63
 
64
-	//show the user a detailed error page
65
-	OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
66
-	OC_Template::printExceptionErrorPage($ex);
64
+    //show the user a detailed error page
65
+    OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
66
+    OC_Template::printExceptionErrorPage($ex);
67 67
 } catch (Error $ex) {
68
-	try {
69
-		\OC::$server->getLogger()->logException($ex, array('app' => 'index'));
70
-	} catch (Error $e) {
68
+    try {
69
+        \OC::$server->getLogger()->logException($ex, array('app' => 'index'));
70
+    } catch (Error $e) {
71 71
 
72
-		$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
73
-		$validProtocols = [
74
-			'HTTP/1.0',
75
-			'HTTP/1.1',
76
-			'HTTP/2',
77
-		];
78
-		$protocol = 'HTTP/1.1';
79
-		if(in_array($claimedProtocol, $validProtocols, true)) {
80
-			$protocol = $claimedProtocol;
81
-		}
82
-		header($protocol . ' 500 Internal Server Error');
83
-		header('Content-Type: text/plain; charset=utf-8');
84
-		print("Internal Server Error\n\n");
85
-		print("The server encountered an internal error and was unable to complete your request.\n");
86
-		print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
87
-		print("More details can be found in the webserver log.\n");
72
+        $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
73
+        $validProtocols = [
74
+            'HTTP/1.0',
75
+            'HTTP/1.1',
76
+            'HTTP/2',
77
+        ];
78
+        $protocol = 'HTTP/1.1';
79
+        if(in_array($claimedProtocol, $validProtocols, true)) {
80
+            $protocol = $claimedProtocol;
81
+        }
82
+        header($protocol . ' 500 Internal Server Error');
83
+        header('Content-Type: text/plain; charset=utf-8');
84
+        print("Internal Server Error\n\n");
85
+        print("The server encountered an internal error and was unable to complete your request.\n");
86
+        print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
87
+        print("More details can be found in the webserver log.\n");
88 88
 
89
-		throw $e;
90
-	}
91
-	OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_INTERNAL_SERVER_ERROR);
89
+        throw $e;
90
+    }
91
+    OC_Template::printExceptionErrorPage($ex, \OC_Response::STATUS_INTERNAL_SERVER_ERROR);
92 92
 }
Please login to merge, or discard this patch.
remote.php 1 patch
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -46,43 +46,43 @@  discard block
 block discarded – undo
46 46
  * @param Exception|Error $e
47 47
  */
48 48
 function handleException($e) {
49
-	$request = \OC::$server->getRequest();
50
-	// in case the request content type is text/xml - we assume it's a WebDAV request
51
-	$isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml');
52
-	if ($isXmlContentType === 0) {
53
-		// fire up a simple server to properly process the exception
54
-		$server = new Server();
55
-		if (!($e instanceof RemoteException)) {
56
-			// we shall not log on RemoteException
57
-			$server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->getLogger()));
58
-		}
59
-		$server->on('beforeMethod', function () use ($e) {
60
-			if ($e instanceof RemoteException) {
61
-				switch ($e->getCode()) {
62
-					case OC_Response::STATUS_SERVICE_UNAVAILABLE:
63
-						throw new ServiceUnavailable($e->getMessage());
64
-					case OC_Response::STATUS_NOT_FOUND:
65
-						throw new \Sabre\DAV\Exception\NotFound($e->getMessage());
66
-				}
67
-			}
68
-			$class = get_class($e);
69
-			$msg = $e->getMessage();
70
-			throw new ServiceUnavailable("$class: $msg");
71
-		});
72
-		$server->exec();
73
-	} else {
74
-		$statusCode = OC_Response::STATUS_INTERNAL_SERVER_ERROR;
75
-		if ($e instanceof \OC\ServiceUnavailableException ) {
76
-			$statusCode = OC_Response::STATUS_SERVICE_UNAVAILABLE;
77
-		}
78
-		if ($e instanceof RemoteException) {
79
-			// we shall not log on RemoteException
80
-			OC_Template::printErrorPage($e->getMessage(), '', $e->getCode());
81
-		} else {
82
-			\OC::$server->getLogger()->logException($e, ['app' => 'remote']);
83
-			OC_Template::printExceptionErrorPage($e, $statusCode);
84
-		}
85
-	}
49
+    $request = \OC::$server->getRequest();
50
+    // in case the request content type is text/xml - we assume it's a WebDAV request
51
+    $isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml');
52
+    if ($isXmlContentType === 0) {
53
+        // fire up a simple server to properly process the exception
54
+        $server = new Server();
55
+        if (!($e instanceof RemoteException)) {
56
+            // we shall not log on RemoteException
57
+            $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->getLogger()));
58
+        }
59
+        $server->on('beforeMethod', function () use ($e) {
60
+            if ($e instanceof RemoteException) {
61
+                switch ($e->getCode()) {
62
+                    case OC_Response::STATUS_SERVICE_UNAVAILABLE:
63
+                        throw new ServiceUnavailable($e->getMessage());
64
+                    case OC_Response::STATUS_NOT_FOUND:
65
+                        throw new \Sabre\DAV\Exception\NotFound($e->getMessage());
66
+                }
67
+            }
68
+            $class = get_class($e);
69
+            $msg = $e->getMessage();
70
+            throw new ServiceUnavailable("$class: $msg");
71
+        });
72
+        $server->exec();
73
+    } else {
74
+        $statusCode = OC_Response::STATUS_INTERNAL_SERVER_ERROR;
75
+        if ($e instanceof \OC\ServiceUnavailableException ) {
76
+            $statusCode = OC_Response::STATUS_SERVICE_UNAVAILABLE;
77
+        }
78
+        if ($e instanceof RemoteException) {
79
+            // we shall not log on RemoteException
80
+            OC_Template::printErrorPage($e->getMessage(), '', $e->getCode());
81
+        } else {
82
+            \OC::$server->getLogger()->logException($e, ['app' => 'remote']);
83
+            OC_Template::printExceptionErrorPage($e, $statusCode);
84
+        }
85
+    }
86 86
 }
87 87
 
88 88
 /**
@@ -90,80 +90,80 @@  discard block
 block discarded – undo
90 90
  * @return string
91 91
  */
92 92
 function resolveService($service) {
93
-	$services = [
94
-		'webdav' => 'dav/appinfo/v1/webdav.php',
95
-		'dav' => 'dav/appinfo/v2/remote.php',
96
-		'caldav' => 'dav/appinfo/v1/caldav.php',
97
-		'calendar' => 'dav/appinfo/v1/caldav.php',
98
-		'carddav' => 'dav/appinfo/v1/carddav.php',
99
-		'contacts' => 'dav/appinfo/v1/carddav.php',
100
-		'files' => 'dav/appinfo/v1/webdav.php',
101
-		'direct' => 'dav/appinfo/v2/direct.php',
102
-	];
103
-	if (isset($services[$service])) {
104
-		return $services[$service];
105
-	}
106
-
107
-	return \OC::$server->getConfig()->getAppValue('core', 'remote_' . $service);
93
+    $services = [
94
+        'webdav' => 'dav/appinfo/v1/webdav.php',
95
+        'dav' => 'dav/appinfo/v2/remote.php',
96
+        'caldav' => 'dav/appinfo/v1/caldav.php',
97
+        'calendar' => 'dav/appinfo/v1/caldav.php',
98
+        'carddav' => 'dav/appinfo/v1/carddav.php',
99
+        'contacts' => 'dav/appinfo/v1/carddav.php',
100
+        'files' => 'dav/appinfo/v1/webdav.php',
101
+        'direct' => 'dav/appinfo/v2/direct.php',
102
+    ];
103
+    if (isset($services[$service])) {
104
+        return $services[$service];
105
+    }
106
+
107
+    return \OC::$server->getConfig()->getAppValue('core', 'remote_' . $service);
108 108
 }
109 109
 
110 110
 try {
111
-	require_once __DIR__ . '/lib/base.php';
112
-
113
-	// All resources served via the DAV endpoint should have the strictest possible
114
-	// policy. Exempted from this is the SabreDAV browser plugin which overwrites
115
-	// this policy with a softer one if debug mode is enabled.
116
-	header("Content-Security-Policy: default-src 'none';");
117
-
118
-	if (\OCP\Util::needUpgrade()) {
119
-		// since the behavior of apps or remotes are unpredictable during
120
-		// an upgrade, return a 503 directly
121
-		throw new RemoteException('Service unavailable', OC_Response::STATUS_SERVICE_UNAVAILABLE);
122
-	}
123
-
124
-	$request = \OC::$server->getRequest();
125
-	$pathInfo = $request->getPathInfo();
126
-	if ($pathInfo === false || $pathInfo === '') {
127
-		throw new RemoteException('Path not found', OC_Response::STATUS_NOT_FOUND);
128
-	}
129
-	if (!$pos = strpos($pathInfo, '/', 1)) {
130
-		$pos = strlen($pathInfo);
131
-	}
132
-	$service=substr($pathInfo, 1, $pos-1);
133
-
134
-	$file = resolveService($service);
135
-
136
-	if(is_null($file)) {
137
-		throw new RemoteException('Path not found', OC_Response::STATUS_NOT_FOUND);
138
-	}
139
-
140
-	$file=ltrim($file, '/');
141
-
142
-	$parts=explode('/', $file, 2);
143
-	$app=$parts[0];
144
-
145
-	// Load all required applications
146
-	\OC::$REQUESTEDAPP = $app;
147
-	OC_App::loadApps(array('authentication'));
148
-	OC_App::loadApps(array('filesystem', 'logging'));
149
-
150
-	switch ($app) {
151
-		case 'core':
152
-			$file =  OC::$SERVERROOT .'/'. $file;
153
-			break;
154
-		default:
155
-			if (!\OC::$server->getAppManager()->isInstalled($app)) {
156
-				throw new RemoteException('App not installed: ' . $app);
157
-			}
158
-			OC_App::loadApp($app);
159
-			$file = OC_App::getAppPath($app) .'/'. $parts[1];
160
-			break;
161
-	}
162
-	$baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
163
-	require_once $file;
111
+    require_once __DIR__ . '/lib/base.php';
112
+
113
+    // All resources served via the DAV endpoint should have the strictest possible
114
+    // policy. Exempted from this is the SabreDAV browser plugin which overwrites
115
+    // this policy with a softer one if debug mode is enabled.
116
+    header("Content-Security-Policy: default-src 'none';");
117
+
118
+    if (\OCP\Util::needUpgrade()) {
119
+        // since the behavior of apps or remotes are unpredictable during
120
+        // an upgrade, return a 503 directly
121
+        throw new RemoteException('Service unavailable', OC_Response::STATUS_SERVICE_UNAVAILABLE);
122
+    }
123
+
124
+    $request = \OC::$server->getRequest();
125
+    $pathInfo = $request->getPathInfo();
126
+    if ($pathInfo === false || $pathInfo === '') {
127
+        throw new RemoteException('Path not found', OC_Response::STATUS_NOT_FOUND);
128
+    }
129
+    if (!$pos = strpos($pathInfo, '/', 1)) {
130
+        $pos = strlen($pathInfo);
131
+    }
132
+    $service=substr($pathInfo, 1, $pos-1);
133
+
134
+    $file = resolveService($service);
135
+
136
+    if(is_null($file)) {
137
+        throw new RemoteException('Path not found', OC_Response::STATUS_NOT_FOUND);
138
+    }
139
+
140
+    $file=ltrim($file, '/');
141
+
142
+    $parts=explode('/', $file, 2);
143
+    $app=$parts[0];
144
+
145
+    // Load all required applications
146
+    \OC::$REQUESTEDAPP = $app;
147
+    OC_App::loadApps(array('authentication'));
148
+    OC_App::loadApps(array('filesystem', 'logging'));
149
+
150
+    switch ($app) {
151
+        case 'core':
152
+            $file =  OC::$SERVERROOT .'/'. $file;
153
+            break;
154
+        default:
155
+            if (!\OC::$server->getAppManager()->isInstalled($app)) {
156
+                throw new RemoteException('App not installed: ' . $app);
157
+            }
158
+            OC_App::loadApp($app);
159
+            $file = OC_App::getAppPath($app) .'/'. $parts[1];
160
+            break;
161
+    }
162
+    $baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
163
+    require_once $file;
164 164
 
165 165
 } catch (Exception $ex) {
166
-	handleException($ex);
166
+    handleException($ex);
167 167
 } catch (Error $e) {
168
-	handleException($e);
168
+    handleException($e);
169 169
 }
Please login to merge, or discard this patch.
lib/private/legacy/files.php 1 patch
Indentation   +430 added lines, -430 removed lines patch added patch discarded remove patch
@@ -49,438 +49,438 @@
 block discarded – undo
49 49
  *
50 50
  */
51 51
 class OC_Files {
52
-	const FILE = 1;
53
-	const ZIP_FILES = 2;
54
-	const ZIP_DIR = 3;
55
-
56
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
-
58
-
59
-	private static $multipartBoundary = '';
60
-
61
-	/**
62
-	 * @return string
63
-	 */
64
-	private static function getBoundary() {
65
-		if (empty(self::$multipartBoundary)) {
66
-			self::$multipartBoundary = md5(mt_rand());
67
-		}
68
-		return self::$multipartBoundary;
69
-	}
70
-
71
-	/**
72
-	 * @param string $filename
73
-	 * @param string $name
74
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
-	 */
76
-	private static function sendHeaders($filename, $name, array $rangeArray) {
77
-		OC_Response::setContentDispositionHeader($name, 'attachment');
78
-		header('Content-Transfer-Encoding: binary', true);
79
-		header('Pragma: public');// enable caching in IE
80
-		header('Expires: 0');
81
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
83
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
-		if ($fileSize > -1) {
85
-			if (!empty($rangeArray)) {
86
-			    header('HTTP/1.1 206 Partial Content', true);
87
-			    header('Accept-Ranges: bytes', true);
88
-			    if (count($rangeArray) > 1) {
89
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
90
-				// no Content-Length header here
91
-			    }
92
-			    else {
93
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
-			    }
96
-			}
97
-			else {
98
-			    OC_Response::setContentLengthHeader($fileSize);
99
-			}
100
-		}
101
-		header('Content-Type: '.$type, true);
102
-	}
103
-
104
-	/**
105
-	 * return the content of a file or return a zip file containing multiple files
106
-	 *
107
-	 * @param string $dir
108
-	 * @param string $files ; separated list of files to download
109
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
-	 */
111
-	public static function get($dir, $files, $params = null) {
112
-
113
-		$view = \OC\Files\Filesystem::getView();
114
-		$getType = self::FILE;
115
-		$filename = $dir;
116
-		try {
117
-
118
-			if (is_array($files) && count($files) === 1) {
119
-				$files = $files[0];
120
-			}
121
-
122
-			if (!is_array($files)) {
123
-				$filename = $dir . '/' . $files;
124
-				if (!$view->is_dir($filename)) {
125
-					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
-					return;
127
-				}
128
-			}
129
-
130
-			$name = 'download';
131
-			if (is_array($files)) {
132
-				$getType = self::ZIP_FILES;
133
-				$basename = basename($dir);
134
-				if ($basename) {
135
-					$name = $basename;
136
-				}
137
-
138
-				$filename = $dir . '/' . $name;
139
-			} else {
140
-				$filename = $dir . '/' . $files;
141
-				$getType = self::ZIP_DIR;
142
-				// downloading root ?
143
-				if ($files !== '') {
144
-					$name = $files;
145
-				}
146
-			}
147
-
148
-			self::lockFiles($view, $dir, $files);
149
-
150
-			/* Calculate filesize and number of files */
151
-			if ($getType === self::ZIP_FILES) {
152
-				$fileInfos = array();
153
-				$fileSize = 0;
154
-				foreach ($files as $file) {
155
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
-					$fileSize += $fileInfo->getSize();
157
-					$fileInfos[] = $fileInfo;
158
-				}
159
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
160
-			} elseif ($getType === self::ZIP_DIR) {
161
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
-				$fileSize = $fileInfo->getSize();
163
-				$numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
-			}
165
-
166
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
-			OC_Util::obEnd();
168
-
169
-			$streamer->sendHeaders($name);
170
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
-				@set_time_limit(0);
173
-			}
174
-			ignore_user_abort(true);
175
-
176
-			if ($getType === self::ZIP_FILES) {
177
-				foreach ($files as $file) {
178
-					$file = $dir . '/' . $file;
179
-					if (\OC\Files\Filesystem::is_file($file)) {
180
-						$fileSize = \OC\Files\Filesystem::filesize($file);
181
-						$fileTime = \OC\Files\Filesystem::filemtime($file);
182
-						$fh = \OC\Files\Filesystem::fopen($file, 'r');
183
-						$streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
-						fclose($fh);
185
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
186
-						$streamer->addDirRecursive($file);
187
-					}
188
-				}
189
-			} elseif ($getType === self::ZIP_DIR) {
190
-				$file = $dir . '/' . $files;
191
-				$streamer->addDirRecursive($file);
192
-			}
193
-			$streamer->finalize();
194
-			set_time_limit($executionTime);
195
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
-		} catch (\OCP\Lock\LockedException $ex) {
197
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
-			OC::$server->getLogger()->logException($ex);
199
-			$l = \OC::$server->getL10N('core');
200
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
202
-		} catch (\OCP\Files\ForbiddenException $ex) {
203
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
-			OC::$server->getLogger()->logException($ex);
205
-			$l = \OC::$server->getL10N('core');
206
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
207
-		} catch (\Exception $ex) {
208
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
-			OC::$server->getLogger()->logException($ex);
210
-			$l = \OC::$server->getL10N('core');
211
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * @param string $rangeHeaderPos
218
-	 * @param int $fileSize
219
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
-	 */
221
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
-		$rArray=explode(',', $rangeHeaderPos);
223
-		$minOffset = 0;
224
-		$ind = 0;
225
-
226
-		$rangeArray = array();
227
-
228
-		foreach ($rArray as $value) {
229
-			$ranges = explode('-', $value);
230
-			if (is_numeric($ranges[0])) {
231
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
-					$ranges[0] = $minOffset;
233
-				}
234
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
-					$ind--;
236
-					$ranges[0] = $rangeArray[$ind]['from'];
237
-				}
238
-			}
239
-
240
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
-				// case: x-x
242
-				if ($ranges[1] >= $fileSize) {
243
-					$ranges[1] = $fileSize-1;
244
-				}
245
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
-				$minOffset = $ranges[1] + 1;
247
-				if ($minOffset >= $fileSize) {
248
-					break;
249
-				}
250
-			}
251
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
-				// case: x-
253
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
-				break;
255
-			}
256
-			elseif (is_numeric($ranges[1])) {
257
-				// case: -x
258
-				if ($ranges[1] > $fileSize) {
259
-					$ranges[1] = $fileSize;
260
-				}
261
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
-				break;
263
-			}
264
-		}
265
-		return $rangeArray;
266
-	}
267
-
268
-	/**
269
-	 * @param View $view
270
-	 * @param string $name
271
-	 * @param string $dir
272
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
-	 */
274
-	private static function getSingleFile($view, $dir, $name, $params) {
275
-		$filename = $dir . '/' . $name;
276
-		OC_Util::obEnd();
277
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
52
+    const FILE = 1;
53
+    const ZIP_FILES = 2;
54
+    const ZIP_DIR = 3;
55
+
56
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
+
58
+
59
+    private static $multipartBoundary = '';
60
+
61
+    /**
62
+     * @return string
63
+     */
64
+    private static function getBoundary() {
65
+        if (empty(self::$multipartBoundary)) {
66
+            self::$multipartBoundary = md5(mt_rand());
67
+        }
68
+        return self::$multipartBoundary;
69
+    }
70
+
71
+    /**
72
+     * @param string $filename
73
+     * @param string $name
74
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
+     */
76
+    private static function sendHeaders($filename, $name, array $rangeArray) {
77
+        OC_Response::setContentDispositionHeader($name, 'attachment');
78
+        header('Content-Transfer-Encoding: binary', true);
79
+        header('Pragma: public');// enable caching in IE
80
+        header('Expires: 0');
81
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
83
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
+        if ($fileSize > -1) {
85
+            if (!empty($rangeArray)) {
86
+                header('HTTP/1.1 206 Partial Content', true);
87
+                header('Accept-Ranges: bytes', true);
88
+                if (count($rangeArray) > 1) {
89
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
90
+                // no Content-Length header here
91
+                }
92
+                else {
93
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
+                }
96
+            }
97
+            else {
98
+                OC_Response::setContentLengthHeader($fileSize);
99
+            }
100
+        }
101
+        header('Content-Type: '.$type, true);
102
+    }
103
+
104
+    /**
105
+     * return the content of a file or return a zip file containing multiple files
106
+     *
107
+     * @param string $dir
108
+     * @param string $files ; separated list of files to download
109
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
+     */
111
+    public static function get($dir, $files, $params = null) {
112
+
113
+        $view = \OC\Files\Filesystem::getView();
114
+        $getType = self::FILE;
115
+        $filename = $dir;
116
+        try {
117
+
118
+            if (is_array($files) && count($files) === 1) {
119
+                $files = $files[0];
120
+            }
121
+
122
+            if (!is_array($files)) {
123
+                $filename = $dir . '/' . $files;
124
+                if (!$view->is_dir($filename)) {
125
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
+                    return;
127
+                }
128
+            }
129
+
130
+            $name = 'download';
131
+            if (is_array($files)) {
132
+                $getType = self::ZIP_FILES;
133
+                $basename = basename($dir);
134
+                if ($basename) {
135
+                    $name = $basename;
136
+                }
137
+
138
+                $filename = $dir . '/' . $name;
139
+            } else {
140
+                $filename = $dir . '/' . $files;
141
+                $getType = self::ZIP_DIR;
142
+                // downloading root ?
143
+                if ($files !== '') {
144
+                    $name = $files;
145
+                }
146
+            }
147
+
148
+            self::lockFiles($view, $dir, $files);
149
+
150
+            /* Calculate filesize and number of files */
151
+            if ($getType === self::ZIP_FILES) {
152
+                $fileInfos = array();
153
+                $fileSize = 0;
154
+                foreach ($files as $file) {
155
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
+                    $fileSize += $fileInfo->getSize();
157
+                    $fileInfos[] = $fileInfo;
158
+                }
159
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
160
+            } elseif ($getType === self::ZIP_DIR) {
161
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
+                $fileSize = $fileInfo->getSize();
163
+                $numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
+            }
165
+
166
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
+            OC_Util::obEnd();
168
+
169
+            $streamer->sendHeaders($name);
170
+            $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
+                @set_time_limit(0);
173
+            }
174
+            ignore_user_abort(true);
175
+
176
+            if ($getType === self::ZIP_FILES) {
177
+                foreach ($files as $file) {
178
+                    $file = $dir . '/' . $file;
179
+                    if (\OC\Files\Filesystem::is_file($file)) {
180
+                        $fileSize = \OC\Files\Filesystem::filesize($file);
181
+                        $fileTime = \OC\Files\Filesystem::filemtime($file);
182
+                        $fh = \OC\Files\Filesystem::fopen($file, 'r');
183
+                        $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
+                        fclose($fh);
185
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
186
+                        $streamer->addDirRecursive($file);
187
+                    }
188
+                }
189
+            } elseif ($getType === self::ZIP_DIR) {
190
+                $file = $dir . '/' . $files;
191
+                $streamer->addDirRecursive($file);
192
+            }
193
+            $streamer->finalize();
194
+            set_time_limit($executionTime);
195
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
+        } catch (\OCP\Lock\LockedException $ex) {
197
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
+            OC::$server->getLogger()->logException($ex);
199
+            $l = \OC::$server->getL10N('core');
200
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
202
+        } catch (\OCP\Files\ForbiddenException $ex) {
203
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
+            OC::$server->getLogger()->logException($ex);
205
+            $l = \OC::$server->getL10N('core');
206
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
207
+        } catch (\Exception $ex) {
208
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
+            OC::$server->getLogger()->logException($ex);
210
+            $l = \OC::$server->getL10N('core');
211
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
213
+        }
214
+    }
215
+
216
+    /**
217
+     * @param string $rangeHeaderPos
218
+     * @param int $fileSize
219
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
+     */
221
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
+        $rArray=explode(',', $rangeHeaderPos);
223
+        $minOffset = 0;
224
+        $ind = 0;
225
+
226
+        $rangeArray = array();
227
+
228
+        foreach ($rArray as $value) {
229
+            $ranges = explode('-', $value);
230
+            if (is_numeric($ranges[0])) {
231
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
+                    $ranges[0] = $minOffset;
233
+                }
234
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
+                    $ind--;
236
+                    $ranges[0] = $rangeArray[$ind]['from'];
237
+                }
238
+            }
239
+
240
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
+                // case: x-x
242
+                if ($ranges[1] >= $fileSize) {
243
+                    $ranges[1] = $fileSize-1;
244
+                }
245
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
+                $minOffset = $ranges[1] + 1;
247
+                if ($minOffset >= $fileSize) {
248
+                    break;
249
+                }
250
+            }
251
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
+                // case: x-
253
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
+                break;
255
+            }
256
+            elseif (is_numeric($ranges[1])) {
257
+                // case: -x
258
+                if ($ranges[1] > $fileSize) {
259
+                    $ranges[1] = $fileSize;
260
+                }
261
+                $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
+                break;
263
+            }
264
+        }
265
+        return $rangeArray;
266
+    }
267
+
268
+    /**
269
+     * @param View $view
270
+     * @param string $name
271
+     * @param string $dir
272
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
+     */
274
+    private static function getSingleFile($view, $dir, $name, $params) {
275
+        $filename = $dir . '/' . $name;
276
+        OC_Util::obEnd();
277
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
278 278
 		
279
-		$rangeArray = array();
279
+        $rangeArray = array();
280 280
 
281
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
-								 \OC\Files\Filesystem::filesize($filename));
284
-		}
281
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
+                                    \OC\Files\Filesystem::filesize($filename));
284
+        }
285 285
 		
286
-		if (\OC\Files\Filesystem::isReadable($filename)) {
287
-			self::sendHeaders($filename, $name, $rangeArray);
288
-		} elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
-			header("HTTP/1.1 404 Not Found");
290
-			$tmpl = new OC_Template('', '404', 'guest');
291
-			$tmpl->printPage();
292
-			exit();
293
-		} else {
294
-			header("HTTP/1.1 403 Forbidden");
295
-			die('403 Forbidden');
296
-		}
297
-		if (isset($params['head']) && $params['head']) {
298
-			return;
299
-		}
300
-		if (!empty($rangeArray)) {
301
-			try {
302
-			    if (count($rangeArray) == 1) {
303
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
-			    }
305
-			    else {
306
-				// check if file is seekable (if not throw UnseekableException)
307
-				// we have to check it before body contents
308
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
-
310
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
-
312
-				foreach ($rangeArray as $range) {
313
-				    echo "\r\n--".self::getBoundary()."\r\n".
314
-				         "Content-type: ".$type."\r\n".
315
-				         "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
-				    $view->readfilePart($filename, $range['from'], $range['to']);
317
-				}
318
-				echo "\r\n--".self::getBoundary()."--\r\n";
319
-			    }
320
-			} catch (\OCP\Files\UnseekableException $ex) {
321
-			    // file is unseekable
322
-			    header_remove('Accept-Ranges');
323
-			    header_remove('Content-Range');
324
-			    header("HTTP/1.1 200 OK");
325
-			    self::sendHeaders($filename, $name, array());
326
-			    $view->readfile($filename);
327
-			}
328
-		}
329
-		else {
330
-		    $view->readfile($filename);
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * Returns the total (recursive) number of files and folders in the given
336
-	 * FileInfos.
337
-	 *
338
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
-	 * @return int the total number of files and folders
340
-	 */
341
-	private static function getNumberOfFiles($fileInfos) {
342
-		$numberOfFiles = 0;
343
-
344
-		$view = new View();
345
-
346
-		while ($fileInfo = array_pop($fileInfos)) {
347
-			$numberOfFiles++;
348
-
349
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
-			}
352
-		}
353
-
354
-		return $numberOfFiles;
355
-	}
356
-
357
-	/**
358
-	 * @param View $view
359
-	 * @param string $dir
360
-	 * @param string[]|string $files
361
-	 */
362
-	public static function lockFiles($view, $dir, $files) {
363
-		if (!is_array($files)) {
364
-			$file = $dir . '/' . $files;
365
-			$files = [$file];
366
-		}
367
-		foreach ($files as $file) {
368
-			$file = $dir . '/' . $file;
369
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
-			if ($view->is_dir($file)) {
371
-				$contents = $view->getDirectoryContent($file);
372
-				$contents = array_map(function($fileInfo) use ($file) {
373
-					/** @var \OCP\Files\FileInfo $fileInfo */
374
-					return $file . '/' . $fileInfo->getName();
375
-				}, $contents);
376
-				self::lockFiles($view, $dir, $contents);
377
-			}
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * set the maximum upload size limit for apache hosts using .htaccess
383
-	 *
384
-	 * @param int $size file size in bytes
385
-	 * @param array $files override '.htaccess' and '.user.ini' locations
386
-	 * @return bool|int false on failure, size on success
387
-	 */
388
-	public static function setUploadLimit($size, $files = []) {
389
-		//don't allow user to break his config
390
-		$size = (int)$size;
391
-		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
-			return false;
393
-		}
394
-		$size = OC_Helper::phpFileSize($size);
395
-
396
-		$phpValueKeys = array(
397
-			'upload_max_filesize',
398
-			'post_max_size'
399
-		);
400
-
401
-		// default locations if not overridden by $files
402
-		$files = array_merge([
403
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
-		], $files);
406
-
407
-		$updateFiles = [
408
-			$files['.htaccess'] => [
409
-				'pattern' => '/php_value %1$s (\S)*/',
410
-				'setting' => 'php_value %1$s %2$s'
411
-			],
412
-			$files['.user.ini'] => [
413
-				'pattern' => '/%1$s=(\S)*/',
414
-				'setting' => '%1$s=%2$s'
415
-			]
416
-		];
417
-
418
-		$success = true;
419
-
420
-		foreach ($updateFiles as $filename => $patternMap) {
421
-			// suppress warnings from fopen()
422
-			$handle = @fopen($filename, 'r+');
423
-			if (!$handle) {
424
-				\OCP\Util::writeLog('files',
425
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
-					ILogger::WARN);
427
-				$success = false;
428
-				continue; // try to update as many files as possible
429
-			}
430
-
431
-			$content = '';
432
-			while (!feof($handle)) {
433
-				$content .= fread($handle, 1000);
434
-			}
435
-
436
-			foreach ($phpValueKeys as $key) {
437
-				$pattern = vsprintf($patternMap['pattern'], [$key]);
438
-				$setting = vsprintf($patternMap['setting'], [$key, $size]);
439
-				$hasReplaced = 0;
440
-				$newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
-				if ($newContent !== null) {
442
-					$content = $newContent;
443
-				}
444
-				if ($hasReplaced === 0) {
445
-					$content .= "\n" . $setting;
446
-				}
447
-			}
448
-
449
-			// write file back
450
-			ftruncate($handle, 0);
451
-			rewind($handle);
452
-			fwrite($handle, $content);
453
-
454
-			fclose($handle);
455
-		}
456
-
457
-		if ($success) {
458
-			return OC_Helper::computerFileSize($size);
459
-		}
460
-		return false;
461
-	}
462
-
463
-	/**
464
-	 * @param string $dir
465
-	 * @param $files
466
-	 * @param integer $getType
467
-	 * @param View $view
468
-	 * @param string $filename
469
-	 */
470
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
-		if ($getType === self::FILE) {
472
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
-		}
474
-		if ($getType === self::ZIP_FILES) {
475
-			foreach ($files as $file) {
476
-				$file = $dir . '/' . $file;
477
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
-			}
479
-		}
480
-		if ($getType === self::ZIP_DIR) {
481
-			$file = $dir . '/' . $files;
482
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
-		}
484
-	}
286
+        if (\OC\Files\Filesystem::isReadable($filename)) {
287
+            self::sendHeaders($filename, $name, $rangeArray);
288
+        } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
+            header("HTTP/1.1 404 Not Found");
290
+            $tmpl = new OC_Template('', '404', 'guest');
291
+            $tmpl->printPage();
292
+            exit();
293
+        } else {
294
+            header("HTTP/1.1 403 Forbidden");
295
+            die('403 Forbidden');
296
+        }
297
+        if (isset($params['head']) && $params['head']) {
298
+            return;
299
+        }
300
+        if (!empty($rangeArray)) {
301
+            try {
302
+                if (count($rangeArray) == 1) {
303
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
+                }
305
+                else {
306
+                // check if file is seekable (if not throw UnseekableException)
307
+                // we have to check it before body contents
308
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
+
310
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
+
312
+                foreach ($rangeArray as $range) {
313
+                    echo "\r\n--".self::getBoundary()."\r\n".
314
+                            "Content-type: ".$type."\r\n".
315
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
+                    $view->readfilePart($filename, $range['from'], $range['to']);
317
+                }
318
+                echo "\r\n--".self::getBoundary()."--\r\n";
319
+                }
320
+            } catch (\OCP\Files\UnseekableException $ex) {
321
+                // file is unseekable
322
+                header_remove('Accept-Ranges');
323
+                header_remove('Content-Range');
324
+                header("HTTP/1.1 200 OK");
325
+                self::sendHeaders($filename, $name, array());
326
+                $view->readfile($filename);
327
+            }
328
+        }
329
+        else {
330
+            $view->readfile($filename);
331
+        }
332
+    }
333
+
334
+    /**
335
+     * Returns the total (recursive) number of files and folders in the given
336
+     * FileInfos.
337
+     *
338
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
+     * @return int the total number of files and folders
340
+     */
341
+    private static function getNumberOfFiles($fileInfos) {
342
+        $numberOfFiles = 0;
343
+
344
+        $view = new View();
345
+
346
+        while ($fileInfo = array_pop($fileInfos)) {
347
+            $numberOfFiles++;
348
+
349
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
+            }
352
+        }
353
+
354
+        return $numberOfFiles;
355
+    }
356
+
357
+    /**
358
+     * @param View $view
359
+     * @param string $dir
360
+     * @param string[]|string $files
361
+     */
362
+    public static function lockFiles($view, $dir, $files) {
363
+        if (!is_array($files)) {
364
+            $file = $dir . '/' . $files;
365
+            $files = [$file];
366
+        }
367
+        foreach ($files as $file) {
368
+            $file = $dir . '/' . $file;
369
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
+            if ($view->is_dir($file)) {
371
+                $contents = $view->getDirectoryContent($file);
372
+                $contents = array_map(function($fileInfo) use ($file) {
373
+                    /** @var \OCP\Files\FileInfo $fileInfo */
374
+                    return $file . '/' . $fileInfo->getName();
375
+                }, $contents);
376
+                self::lockFiles($view, $dir, $contents);
377
+            }
378
+        }
379
+    }
380
+
381
+    /**
382
+     * set the maximum upload size limit for apache hosts using .htaccess
383
+     *
384
+     * @param int $size file size in bytes
385
+     * @param array $files override '.htaccess' and '.user.ini' locations
386
+     * @return bool|int false on failure, size on success
387
+     */
388
+    public static function setUploadLimit($size, $files = []) {
389
+        //don't allow user to break his config
390
+        $size = (int)$size;
391
+        if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
+            return false;
393
+        }
394
+        $size = OC_Helper::phpFileSize($size);
395
+
396
+        $phpValueKeys = array(
397
+            'upload_max_filesize',
398
+            'post_max_size'
399
+        );
400
+
401
+        // default locations if not overridden by $files
402
+        $files = array_merge([
403
+            '.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
+            '.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
+        ], $files);
406
+
407
+        $updateFiles = [
408
+            $files['.htaccess'] => [
409
+                'pattern' => '/php_value %1$s (\S)*/',
410
+                'setting' => 'php_value %1$s %2$s'
411
+            ],
412
+            $files['.user.ini'] => [
413
+                'pattern' => '/%1$s=(\S)*/',
414
+                'setting' => '%1$s=%2$s'
415
+            ]
416
+        ];
417
+
418
+        $success = true;
419
+
420
+        foreach ($updateFiles as $filename => $patternMap) {
421
+            // suppress warnings from fopen()
422
+            $handle = @fopen($filename, 'r+');
423
+            if (!$handle) {
424
+                \OCP\Util::writeLog('files',
425
+                    'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
+                    ILogger::WARN);
427
+                $success = false;
428
+                continue; // try to update as many files as possible
429
+            }
430
+
431
+            $content = '';
432
+            while (!feof($handle)) {
433
+                $content .= fread($handle, 1000);
434
+            }
435
+
436
+            foreach ($phpValueKeys as $key) {
437
+                $pattern = vsprintf($patternMap['pattern'], [$key]);
438
+                $setting = vsprintf($patternMap['setting'], [$key, $size]);
439
+                $hasReplaced = 0;
440
+                $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
+                if ($newContent !== null) {
442
+                    $content = $newContent;
443
+                }
444
+                if ($hasReplaced === 0) {
445
+                    $content .= "\n" . $setting;
446
+                }
447
+            }
448
+
449
+            // write file back
450
+            ftruncate($handle, 0);
451
+            rewind($handle);
452
+            fwrite($handle, $content);
453
+
454
+            fclose($handle);
455
+        }
456
+
457
+        if ($success) {
458
+            return OC_Helper::computerFileSize($size);
459
+        }
460
+        return false;
461
+    }
462
+
463
+    /**
464
+     * @param string $dir
465
+     * @param $files
466
+     * @param integer $getType
467
+     * @param View $view
468
+     * @param string $filename
469
+     */
470
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
+        if ($getType === self::FILE) {
472
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
+        }
474
+        if ($getType === self::ZIP_FILES) {
475
+            foreach ($files as $file) {
476
+                $file = $dir . '/' . $file;
477
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
+            }
479
+        }
480
+        if ($getType === self::ZIP_DIR) {
481
+            $file = $dir . '/' . $files;
482
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
+        }
484
+    }
485 485
 
486 486
 }
Please login to merge, or discard this patch.
lib/private/legacy/template.php 2 patches
Indentation   +324 added lines, -324 removed lines patch added patch discarded remove patch
@@ -46,328 +46,328 @@
 block discarded – undo
46 46
  */
47 47
 class OC_Template extends \OC\Template\Base {
48 48
 
49
-	/** @var string */
50
-	private $renderAs; // Create a full page?
51
-
52
-	/** @var string */
53
-	private $path; // The path to the template
54
-
55
-	/** @var array */
56
-	private $headers = array(); //custom headers
57
-
58
-	/** @var string */
59
-	protected $app; // app id
60
-
61
-	protected static $initTemplateEngineFirstRun = true;
62
-
63
-	/**
64
-	 * Constructor
65
-	 *
66
-	 * @param string $app app providing the template
67
-	 * @param string $name of the template file (without suffix)
68
-	 * @param string $renderAs If $renderAs is set, OC_Template will try to
69
-	 *                         produce a full page in the according layout. For
70
-	 *                         now, $renderAs can be set to "guest", "user" or
71
-	 *                         "admin".
72
-	 * @param bool $registerCall = true
73
-	 */
74
-	public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
75
-		// Read the selected theme from the config file
76
-		self::initTemplateEngine($renderAs);
77
-
78
-		$theme = OC_Util::getTheme();
79
-
80
-		$requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
81
-
82
-		$parts = explode('/', $app); // fix translation when app is something like core/lostpassword
83
-		$l10n = \OC::$server->getL10N($parts[0]);
84
-		/** @var \OCP\Defaults $themeDefaults */
85
-		$themeDefaults = \OC::$server->query(\OCP\Defaults::class);
86
-
87
-		list($path, $template) = $this->findTemplate($theme, $app, $name);
88
-
89
-		// Set the private data
90
-		$this->renderAs = $renderAs;
91
-		$this->path = $path;
92
-		$this->app = $app;
93
-
94
-		parent::__construct($template, $requestToken, $l10n, $themeDefaults);
95
-	}
96
-
97
-	/**
98
-	 * @param string $renderAs
99
-	 */
100
-	public static function initTemplateEngine($renderAs) {
101
-		if (self::$initTemplateEngineFirstRun){
102
-
103
-			//apps that started before the template initialization can load their own scripts/styles
104
-			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
105
-			//meaning the last script/style in this list will be loaded first
106
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
107
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
108
-					OC_Util::addScript ( 'backgroundjobs', null, true );
109
-				}
110
-			}
111
-
112
-			OC_Util::addStyle('css-variables', null, true);
113
-			OC_Util::addStyle('server', null, true);
114
-			OC_Util::addStyle('jquery-ui-fixes',null,true);
115
-			OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
116
-			OC_Util::addVendorStyle('select2/select2', null, true);
117
-			OC_Util::addStyle('jquery.ocdialog');
118
-			OC_Util::addTranslations("core", null, true);
119
-			OC_Util::addStyle('search', 'results');
120
-			OC_Util::addScript('search', 'search', true);
121
-			OC_Util::addScript('search', 'searchprovider');
122
-			OC_Util::addScript('merged-template-prepend', null, true);
123
-			OC_Util::addScript('jquery-ui-fixes');
124
-			OC_Util::addScript('files/fileinfo');
125
-			OC_Util::addScript('files/client');
126
-			OC_Util::addScript('contactsmenu');
127
-
128
-			if (\OC::$server->getConfig()->getSystemValue('debug')) {
129
-				// Add the stuff we need always
130
-				// following logic will import all vendor libraries that are
131
-				// specified in core/js/core.json
132
-				$fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
133
-				if($fileContent !== false) {
134
-					$coreDependencies = json_decode($fileContent, true);
135
-					foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
136
-						//remove trailing ".js" as addVendorScript will append it
137
-						OC_Util::addVendorScript(
138
-							substr($vendorLibrary, 0, -3),null,true);
139
-						}
140
- 				} else {
141
-					throw new \Exception('Cannot read core/js/core.json');
142
-				}
143
-			} else {
144
-				// Import all (combined) default vendor libraries
145
-				OC_Util::addVendorScript('core', null, true);
146
-			}
147
-
148
-			if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
149
-				// polyfill for btoa/atob for IE friends
150
-				OC_Util::addVendorScript('base64/base64');
151
-				// shim for the davclient.js library
152
-				\OCP\Util::addScript('files/iedavclient');
153
-			}
154
-
155
-			self::$initTemplateEngineFirstRun = false;
156
-		}
157
-
158
-	}
159
-
160
-
161
-	/**
162
-	 * find the template with the given name
163
-	 * @param string $name of the template file (without suffix)
164
-	 *
165
-	 * Will select the template file for the selected theme.
166
-	 * Checking all the possible locations.
167
-	 * @param string $theme
168
-	 * @param string $app
169
-	 * @return string[]
170
-	 */
171
-	protected function findTemplate($theme, $app, $name) {
172
-		// Check if it is a app template or not.
173
-		if( $app !== '' ) {
174
-			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
175
-		} else {
176
-			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
177
-		}
178
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
179
-		$template = $locator->find($name);
180
-		$path = $locator->getPath();
181
-		return array($path, $template);
182
-	}
183
-
184
-	/**
185
-	 * Add a custom element to the header
186
-	 * @param string $tag tag name of the element
187
-	 * @param array $attributes array of attributes for the element
188
-	 * @param string $text the text content for the element. If $text is null then the
189
-	 * element will be written as empty element. So use "" to get a closing tag.
190
-	 */
191
-	public function addHeader($tag, $attributes, $text=null) {
192
-		$this->headers[]= array(
193
-			'tag' => $tag,
194
-			'attributes' => $attributes,
195
-			'text' => $text
196
-		);
197
-	}
198
-
199
-	/**
200
-	 * Process the template
201
-	 * @return boolean|string
202
-	 *
203
-	 * This function process the template. If $this->renderAs is set, it
204
-	 * will produce a full page.
205
-	 */
206
-	public function fetchPage($additionalParams = null) {
207
-		$data = parent::fetchPage($additionalParams);
208
-
209
-		if( $this->renderAs ) {
210
-			$page = new TemplateLayout($this->renderAs, $this->app);
211
-
212
-			if(is_array($additionalParams)) {
213
-				foreach ($additionalParams as $key => $value) {
214
-					$page->assign($key, $value);
215
-				}
216
-			}
217
-
218
-			// Add custom headers
219
-			$headers = '';
220
-			foreach(OC_Util::$headers as $header) {
221
-				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
222
-				if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
223
-					$headers .= ' defer';
224
-				}
225
-				foreach($header['attributes'] as $name=>$value) {
226
-					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
227
-				}
228
-				if ($header['text'] !== null) {
229
-					$headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
230
-				} else {
231
-					$headers .= '/>';
232
-				}
233
-			}
234
-
235
-			$page->assign('headers', $headers);
236
-
237
-			$page->assign('content', $data);
238
-			return $page->fetchPage($additionalParams);
239
-		}
240
-
241
-		return $data;
242
-	}
243
-
244
-	/**
245
-	 * Include template
246
-	 *
247
-	 * @param string $file
248
-	 * @param array|null $additionalParams
249
-	 * @return string returns content of included template
250
-	 *
251
-	 * Includes another template. use <?php echo $this->inc('template'); ?> to
252
-	 * do this.
253
-	 */
254
-	public function inc( $file, $additionalParams = null ) {
255
-		return $this->load($this->path.$file.'.php', $additionalParams);
256
-	}
257
-
258
-	/**
259
-	 * Shortcut to print a simple page for users
260
-	 * @param string $application The application we render the template for
261
-	 * @param string $name Name of the template
262
-	 * @param array $parameters Parameters for the template
263
-	 * @return boolean|null
264
-	 */
265
-	public static function printUserPage( $application, $name, $parameters = array() ) {
266
-		$content = new OC_Template( $application, $name, "user" );
267
-		foreach( $parameters as $key => $value ) {
268
-			$content->assign( $key, $value );
269
-		}
270
-		print $content->printPage();
271
-	}
272
-
273
-	/**
274
-	 * Shortcut to print a simple page for admins
275
-	 * @param string $application The application we render the template for
276
-	 * @param string $name Name of the template
277
-	 * @param array $parameters Parameters for the template
278
-	 * @return bool
279
-	 */
280
-	public static function printAdminPage( $application, $name, $parameters = array() ) {
281
-		$content = new OC_Template( $application, $name, "admin" );
282
-		foreach( $parameters as $key => $value ) {
283
-			$content->assign( $key, $value );
284
-		}
285
-		return $content->printPage();
286
-	}
287
-
288
-	/**
289
-	 * Shortcut to print a simple page for guests
290
-	 * @param string $application The application we render the template for
291
-	 * @param string $name Name of the template
292
-	 * @param array|string $parameters Parameters for the template
293
-	 * @return bool
294
-	 */
295
-	public static function printGuestPage( $application, $name, $parameters = array() ) {
296
-		$content = new OC_Template( $application, $name, "guest" );
297
-		foreach( $parameters as $key => $value ) {
298
-			$content->assign( $key, $value );
299
-		}
300
-		return $content->printPage();
301
-	}
302
-
303
-	/**
304
-	 * Print a fatal error page and terminates the script
305
-	 * @param string $error_msg The error message to show
306
-	 * @param string $hint An optional hint message - needs to be properly escape
307
-	 * @param int $statusCode
308
-	 * @suppress PhanAccessMethodInternal
309
-	 */
310
-	public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
311
-		if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
312
-			\OC_App::loadApp('theming');
313
-		}
314
-
315
-
316
-		if ($error_msg === $hint) {
317
-			// If the hint is the same as the message there is no need to display it twice.
318
-			$hint = '';
319
-		}
320
-
321
-		http_response_code($statusCode);
322
-		try {
323
-			$content = new \OC_Template( '', 'error', 'error', false );
324
-			$errors = array(array('error' => $error_msg, 'hint' => $hint));
325
-			$content->assign( 'errors', $errors );
326
-			$content->printPage();
327
-		} catch (\Exception $e) {
328
-			$logger = \OC::$server->getLogger();
329
-			$logger->error("$error_msg $hint", ['app' => 'core']);
330
-			$logger->logException($e, ['app' => 'core']);
331
-
332
-			header('Content-Type: text/plain; charset=utf-8');
333
-			print("$error_msg $hint");
334
-		}
335
-		die();
336
-	}
337
-
338
-	/**
339
-	 * print error page using Exception details
340
-	 * @param Exception|Throwable $exception
341
-	 * @param int $statusCode
342
-	 * @return bool|string
343
-	 * @suppress PhanAccessMethodInternal
344
-	 */
345
-	public static function printExceptionErrorPage($exception, $statusCode = 503) {
346
-		http_response_code($statusCode);
347
-		try {
348
-			$request = \OC::$server->getRequest();
349
-			$content = new \OC_Template('', 'exception', 'error', false);
350
-			$content->assign('errorClass', get_class($exception));
351
-			$content->assign('errorMsg', $exception->getMessage());
352
-			$content->assign('errorCode', $exception->getCode());
353
-			$content->assign('file', $exception->getFile());
354
-			$content->assign('line', $exception->getLine());
355
-			$content->assign('trace', $exception->getTraceAsString());
356
-			$content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
357
-			$content->assign('remoteAddr', $request->getRemoteAddress());
358
-			$content->assign('requestID', $request->getId());
359
-			$content->printPage();
360
-		} catch (\Exception $e) {
361
-			$logger = \OC::$server->getLogger();
362
-			$logger->logException($exception, ['app' => 'core']);
363
-			$logger->logException($e, ['app' => 'core']);
364
-
365
-			header('Content-Type: text/plain; charset=utf-8');
366
-			print("Internal Server Error\n\n");
367
-			print("The server encountered an internal error and was unable to complete your request.\n");
368
-			print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
369
-			print("More details can be found in the server log.\n");
370
-		}
371
-		die();
372
-	}
49
+    /** @var string */
50
+    private $renderAs; // Create a full page?
51
+
52
+    /** @var string */
53
+    private $path; // The path to the template
54
+
55
+    /** @var array */
56
+    private $headers = array(); //custom headers
57
+
58
+    /** @var string */
59
+    protected $app; // app id
60
+
61
+    protected static $initTemplateEngineFirstRun = true;
62
+
63
+    /**
64
+     * Constructor
65
+     *
66
+     * @param string $app app providing the template
67
+     * @param string $name of the template file (without suffix)
68
+     * @param string $renderAs If $renderAs is set, OC_Template will try to
69
+     *                         produce a full page in the according layout. For
70
+     *                         now, $renderAs can be set to "guest", "user" or
71
+     *                         "admin".
72
+     * @param bool $registerCall = true
73
+     */
74
+    public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
75
+        // Read the selected theme from the config file
76
+        self::initTemplateEngine($renderAs);
77
+
78
+        $theme = OC_Util::getTheme();
79
+
80
+        $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
81
+
82
+        $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
83
+        $l10n = \OC::$server->getL10N($parts[0]);
84
+        /** @var \OCP\Defaults $themeDefaults */
85
+        $themeDefaults = \OC::$server->query(\OCP\Defaults::class);
86
+
87
+        list($path, $template) = $this->findTemplate($theme, $app, $name);
88
+
89
+        // Set the private data
90
+        $this->renderAs = $renderAs;
91
+        $this->path = $path;
92
+        $this->app = $app;
93
+
94
+        parent::__construct($template, $requestToken, $l10n, $themeDefaults);
95
+    }
96
+
97
+    /**
98
+     * @param string $renderAs
99
+     */
100
+    public static function initTemplateEngine($renderAs) {
101
+        if (self::$initTemplateEngineFirstRun){
102
+
103
+            //apps that started before the template initialization can load their own scripts/styles
104
+            //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
105
+            //meaning the last script/style in this list will be loaded first
106
+            if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
107
+                if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
108
+                    OC_Util::addScript ( 'backgroundjobs', null, true );
109
+                }
110
+            }
111
+
112
+            OC_Util::addStyle('css-variables', null, true);
113
+            OC_Util::addStyle('server', null, true);
114
+            OC_Util::addStyle('jquery-ui-fixes',null,true);
115
+            OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
116
+            OC_Util::addVendorStyle('select2/select2', null, true);
117
+            OC_Util::addStyle('jquery.ocdialog');
118
+            OC_Util::addTranslations("core", null, true);
119
+            OC_Util::addStyle('search', 'results');
120
+            OC_Util::addScript('search', 'search', true);
121
+            OC_Util::addScript('search', 'searchprovider');
122
+            OC_Util::addScript('merged-template-prepend', null, true);
123
+            OC_Util::addScript('jquery-ui-fixes');
124
+            OC_Util::addScript('files/fileinfo');
125
+            OC_Util::addScript('files/client');
126
+            OC_Util::addScript('contactsmenu');
127
+
128
+            if (\OC::$server->getConfig()->getSystemValue('debug')) {
129
+                // Add the stuff we need always
130
+                // following logic will import all vendor libraries that are
131
+                // specified in core/js/core.json
132
+                $fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
133
+                if($fileContent !== false) {
134
+                    $coreDependencies = json_decode($fileContent, true);
135
+                    foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
136
+                        //remove trailing ".js" as addVendorScript will append it
137
+                        OC_Util::addVendorScript(
138
+                            substr($vendorLibrary, 0, -3),null,true);
139
+                        }
140
+                    } else {
141
+                    throw new \Exception('Cannot read core/js/core.json');
142
+                }
143
+            } else {
144
+                // Import all (combined) default vendor libraries
145
+                OC_Util::addVendorScript('core', null, true);
146
+            }
147
+
148
+            if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
149
+                // polyfill for btoa/atob for IE friends
150
+                OC_Util::addVendorScript('base64/base64');
151
+                // shim for the davclient.js library
152
+                \OCP\Util::addScript('files/iedavclient');
153
+            }
154
+
155
+            self::$initTemplateEngineFirstRun = false;
156
+        }
157
+
158
+    }
159
+
160
+
161
+    /**
162
+     * find the template with the given name
163
+     * @param string $name of the template file (without suffix)
164
+     *
165
+     * Will select the template file for the selected theme.
166
+     * Checking all the possible locations.
167
+     * @param string $theme
168
+     * @param string $app
169
+     * @return string[]
170
+     */
171
+    protected function findTemplate($theme, $app, $name) {
172
+        // Check if it is a app template or not.
173
+        if( $app !== '' ) {
174
+            $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
175
+        } else {
176
+            $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
177
+        }
178
+        $locator = new \OC\Template\TemplateFileLocator( $dirs );
179
+        $template = $locator->find($name);
180
+        $path = $locator->getPath();
181
+        return array($path, $template);
182
+    }
183
+
184
+    /**
185
+     * Add a custom element to the header
186
+     * @param string $tag tag name of the element
187
+     * @param array $attributes array of attributes for the element
188
+     * @param string $text the text content for the element. If $text is null then the
189
+     * element will be written as empty element. So use "" to get a closing tag.
190
+     */
191
+    public function addHeader($tag, $attributes, $text=null) {
192
+        $this->headers[]= array(
193
+            'tag' => $tag,
194
+            'attributes' => $attributes,
195
+            'text' => $text
196
+        );
197
+    }
198
+
199
+    /**
200
+     * Process the template
201
+     * @return boolean|string
202
+     *
203
+     * This function process the template. If $this->renderAs is set, it
204
+     * will produce a full page.
205
+     */
206
+    public function fetchPage($additionalParams = null) {
207
+        $data = parent::fetchPage($additionalParams);
208
+
209
+        if( $this->renderAs ) {
210
+            $page = new TemplateLayout($this->renderAs, $this->app);
211
+
212
+            if(is_array($additionalParams)) {
213
+                foreach ($additionalParams as $key => $value) {
214
+                    $page->assign($key, $value);
215
+                }
216
+            }
217
+
218
+            // Add custom headers
219
+            $headers = '';
220
+            foreach(OC_Util::$headers as $header) {
221
+                $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
222
+                if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
223
+                    $headers .= ' defer';
224
+                }
225
+                foreach($header['attributes'] as $name=>$value) {
226
+                    $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
227
+                }
228
+                if ($header['text'] !== null) {
229
+                    $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
230
+                } else {
231
+                    $headers .= '/>';
232
+                }
233
+            }
234
+
235
+            $page->assign('headers', $headers);
236
+
237
+            $page->assign('content', $data);
238
+            return $page->fetchPage($additionalParams);
239
+        }
240
+
241
+        return $data;
242
+    }
243
+
244
+    /**
245
+     * Include template
246
+     *
247
+     * @param string $file
248
+     * @param array|null $additionalParams
249
+     * @return string returns content of included template
250
+     *
251
+     * Includes another template. use <?php echo $this->inc('template'); ?> to
252
+     * do this.
253
+     */
254
+    public function inc( $file, $additionalParams = null ) {
255
+        return $this->load($this->path.$file.'.php', $additionalParams);
256
+    }
257
+
258
+    /**
259
+     * Shortcut to print a simple page for users
260
+     * @param string $application The application we render the template for
261
+     * @param string $name Name of the template
262
+     * @param array $parameters Parameters for the template
263
+     * @return boolean|null
264
+     */
265
+    public static function printUserPage( $application, $name, $parameters = array() ) {
266
+        $content = new OC_Template( $application, $name, "user" );
267
+        foreach( $parameters as $key => $value ) {
268
+            $content->assign( $key, $value );
269
+        }
270
+        print $content->printPage();
271
+    }
272
+
273
+    /**
274
+     * Shortcut to print a simple page for admins
275
+     * @param string $application The application we render the template for
276
+     * @param string $name Name of the template
277
+     * @param array $parameters Parameters for the template
278
+     * @return bool
279
+     */
280
+    public static function printAdminPage( $application, $name, $parameters = array() ) {
281
+        $content = new OC_Template( $application, $name, "admin" );
282
+        foreach( $parameters as $key => $value ) {
283
+            $content->assign( $key, $value );
284
+        }
285
+        return $content->printPage();
286
+    }
287
+
288
+    /**
289
+     * Shortcut to print a simple page for guests
290
+     * @param string $application The application we render the template for
291
+     * @param string $name Name of the template
292
+     * @param array|string $parameters Parameters for the template
293
+     * @return bool
294
+     */
295
+    public static function printGuestPage( $application, $name, $parameters = array() ) {
296
+        $content = new OC_Template( $application, $name, "guest" );
297
+        foreach( $parameters as $key => $value ) {
298
+            $content->assign( $key, $value );
299
+        }
300
+        return $content->printPage();
301
+    }
302
+
303
+    /**
304
+     * Print a fatal error page and terminates the script
305
+     * @param string $error_msg The error message to show
306
+     * @param string $hint An optional hint message - needs to be properly escape
307
+     * @param int $statusCode
308
+     * @suppress PhanAccessMethodInternal
309
+     */
310
+    public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
311
+        if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
312
+            \OC_App::loadApp('theming');
313
+        }
314
+
315
+
316
+        if ($error_msg === $hint) {
317
+            // If the hint is the same as the message there is no need to display it twice.
318
+            $hint = '';
319
+        }
320
+
321
+        http_response_code($statusCode);
322
+        try {
323
+            $content = new \OC_Template( '', 'error', 'error', false );
324
+            $errors = array(array('error' => $error_msg, 'hint' => $hint));
325
+            $content->assign( 'errors', $errors );
326
+            $content->printPage();
327
+        } catch (\Exception $e) {
328
+            $logger = \OC::$server->getLogger();
329
+            $logger->error("$error_msg $hint", ['app' => 'core']);
330
+            $logger->logException($e, ['app' => 'core']);
331
+
332
+            header('Content-Type: text/plain; charset=utf-8');
333
+            print("$error_msg $hint");
334
+        }
335
+        die();
336
+    }
337
+
338
+    /**
339
+     * print error page using Exception details
340
+     * @param Exception|Throwable $exception
341
+     * @param int $statusCode
342
+     * @return bool|string
343
+     * @suppress PhanAccessMethodInternal
344
+     */
345
+    public static function printExceptionErrorPage($exception, $statusCode = 503) {
346
+        http_response_code($statusCode);
347
+        try {
348
+            $request = \OC::$server->getRequest();
349
+            $content = new \OC_Template('', 'exception', 'error', false);
350
+            $content->assign('errorClass', get_class($exception));
351
+            $content->assign('errorMsg', $exception->getMessage());
352
+            $content->assign('errorCode', $exception->getCode());
353
+            $content->assign('file', $exception->getFile());
354
+            $content->assign('line', $exception->getLine());
355
+            $content->assign('trace', $exception->getTraceAsString());
356
+            $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
357
+            $content->assign('remoteAddr', $request->getRemoteAddress());
358
+            $content->assign('requestID', $request->getId());
359
+            $content->printPage();
360
+        } catch (\Exception $e) {
361
+            $logger = \OC::$server->getLogger();
362
+            $logger->logException($exception, ['app' => 'core']);
363
+            $logger->logException($e, ['app' => 'core']);
364
+
365
+            header('Content-Type: text/plain; charset=utf-8');
366
+            print("Internal Server Error\n\n");
367
+            print("The server encountered an internal error and was unable to complete your request.\n");
368
+            print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
369
+            print("More details can be found in the server log.\n");
370
+        }
371
+        die();
372
+    }
373 373
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 	 *                         "admin".
72 72
 	 * @param bool $registerCall = true
73 73
 	 */
74
-	public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
74
+	public function __construct($app, $name, $renderAs = "", $registerCall = true) {
75 75
 		// Read the selected theme from the config file
76 76
 		self::initTemplateEngine($renderAs);
77 77
 
@@ -98,21 +98,21 @@  discard block
 block discarded – undo
98 98
 	 * @param string $renderAs
99 99
 	 */
100 100
 	public static function initTemplateEngine($renderAs) {
101
-		if (self::$initTemplateEngineFirstRun){
101
+		if (self::$initTemplateEngineFirstRun) {
102 102
 
103 103
 			//apps that started before the template initialization can load their own scripts/styles
104 104
 			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
105 105
 			//meaning the last script/style in this list will be loaded first
106
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
107
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
108
-					OC_Util::addScript ( 'backgroundjobs', null, true );
106
+			if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
107
+				if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
108
+					OC_Util::addScript('backgroundjobs', null, true);
109 109
 				}
110 110
 			}
111 111
 
112 112
 			OC_Util::addStyle('css-variables', null, true);
113 113
 			OC_Util::addStyle('server', null, true);
114
-			OC_Util::addStyle('jquery-ui-fixes',null,true);
115
-			OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui',null,true);
114
+			OC_Util::addStyle('jquery-ui-fixes', null, true);
115
+			OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui', null, true);
116 116
 			OC_Util::addVendorStyle('select2/select2', null, true);
117 117
 			OC_Util::addStyle('jquery.ocdialog');
118 118
 			OC_Util::addTranslations("core", null, true);
@@ -129,13 +129,13 @@  discard block
 block discarded – undo
129 129
 				// Add the stuff we need always
130 130
 				// following logic will import all vendor libraries that are
131 131
 				// specified in core/js/core.json
132
-				$fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
133
-				if($fileContent !== false) {
132
+				$fileContent = file_get_contents(OC::$SERVERROOT.'/core/js/core.json');
133
+				if ($fileContent !== false) {
134 134
 					$coreDependencies = json_decode($fileContent, true);
135
-					foreach(array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
135
+					foreach (array_reverse($coreDependencies['vendor']) as $vendorLibrary) {
136 136
 						//remove trailing ".js" as addVendorScript will append it
137 137
 						OC_Util::addVendorScript(
138
-							substr($vendorLibrary, 0, -3),null,true);
138
+							substr($vendorLibrary, 0, -3), null, true);
139 139
 						}
140 140
  				} else {
141 141
 					throw new \Exception('Cannot read core/js/core.json');
@@ -170,12 +170,12 @@  discard block
 block discarded – undo
170 170
 	 */
171 171
 	protected function findTemplate($theme, $app, $name) {
172 172
 		// Check if it is a app template or not.
173
-		if( $app !== '' ) {
173
+		if ($app !== '') {
174 174
 			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
175 175
 		} else {
176 176
 			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
177 177
 		}
178
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
178
+		$locator = new \OC\Template\TemplateFileLocator($dirs);
179 179
 		$template = $locator->find($name);
180 180
 		$path = $locator->getPath();
181 181
 		return array($path, $template);
@@ -188,8 +188,8 @@  discard block
 block discarded – undo
188 188
 	 * @param string $text the text content for the element. If $text is null then the
189 189
 	 * element will be written as empty element. So use "" to get a closing tag.
190 190
 	 */
191
-	public function addHeader($tag, $attributes, $text=null) {
192
-		$this->headers[]= array(
191
+	public function addHeader($tag, $attributes, $text = null) {
192
+		$this->headers[] = array(
193 193
 			'tag' => $tag,
194 194
 			'attributes' => $attributes,
195 195
 			'text' => $text
@@ -206,10 +206,10 @@  discard block
 block discarded – undo
206 206
 	public function fetchPage($additionalParams = null) {
207 207
 		$data = parent::fetchPage($additionalParams);
208 208
 
209
-		if( $this->renderAs ) {
209
+		if ($this->renderAs) {
210 210
 			$page = new TemplateLayout($this->renderAs, $this->app);
211 211
 
212
-			if(is_array($additionalParams)) {
212
+			if (is_array($additionalParams)) {
213 213
 				foreach ($additionalParams as $key => $value) {
214 214
 					$page->assign($key, $value);
215 215
 				}
@@ -217,12 +217,12 @@  discard block
 block discarded – undo
217 217
 
218 218
 			// Add custom headers
219 219
 			$headers = '';
220
-			foreach(OC_Util::$headers as $header) {
220
+			foreach (OC_Util::$headers as $header) {
221 221
 				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
222
-				if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
222
+				if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
223 223
 					$headers .= ' defer';
224 224
 				}
225
-				foreach($header['attributes'] as $name=>$value) {
225
+				foreach ($header['attributes'] as $name=>$value) {
226 226
 					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
227 227
 				}
228 228
 				if ($header['text'] !== null) {
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 	 * Includes another template. use <?php echo $this->inc('template'); ?> to
252 252
 	 * do this.
253 253
 	 */
254
-	public function inc( $file, $additionalParams = null ) {
254
+	public function inc($file, $additionalParams = null) {
255 255
 		return $this->load($this->path.$file.'.php', $additionalParams);
256 256
 	}
257 257
 
@@ -262,10 +262,10 @@  discard block
 block discarded – undo
262 262
 	 * @param array $parameters Parameters for the template
263 263
 	 * @return boolean|null
264 264
 	 */
265
-	public static function printUserPage( $application, $name, $parameters = array() ) {
266
-		$content = new OC_Template( $application, $name, "user" );
267
-		foreach( $parameters as $key => $value ) {
268
-			$content->assign( $key, $value );
265
+	public static function printUserPage($application, $name, $parameters = array()) {
266
+		$content = new OC_Template($application, $name, "user");
267
+		foreach ($parameters as $key => $value) {
268
+			$content->assign($key, $value);
269 269
 		}
270 270
 		print $content->printPage();
271 271
 	}
@@ -277,10 +277,10 @@  discard block
 block discarded – undo
277 277
 	 * @param array $parameters Parameters for the template
278 278
 	 * @return bool
279 279
 	 */
280
-	public static function printAdminPage( $application, $name, $parameters = array() ) {
281
-		$content = new OC_Template( $application, $name, "admin" );
282
-		foreach( $parameters as $key => $value ) {
283
-			$content->assign( $key, $value );
280
+	public static function printAdminPage($application, $name, $parameters = array()) {
281
+		$content = new OC_Template($application, $name, "admin");
282
+		foreach ($parameters as $key => $value) {
283
+			$content->assign($key, $value);
284 284
 		}
285 285
 		return $content->printPage();
286 286
 	}
@@ -292,10 +292,10 @@  discard block
 block discarded – undo
292 292
 	 * @param array|string $parameters Parameters for the template
293 293
 	 * @return bool
294 294
 	 */
295
-	public static function printGuestPage( $application, $name, $parameters = array() ) {
296
-		$content = new OC_Template( $application, $name, "guest" );
297
-		foreach( $parameters as $key => $value ) {
298
-			$content->assign( $key, $value );
295
+	public static function printGuestPage($application, $name, $parameters = array()) {
296
+		$content = new OC_Template($application, $name, "guest");
297
+		foreach ($parameters as $key => $value) {
298
+			$content->assign($key, $value);
299 299
 		}
300 300
 		return $content->printPage();
301 301
 	}
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 	 * @param int $statusCode
308 308
 	 * @suppress PhanAccessMethodInternal
309 309
 	 */
310
-	public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
310
+	public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
311 311
 		if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
312 312
 			\OC_App::loadApp('theming');
313 313
 		}
@@ -320,9 +320,9 @@  discard block
 block discarded – undo
320 320
 
321 321
 		http_response_code($statusCode);
322 322
 		try {
323
-			$content = new \OC_Template( '', 'error', 'error', false );
323
+			$content = new \OC_Template('', 'error', 'error', false);
324 324
 			$errors = array(array('error' => $error_msg, 'hint' => $hint));
325
-			$content->assign( 'errors', $errors );
325
+			$content->assign('errors', $errors);
326 326
 			$content->printPage();
327 327
 		} catch (\Exception $e) {
328 328
 			$logger = \OC::$server->getLogger();
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +1004 added lines, -1004 removed lines patch added patch discarded remove patch
@@ -68,1010 +68,1010 @@
 block discarded – undo
68 68
  * OC_autoload!
69 69
  */
70 70
 class OC {
71
-	/**
72
-	 * Associative array for autoloading. classname => filename
73
-	 */
74
-	public static $CLASSPATH = array();
75
-	/**
76
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
-	 */
78
-	public static $SERVERROOT = '';
79
-	/**
80
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
-	 */
82
-	private static $SUBURI = '';
83
-	/**
84
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
85
-	 */
86
-	public static $WEBROOT = '';
87
-	/**
88
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
-	 * web path in 'url'
90
-	 */
91
-	public static $APPSROOTS = array();
92
-
93
-	/**
94
-	 * @var string
95
-	 */
96
-	public static $configDir;
97
-
98
-	/**
99
-	 * requested app
100
-	 */
101
-	public static $REQUESTEDAPP = '';
102
-
103
-	/**
104
-	 * check if Nextcloud runs in cli mode
105
-	 */
106
-	public static $CLI = false;
107
-
108
-	/**
109
-	 * @var \OC\Autoloader $loader
110
-	 */
111
-	public static $loader = null;
112
-
113
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
-	public static $composerAutoloader = null;
115
-
116
-	/**
117
-	 * @var \OC\Server
118
-	 */
119
-	public static $server = null;
120
-
121
-	/**
122
-	 * @var \OC\Config
123
-	 */
124
-	private static $config = null;
125
-
126
-	/**
127
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
128
-	 * the app path list is empty or contains an invalid path
129
-	 */
130
-	public static function initPaths() {
131
-		if(defined('PHPUNIT_CONFIG_DIR')) {
132
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
-			self::$configDir = rtrim($dir, '/') . '/';
137
-		} else {
138
-			self::$configDir = OC::$SERVERROOT . '/config/';
139
-		}
140
-		self::$config = new \OC\Config(self::$configDir);
141
-
142
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
-		/**
144
-		 * FIXME: The following lines are required because we can't yet instantiate
145
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
-		 */
147
-		$params = [
148
-			'server' => [
149
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
-			],
152
-		];
153
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
-		$scriptName = $fakeRequest->getScriptName();
155
-		if (substr($scriptName, -1) == '/') {
156
-			$scriptName .= 'index.php';
157
-			//make sure suburi follows the same rules as scriptName
158
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
159
-				if (substr(OC::$SUBURI, -1) != '/') {
160
-					OC::$SUBURI = OC::$SUBURI . '/';
161
-				}
162
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
163
-			}
164
-		}
165
-
166
-
167
-		if (OC::$CLI) {
168
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
-		} else {
170
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
-
173
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
175
-				}
176
-			} else {
177
-				// The scriptName is not ending with OC::$SUBURI
178
-				// This most likely means that we are calling from CLI.
179
-				// However some cron jobs still need to generate
180
-				// a web URL, so we use overwritewebroot as a fallback.
181
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
-			}
183
-
184
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
-			// slash which is required by URL generation.
186
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
-				header('Location: '.\OC::$WEBROOT.'/');
189
-				exit();
190
-			}
191
-		}
192
-
193
-		// search the apps folder
194
-		$config_paths = self::$config->getValue('apps_paths', array());
195
-		if (!empty($config_paths)) {
196
-			foreach ($config_paths as $paths) {
197
-				if (isset($paths['url']) && isset($paths['path'])) {
198
-					$paths['url'] = rtrim($paths['url'], '/');
199
-					$paths['path'] = rtrim($paths['path'], '/');
200
-					OC::$APPSROOTS[] = $paths;
201
-				}
202
-			}
203
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
-			OC::$APPSROOTS[] = array(
207
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
-				'url' => '/apps',
209
-				'writable' => true
210
-			);
211
-		}
212
-
213
-		if (empty(OC::$APPSROOTS)) {
214
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
-				. ' or the folder above. You can also configure the location in the config.php file.');
216
-		}
217
-		$paths = array();
218
-		foreach (OC::$APPSROOTS as $path) {
219
-			$paths[] = $path['path'];
220
-			if (!is_dir($path['path'])) {
221
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
223
-					. ' config.php file.', $path['path']));
224
-			}
225
-		}
226
-
227
-		// set the right include path
228
-		set_include_path(
229
-			implode(PATH_SEPARATOR, $paths)
230
-		);
231
-	}
232
-
233
-	public static function checkConfig() {
234
-		$l = \OC::$server->getL10N('lib');
235
-
236
-		// Create config if it does not already exist
237
-		$configFilePath = self::$configDir .'/config.php';
238
-		if(!file_exists($configFilePath)) {
239
-			@touch($configFilePath);
240
-		}
241
-
242
-		// Check if config is writable
243
-		$configFileWritable = is_writable($configFilePath);
244
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
246
-
247
-			$urlGenerator = \OC::$server->getURLGenerator();
248
-
249
-			if (self::$CLI) {
250
-				echo $l->t('Cannot write into "config" directory!')."\n";
251
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
-				echo "\n";
254
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
-				exit;
257
-			} else {
258
-				OC_Template::printErrorPage(
259
-					$l->t('Cannot write into "config" directory!'),
260
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
-					[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
262
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
264
-					\OC_Response::STATUS_SERVICE_UNAVAILABLE
265
-				);
266
-			}
267
-		}
268
-	}
269
-
270
-	public static function checkInstalled() {
271
-		if (defined('OC_CONSOLE')) {
272
-			return;
273
-		}
274
-		// Redirect to installer if not installed
275
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
276
-			if (OC::$CLI) {
277
-				throw new Exception('Not installed');
278
-			} else {
279
-				$url = OC::$WEBROOT . '/index.php';
280
-				header('Location: ' . $url);
281
-			}
282
-			exit();
283
-		}
284
-	}
285
-
286
-	public static function checkMaintenanceMode() {
287
-		// Allow ajax update script to execute without being stopped
288
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
289
-			// send http status 503
290
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
291
-			header('Status: 503 Service Temporarily Unavailable');
292
-			header('Retry-After: 120');
293
-
294
-			// render error page
295
-			$template = new OC_Template('', 'update.user', 'guest');
296
-			OC_Util::addScript('maintenance-check');
297
-			OC_Util::addStyle('core', 'guest');
298
-			$template->printPage();
299
-			die();
300
-		}
301
-	}
302
-
303
-	/**
304
-	 * Prints the upgrade page
305
-	 *
306
-	 * @param \OC\SystemConfig $systemConfig
307
-	 */
308
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
309
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
310
-		$tooBig = false;
311
-		if (!$disableWebUpdater) {
312
-			$apps = \OC::$server->getAppManager();
313
-			if ($apps->isInstalled('user_ldap')) {
314
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
315
-
316
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
317
-					->from('ldap_user_mapping')
318
-					->execute();
319
-				$row = $result->fetch();
320
-				$result->closeCursor();
321
-
322
-				$tooBig = ($row['user_count'] > 50);
323
-			}
324
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
325
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
-
327
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
-					->from('user_saml_users')
329
-					->execute();
330
-				$row = $result->fetch();
331
-				$result->closeCursor();
332
-
333
-				$tooBig = ($row['user_count'] > 50);
334
-			}
335
-			if (!$tooBig) {
336
-				// count users
337
-				$stats = \OC::$server->getUserManager()->countUsers();
338
-				$totalUsers = array_sum($stats);
339
-				$tooBig = ($totalUsers > 50);
340
-			}
341
-		}
342
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
343
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
344
-
345
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
346
-			// send http status 503
347
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
348
-			header('Status: 503 Service Temporarily Unavailable');
349
-			header('Retry-After: 120');
350
-
351
-			// render error page
352
-			$template = new OC_Template('', 'update.use-cli', 'guest');
353
-			$template->assign('productName', 'nextcloud'); // for now
354
-			$template->assign('version', OC_Util::getVersionString());
355
-			$template->assign('tooBig', $tooBig);
356
-
357
-			$template->printPage();
358
-			die();
359
-		}
360
-
361
-		// check whether this is a core update or apps update
362
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
363
-		$currentVersion = implode('.', \OCP\Util::getVersion());
364
-
365
-		// if not a core upgrade, then it's apps upgrade
366
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
367
-
368
-		$oldTheme = $systemConfig->getValue('theme');
369
-		$systemConfig->setValue('theme', '');
370
-		OC_Util::addScript('config'); // needed for web root
371
-		OC_Util::addScript('update');
372
-
373
-		/** @var \OC\App\AppManager $appManager */
374
-		$appManager = \OC::$server->getAppManager();
375
-
376
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
377
-		$tmpl->assign('version', OC_Util::getVersionString());
378
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
379
-
380
-		// get third party apps
381
-		$ocVersion = \OCP\Util::getVersion();
382
-		$ocVersion = implode('.', $ocVersion);
383
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
384
-		$incompatibleShippedApps = [];
385
-		foreach ($incompatibleApps as $appInfo) {
386
-			if ($appManager->isShipped($appInfo['id'])) {
387
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
388
-			}
389
-		}
390
-
391
-		if (!empty($incompatibleShippedApps)) {
392
-			$l = \OC::$server->getL10N('core');
393
-			$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)]);
394
-			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);
395
-		}
396
-
397
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
398
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
399
-		$tmpl->assign('productName', 'Nextcloud'); // for now
400
-		$tmpl->assign('oldTheme', $oldTheme);
401
-		$tmpl->printPage();
402
-	}
403
-
404
-	public static function initSession() {
405
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
406
-			ini_set('session.cookie_secure', true);
407
-		}
408
-
409
-		// prevents javascript from accessing php session cookies
410
-		ini_set('session.cookie_httponly', 'true');
411
-
412
-		// set the cookie path to the Nextcloud directory
413
-		$cookie_path = OC::$WEBROOT ? : '/';
414
-		ini_set('session.cookie_path', $cookie_path);
415
-
416
-		// Let the session name be changed in the initSession Hook
417
-		$sessionName = OC_Util::getInstanceId();
418
-
419
-		try {
420
-			// Allow session apps to create a custom session object
421
-			$useCustomSession = false;
422
-			$session = self::$server->getSession();
423
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
424
-			if (!$useCustomSession) {
425
-				// set the session name to the instance id - which is unique
426
-				$session = new \OC\Session\Internal($sessionName);
427
-			}
428
-
429
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
430
-			$session = $cryptoWrapper->wrapSession($session);
431
-			self::$server->setSession($session);
432
-
433
-			// if session can't be started break with http 500 error
434
-		} catch (Exception $e) {
435
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
436
-			//show the user a detailed error page
437
-			OC_Template::printExceptionErrorPage($e, \OC_Response::STATUS_INTERNAL_SERVER_ERROR);
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 = \OC::$server->getConfig()->getSystemValue('csrf.optout');
531
-
532
-		// Fallback, if csrf.optout is unset
533
-		if (!is_array($incompatibleUserAgents)) {
534
-			$incompatibleUserAgents = [
535
-				// OS X Finder
536
-				'/^WebDAVFS/',
537
-				// Windows webdav drive
538
-				'/^Microsoft-WebDAV-MiniRedir/',
539
-			];
540
-		}
541
-
542
-		if($request->isUserAgent($incompatibleUserAgents)) {
543
-			return;
544
-		}
545
-
546
-		if(count($_COOKIE) > 0) {
547
-			$requestUri = $request->getScriptName();
548
-			$processingScript = explode('/', $requestUri);
549
-			$processingScript = $processingScript[count($processingScript)-1];
550
-
551
-			// index.php routes are handled in the middleware
552
-			if($processingScript === 'index.php') {
553
-				return;
554
-			}
555
-
556
-			// All other endpoints require the lax and the strict cookie
557
-			if(!$request->passesStrictCookieCheck()) {
558
-				self::sendSameSiteCookies();
559
-				// Debug mode gets access to the resources without strict cookie
560
-				// due to the fact that the SabreDAV browser also lives there.
561
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
562
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
563
-					exit();
564
-				}
565
-			}
566
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
567
-			self::sendSameSiteCookies();
568
-		}
569
-	}
570
-
571
-	public static function init() {
572
-		// calculate the root directories
573
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
574
-
575
-		// register autoloader
576
-		$loaderStart = microtime(true);
577
-		require_once __DIR__ . '/autoloader.php';
578
-		self::$loader = new \OC\Autoloader([
579
-			OC::$SERVERROOT . '/lib/private/legacy',
580
-		]);
581
-		if (defined('PHPUNIT_RUN')) {
582
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
583
-		}
584
-		spl_autoload_register(array(self::$loader, 'load'));
585
-		$loaderEnd = microtime(true);
586
-
587
-		self::$CLI = (php_sapi_name() == 'cli');
588
-
589
-		// Add default composer PSR-4 autoloader
590
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
591
-
592
-		try {
593
-			self::initPaths();
594
-			// setup 3rdparty autoloader
595
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
596
-			if (!file_exists($vendorAutoLoad)) {
597
-				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".');
598
-			}
599
-			require_once $vendorAutoLoad;
600
-
601
-		} catch (\RuntimeException $e) {
602
-			if (!self::$CLI) {
603
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
604
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
605
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
606
-			}
607
-			// we can't use the template error page here, because this needs the
608
-			// DI container which isn't available yet
609
-			print($e->getMessage());
610
-			exit();
611
-		}
612
-
613
-		// setup the basic server
614
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
615
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
616
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
617
-
618
-		// Don't display errors and log them
619
-		error_reporting(E_ALL | E_STRICT);
620
-		@ini_set('display_errors', '0');
621
-		@ini_set('log_errors', '1');
622
-
623
-		if(!date_default_timezone_set('UTC')) {
624
-			throw new \RuntimeException('Could not set timezone to UTC');
625
-		}
626
-
627
-		//try to configure php to enable big file uploads.
628
-		//this doesn´t work always depending on the webserver and php configuration.
629
-		//Let´s try to overwrite some defaults anyway
630
-
631
-		//try to set the maximum execution time to 60min
632
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
633
-			@set_time_limit(3600);
634
-		}
635
-		@ini_set('max_execution_time', '3600');
636
-		@ini_set('max_input_time', '3600');
637
-
638
-		//try to set the maximum filesize to 10G
639
-		@ini_set('upload_max_filesize', '10G');
640
-		@ini_set('post_max_size', '10G');
641
-		@ini_set('file_uploads', '50');
642
-
643
-		self::setRequiredIniValues();
644
-		self::handleAuthHeaders();
645
-		self::registerAutoloaderCache();
646
-
647
-		// initialize intl fallback is necessary
648
-		\Patchwork\Utf8\Bootup::initIntl();
649
-		OC_Util::isSetLocaleWorking();
650
-
651
-		if (!defined('PHPUNIT_RUN')) {
652
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
653
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
654
-			OC\Log\ErrorHandler::register($debug);
655
-		}
656
-
657
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
658
-		OC_App::loadApps(array('session'));
659
-		if (!self::$CLI) {
660
-			self::initSession();
661
-		}
662
-		\OC::$server->getEventLogger()->end('init_session');
663
-		self::checkConfig();
664
-		self::checkInstalled();
665
-
666
-		OC_Response::addSecurityHeaders();
667
-
668
-		self::performSameSiteCookieProtection();
669
-
670
-		if (!defined('OC_CONSOLE')) {
671
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
672
-			if (count($errors) > 0) {
673
-				if (self::$CLI) {
674
-					// Convert l10n string into regular string for usage in database
675
-					$staticErrors = [];
676
-					foreach ($errors as $error) {
677
-						echo $error['error'] . "\n";
678
-						echo $error['hint'] . "\n\n";
679
-						$staticErrors[] = [
680
-							'error' => (string)$error['error'],
681
-							'hint' => (string)$error['hint'],
682
-						];
683
-					}
684
-
685
-					try {
686
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
687
-					} catch (\Exception $e) {
688
-						echo('Writing to database failed');
689
-					}
690
-					exit(1);
691
-				} else {
692
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
693
-					OC_Util::addStyle('guest');
694
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
695
-					exit;
696
-				}
697
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
698
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
699
-			}
700
-		}
701
-		//try to set the session lifetime
702
-		$sessionLifeTime = self::getSessionLifeTime();
703
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
704
-
705
-		$systemConfig = \OC::$server->getSystemConfig();
706
-
707
-		// User and Groups
708
-		if (!$systemConfig->getValue("installed", false)) {
709
-			self::$server->getSession()->set('user_id', '');
710
-		}
711
-
712
-		OC_User::useBackend(new \OC\User\Database());
713
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
714
-
715
-		// Subscribe to the hook
716
-		\OCP\Util::connectHook(
717
-			'\OCA\Files_Sharing\API\Server2Server',
718
-			'preLoginNameUsedAsUserName',
719
-			'\OC\User\Database',
720
-			'preLoginNameUsedAsUserName'
721
-		);
722
-
723
-		//setup extra user backends
724
-		if (!\OCP\Util::needUpgrade()) {
725
-			OC_User::setupBackends();
726
-		} else {
727
-			// Run upgrades in incognito mode
728
-			OC_User::setIncognitoMode(true);
729
-		}
730
-
731
-		self::registerCleanupHooks();
732
-		self::registerFilesystemHooks();
733
-		self::registerShareHooks();
734
-		self::registerEncryptionWrapper();
735
-		self::registerEncryptionHooks();
736
-		self::registerAccountHooks();
737
-
738
-		// Make sure that the application class is not loaded before the database is setup
739
-		if ($systemConfig->getValue("installed", false)) {
740
-			$settings = new \OC\Settings\Application();
741
-			$settings->register();
742
-		}
743
-
744
-		//make sure temporary files are cleaned up
745
-		$tmpManager = \OC::$server->getTempManager();
746
-		register_shutdown_function(array($tmpManager, 'clean'));
747
-		$lockProvider = \OC::$server->getLockingProvider();
748
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
749
-
750
-		// Check whether the sample configuration has been copied
751
-		if($systemConfig->getValue('copied_sample_config', false)) {
752
-			$l = \OC::$server->getL10N('lib');
753
-			OC_Template::printErrorPage(
754
-				$l->t('Sample configuration detected'),
755
-				$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'),
756
-				\OC_Response::STATUS_SERVICE_UNAVAILABLE
757
-			);
758
-			return;
759
-		}
760
-
761
-		$request = \OC::$server->getRequest();
762
-		$host = $request->getInsecureServerHost();
763
-		/**
764
-		 * if the host passed in headers isn't trusted
765
-		 * FIXME: Should not be in here at all :see_no_evil:
766
-		 */
767
-		if (!OC::$CLI
768
-			// overwritehost is always trusted, workaround to not have to make
769
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
770
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
771
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
772
-			&& self::$server->getConfig()->getSystemValue('installed', false)
773
-		) {
774
-			// Allow access to CSS resources
775
-			$isScssRequest = false;
776
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
777
-				$isScssRequest = true;
778
-			}
779
-
780
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
781
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
782
-				header('Status: 400 Bad Request');
783
-				header('Content-Type: application/json');
784
-				echo '{"error": "Trusted domain error.", "code": 15}';
785
-				exit();
786
-			}
787
-
788
-			if (!$isScssRequest) {
789
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
790
-				header('Status: 400 Bad Request');
791
-
792
-				\OC::$server->getLogger()->info(
793
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
794
-					[
795
-						'app' => 'core',
796
-						'remoteAddress' => $request->getRemoteAddress(),
797
-						'host' => $host,
798
-					]
799
-				);
800
-
801
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
802
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
803
-				$tmpl->printPage();
804
-
805
-				exit();
806
-			}
807
-		}
808
-		\OC::$server->getEventLogger()->end('boot');
809
-	}
810
-
811
-	/**
812
-	 * register hooks for the cleanup of cache and bruteforce protection
813
-	 */
814
-	public static function registerCleanupHooks() {
815
-		//don't try to do this before we are properly setup
816
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
817
-
818
-			// NOTE: This will be replaced to use OCP
819
-			$userSession = self::$server->getUserSession();
820
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
821
-				if (!defined('PHPUNIT_RUN')) {
822
-					// reset brute force delay for this IP address and username
823
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
824
-					$request = \OC::$server->getRequest();
825
-					$throttler = \OC::$server->getBruteForceThrottler();
826
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
827
-				}
828
-
829
-				try {
830
-					$cache = new \OC\Cache\File();
831
-					$cache->gc();
832
-				} catch (\OC\ServerNotAvailableException $e) {
833
-					// not a GC exception, pass it on
834
-					throw $e;
835
-				} catch (\OC\ForbiddenException $e) {
836
-					// filesystem blocked for this request, ignore
837
-				} catch (\Exception $e) {
838
-					// a GC exception should not prevent users from using OC,
839
-					// so log the exception
840
-					\OC::$server->getLogger()->logException($e, [
841
-						'message' => 'Exception when running cache gc.',
842
-						'level' => ILogger::WARN,
843
-						'app' => 'core',
844
-					]);
845
-				}
846
-			});
847
-		}
848
-	}
849
-
850
-	private static function registerEncryptionWrapper() {
851
-		$manager = self::$server->getEncryptionManager();
852
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
853
-	}
854
-
855
-	private static function registerEncryptionHooks() {
856
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
857
-		if ($enabled) {
858
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
859
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
860
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
861
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
862
-		}
863
-	}
864
-
865
-	private static function registerAccountHooks() {
866
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
867
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
868
-	}
869
-
870
-	/**
871
-	 * register hooks for the filesystem
872
-	 */
873
-	public static function registerFilesystemHooks() {
874
-		// Check for blacklisted files
875
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
876
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
877
-	}
878
-
879
-	/**
880
-	 * register hooks for sharing
881
-	 */
882
-	public static function registerShareHooks() {
883
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
884
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
885
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
886
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
887
-		}
888
-	}
889
-
890
-	protected static function registerAutoloaderCache() {
891
-		// The class loader takes an optional low-latency cache, which MUST be
892
-		// namespaced. The instanceid is used for namespacing, but might be
893
-		// unavailable at this point. Furthermore, it might not be possible to
894
-		// generate an instanceid via \OC_Util::getInstanceId() because the
895
-		// config file may not be writable. As such, we only register a class
896
-		// loader cache if instanceid is available without trying to create one.
897
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
898
-		if ($instanceId) {
899
-			try {
900
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
901
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
902
-			} catch (\Exception $ex) {
903
-			}
904
-
905
-			self::$composerAutoloader->setApcuPrefix($instanceId . '-mainComposer');
906
-		}
907
-	}
908
-
909
-	/**
910
-	 * Handle the request
911
-	 */
912
-	public static function handleRequest() {
913
-
914
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
915
-		$systemConfig = \OC::$server->getSystemConfig();
916
-		// load all the classpaths from the enabled apps so they are available
917
-		// in the routing files of each app
918
-		OC::loadAppClassPaths();
919
-
920
-		// Check if Nextcloud is installed or in maintenance (update) mode
921
-		if (!$systemConfig->getValue('installed', false)) {
922
-			\OC::$server->getSession()->clear();
923
-			$setupHelper = new OC\Setup(
924
-				$systemConfig,
925
-				\OC::$server->getIniWrapper(),
926
-				\OC::$server->getL10N('lib'),
927
-				\OC::$server->query(\OCP\Defaults::class),
928
-				\OC::$server->getLogger(),
929
-				\OC::$server->getSecureRandom(),
930
-				\OC::$server->query(\OC\Installer::class)
931
-			);
932
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
933
-			$controller->run($_POST);
934
-			exit();
935
-		}
936
-
937
-		$request = \OC::$server->getRequest();
938
-		$requestPath = $request->getRawPathInfo();
939
-		if ($requestPath === '/heartbeat') {
940
-			return;
941
-		}
942
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
943
-			self::checkMaintenanceMode();
944
-
945
-			if (\OCP\Util::needUpgrade()) {
946
-				if (function_exists('opcache_reset')) {
947
-					opcache_reset();
948
-				}
949
-				if (!$systemConfig->getValue('maintenance', false)) {
950
-					self::printUpgradePage($systemConfig);
951
-					exit();
952
-				}
953
-			}
954
-		}
955
-
956
-		// emergency app disabling
957
-		if ($requestPath === '/disableapp'
958
-			&& $request->getMethod() === 'POST'
959
-			&& ((array)$request->getParam('appid')) !== ''
960
-		) {
961
-			\OC_JSON::callCheck();
962
-			\OC_JSON::checkAdminUser();
963
-			$appIds = (array)$request->getParam('appid');
964
-			foreach($appIds as $appId) {
965
-				$appId = \OC_App::cleanAppId($appId);
966
-				\OC::$server->getAppManager()->disableApp($appId);
967
-			}
968
-			\OC_JSON::success();
969
-			exit();
970
-		}
971
-
972
-		// Always load authentication apps
973
-		OC_App::loadApps(['authentication']);
974
-
975
-		// Load minimum set of apps
976
-		if (!\OCP\Util::needUpgrade()
977
-			&& !$systemConfig->getValue('maintenance', false)) {
978
-			// For logged-in users: Load everything
979
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
980
-				OC_App::loadApps();
981
-			} else {
982
-				// For guests: Load only filesystem and logging
983
-				OC_App::loadApps(array('filesystem', 'logging'));
984
-				self::handleLogin($request);
985
-			}
986
-		}
987
-
988
-		if (!self::$CLI) {
989
-			try {
990
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
991
-					OC_App::loadApps(array('filesystem', 'logging'));
992
-					OC_App::loadApps();
993
-				}
994
-				OC_Util::setupFS();
995
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
996
-				return;
997
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
998
-				//header('HTTP/1.0 404 Not Found');
999
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1000
-				OC_Response::setStatus(405);
1001
-				return;
1002
-			}
1003
-		}
1004
-
1005
-		// Handle WebDAV
1006
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1007
-			// not allowed any more to prevent people
1008
-			// mounting this root directly.
1009
-			// Users need to mount remote.php/webdav instead.
1010
-			header('HTTP/1.1 405 Method Not Allowed');
1011
-			header('Status: 405 Method Not Allowed');
1012
-			return;
1013
-		}
1014
-
1015
-		// Someone is logged in
1016
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1017
-			OC_App::loadApps();
1018
-			OC_User::setupBackends();
1019
-			OC_Util::setupFS();
1020
-			// FIXME
1021
-			// Redirect to default application
1022
-			OC_Util::redirectToDefaultPage();
1023
-		} else {
1024
-			// Not handled and not logged in
1025
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1026
-		}
1027
-	}
1028
-
1029
-	/**
1030
-	 * Check login: apache auth, auth token, basic auth
1031
-	 *
1032
-	 * @param OCP\IRequest $request
1033
-	 * @return boolean
1034
-	 */
1035
-	static function handleLogin(OCP\IRequest $request) {
1036
-		$userSession = self::$server->getUserSession();
1037
-		if (OC_User::handleApacheAuth()) {
1038
-			return true;
1039
-		}
1040
-		if ($userSession->tryTokenLogin($request)) {
1041
-			return true;
1042
-		}
1043
-		if (isset($_COOKIE['nc_username'])
1044
-			&& isset($_COOKIE['nc_token'])
1045
-			&& isset($_COOKIE['nc_session_id'])
1046
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1047
-			return true;
1048
-		}
1049
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1050
-			return true;
1051
-		}
1052
-		return false;
1053
-	}
1054
-
1055
-	protected static function handleAuthHeaders() {
1056
-		//copy http auth headers for apache+php-fcgid work around
1057
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1058
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1059
-		}
1060
-
1061
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1062
-		$vars = array(
1063
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1064
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1065
-		);
1066
-		foreach ($vars as $var) {
1067
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1068
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1069
-				$_SERVER['PHP_AUTH_USER'] = $name;
1070
-				$_SERVER['PHP_AUTH_PW'] = $password;
1071
-				break;
1072
-			}
1073
-		}
1074
-	}
71
+    /**
72
+     * Associative array for autoloading. classname => filename
73
+     */
74
+    public static $CLASSPATH = array();
75
+    /**
76
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
77
+     */
78
+    public static $SERVERROOT = '';
79
+    /**
80
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
81
+     */
82
+    private static $SUBURI = '';
83
+    /**
84
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
85
+     */
86
+    public static $WEBROOT = '';
87
+    /**
88
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
89
+     * web path in 'url'
90
+     */
91
+    public static $APPSROOTS = array();
92
+
93
+    /**
94
+     * @var string
95
+     */
96
+    public static $configDir;
97
+
98
+    /**
99
+     * requested app
100
+     */
101
+    public static $REQUESTEDAPP = '';
102
+
103
+    /**
104
+     * check if Nextcloud runs in cli mode
105
+     */
106
+    public static $CLI = false;
107
+
108
+    /**
109
+     * @var \OC\Autoloader $loader
110
+     */
111
+    public static $loader = null;
112
+
113
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
114
+    public static $composerAutoloader = null;
115
+
116
+    /**
117
+     * @var \OC\Server
118
+     */
119
+    public static $server = null;
120
+
121
+    /**
122
+     * @var \OC\Config
123
+     */
124
+    private static $config = null;
125
+
126
+    /**
127
+     * @throws \RuntimeException when the 3rdparty directory is missing or
128
+     * the app path list is empty or contains an invalid path
129
+     */
130
+    public static function initPaths() {
131
+        if(defined('PHPUNIT_CONFIG_DIR')) {
132
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
+            self::$configDir = rtrim($dir, '/') . '/';
137
+        } else {
138
+            self::$configDir = OC::$SERVERROOT . '/config/';
139
+        }
140
+        self::$config = new \OC\Config(self::$configDir);
141
+
142
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
143
+        /**
144
+         * FIXME: The following lines are required because we can't yet instantiate
145
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
146
+         */
147
+        $params = [
148
+            'server' => [
149
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
150
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
151
+            ],
152
+        ];
153
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
154
+        $scriptName = $fakeRequest->getScriptName();
155
+        if (substr($scriptName, -1) == '/') {
156
+            $scriptName .= 'index.php';
157
+            //make sure suburi follows the same rules as scriptName
158
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
159
+                if (substr(OC::$SUBURI, -1) != '/') {
160
+                    OC::$SUBURI = OC::$SUBURI . '/';
161
+                }
162
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
163
+            }
164
+        }
165
+
166
+
167
+        if (OC::$CLI) {
168
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
169
+        } else {
170
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
171
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172
+
173
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
175
+                }
176
+            } else {
177
+                // The scriptName is not ending with OC::$SUBURI
178
+                // This most likely means that we are calling from CLI.
179
+                // However some cron jobs still need to generate
180
+                // a web URL, so we use overwritewebroot as a fallback.
181
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
182
+            }
183
+
184
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
185
+            // slash which is required by URL generation.
186
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
187
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
188
+                header('Location: '.\OC::$WEBROOT.'/');
189
+                exit();
190
+            }
191
+        }
192
+
193
+        // search the apps folder
194
+        $config_paths = self::$config->getValue('apps_paths', array());
195
+        if (!empty($config_paths)) {
196
+            foreach ($config_paths as $paths) {
197
+                if (isset($paths['url']) && isset($paths['path'])) {
198
+                    $paths['url'] = rtrim($paths['url'], '/');
199
+                    $paths['path'] = rtrim($paths['path'], '/');
200
+                    OC::$APPSROOTS[] = $paths;
201
+                }
202
+            }
203
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
206
+            OC::$APPSROOTS[] = array(
207
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
208
+                'url' => '/apps',
209
+                'writable' => true
210
+            );
211
+        }
212
+
213
+        if (empty(OC::$APPSROOTS)) {
214
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
215
+                . ' or the folder above. You can also configure the location in the config.php file.');
216
+        }
217
+        $paths = array();
218
+        foreach (OC::$APPSROOTS as $path) {
219
+            $paths[] = $path['path'];
220
+            if (!is_dir($path['path'])) {
221
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
222
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
223
+                    . ' config.php file.', $path['path']));
224
+            }
225
+        }
226
+
227
+        // set the right include path
228
+        set_include_path(
229
+            implode(PATH_SEPARATOR, $paths)
230
+        );
231
+    }
232
+
233
+    public static function checkConfig() {
234
+        $l = \OC::$server->getL10N('lib');
235
+
236
+        // Create config if it does not already exist
237
+        $configFilePath = self::$configDir .'/config.php';
238
+        if(!file_exists($configFilePath)) {
239
+            @touch($configFilePath);
240
+        }
241
+
242
+        // Check if config is writable
243
+        $configFileWritable = is_writable($configFilePath);
244
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
245
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
246
+
247
+            $urlGenerator = \OC::$server->getURLGenerator();
248
+
249
+            if (self::$CLI) {
250
+                echo $l->t('Cannot write into "config" directory!')."\n";
251
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
+                echo "\n";
254
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
256
+                exit;
257
+            } else {
258
+                OC_Template::printErrorPage(
259
+                    $l->t('Cannot write into "config" directory!'),
260
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
+                    [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
262
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
+                    [ $urlGenerator->linkToDocs('admin-config') ] ),
264
+                    \OC_Response::STATUS_SERVICE_UNAVAILABLE
265
+                );
266
+            }
267
+        }
268
+    }
269
+
270
+    public static function checkInstalled() {
271
+        if (defined('OC_CONSOLE')) {
272
+            return;
273
+        }
274
+        // Redirect to installer if not installed
275
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
276
+            if (OC::$CLI) {
277
+                throw new Exception('Not installed');
278
+            } else {
279
+                $url = OC::$WEBROOT . '/index.php';
280
+                header('Location: ' . $url);
281
+            }
282
+            exit();
283
+        }
284
+    }
285
+
286
+    public static function checkMaintenanceMode() {
287
+        // Allow ajax update script to execute without being stopped
288
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
289
+            // send http status 503
290
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
291
+            header('Status: 503 Service Temporarily Unavailable');
292
+            header('Retry-After: 120');
293
+
294
+            // render error page
295
+            $template = new OC_Template('', 'update.user', 'guest');
296
+            OC_Util::addScript('maintenance-check');
297
+            OC_Util::addStyle('core', 'guest');
298
+            $template->printPage();
299
+            die();
300
+        }
301
+    }
302
+
303
+    /**
304
+     * Prints the upgrade page
305
+     *
306
+     * @param \OC\SystemConfig $systemConfig
307
+     */
308
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
309
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
310
+        $tooBig = false;
311
+        if (!$disableWebUpdater) {
312
+            $apps = \OC::$server->getAppManager();
313
+            if ($apps->isInstalled('user_ldap')) {
314
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
315
+
316
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
317
+                    ->from('ldap_user_mapping')
318
+                    ->execute();
319
+                $row = $result->fetch();
320
+                $result->closeCursor();
321
+
322
+                $tooBig = ($row['user_count'] > 50);
323
+            }
324
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
325
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
+
327
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
+                    ->from('user_saml_users')
329
+                    ->execute();
330
+                $row = $result->fetch();
331
+                $result->closeCursor();
332
+
333
+                $tooBig = ($row['user_count'] > 50);
334
+            }
335
+            if (!$tooBig) {
336
+                // count users
337
+                $stats = \OC::$server->getUserManager()->countUsers();
338
+                $totalUsers = array_sum($stats);
339
+                $tooBig = ($totalUsers > 50);
340
+            }
341
+        }
342
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
343
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
344
+
345
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
346
+            // send http status 503
347
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
348
+            header('Status: 503 Service Temporarily Unavailable');
349
+            header('Retry-After: 120');
350
+
351
+            // render error page
352
+            $template = new OC_Template('', 'update.use-cli', 'guest');
353
+            $template->assign('productName', 'nextcloud'); // for now
354
+            $template->assign('version', OC_Util::getVersionString());
355
+            $template->assign('tooBig', $tooBig);
356
+
357
+            $template->printPage();
358
+            die();
359
+        }
360
+
361
+        // check whether this is a core update or apps update
362
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
363
+        $currentVersion = implode('.', \OCP\Util::getVersion());
364
+
365
+        // if not a core upgrade, then it's apps upgrade
366
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
367
+
368
+        $oldTheme = $systemConfig->getValue('theme');
369
+        $systemConfig->setValue('theme', '');
370
+        OC_Util::addScript('config'); // needed for web root
371
+        OC_Util::addScript('update');
372
+
373
+        /** @var \OC\App\AppManager $appManager */
374
+        $appManager = \OC::$server->getAppManager();
375
+
376
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
377
+        $tmpl->assign('version', OC_Util::getVersionString());
378
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
379
+
380
+        // get third party apps
381
+        $ocVersion = \OCP\Util::getVersion();
382
+        $ocVersion = implode('.', $ocVersion);
383
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
384
+        $incompatibleShippedApps = [];
385
+        foreach ($incompatibleApps as $appInfo) {
386
+            if ($appManager->isShipped($appInfo['id'])) {
387
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
388
+            }
389
+        }
390
+
391
+        if (!empty($incompatibleShippedApps)) {
392
+            $l = \OC::$server->getL10N('core');
393
+            $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)]);
394
+            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);
395
+        }
396
+
397
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
398
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
399
+        $tmpl->assign('productName', 'Nextcloud'); // for now
400
+        $tmpl->assign('oldTheme', $oldTheme);
401
+        $tmpl->printPage();
402
+    }
403
+
404
+    public static function initSession() {
405
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
406
+            ini_set('session.cookie_secure', true);
407
+        }
408
+
409
+        // prevents javascript from accessing php session cookies
410
+        ini_set('session.cookie_httponly', 'true');
411
+
412
+        // set the cookie path to the Nextcloud directory
413
+        $cookie_path = OC::$WEBROOT ? : '/';
414
+        ini_set('session.cookie_path', $cookie_path);
415
+
416
+        // Let the session name be changed in the initSession Hook
417
+        $sessionName = OC_Util::getInstanceId();
418
+
419
+        try {
420
+            // Allow session apps to create a custom session object
421
+            $useCustomSession = false;
422
+            $session = self::$server->getSession();
423
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
424
+            if (!$useCustomSession) {
425
+                // set the session name to the instance id - which is unique
426
+                $session = new \OC\Session\Internal($sessionName);
427
+            }
428
+
429
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
430
+            $session = $cryptoWrapper->wrapSession($session);
431
+            self::$server->setSession($session);
432
+
433
+            // if session can't be started break with http 500 error
434
+        } catch (Exception $e) {
435
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
436
+            //show the user a detailed error page
437
+            OC_Template::printExceptionErrorPage($e, \OC_Response::STATUS_INTERNAL_SERVER_ERROR);
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 = \OC::$server->getConfig()->getSystemValue('csrf.optout');
531
+
532
+        // Fallback, if csrf.optout is unset
533
+        if (!is_array($incompatibleUserAgents)) {
534
+            $incompatibleUserAgents = [
535
+                // OS X Finder
536
+                '/^WebDAVFS/',
537
+                // Windows webdav drive
538
+                '/^Microsoft-WebDAV-MiniRedir/',
539
+            ];
540
+        }
541
+
542
+        if($request->isUserAgent($incompatibleUserAgents)) {
543
+            return;
544
+        }
545
+
546
+        if(count($_COOKIE) > 0) {
547
+            $requestUri = $request->getScriptName();
548
+            $processingScript = explode('/', $requestUri);
549
+            $processingScript = $processingScript[count($processingScript)-1];
550
+
551
+            // index.php routes are handled in the middleware
552
+            if($processingScript === 'index.php') {
553
+                return;
554
+            }
555
+
556
+            // All other endpoints require the lax and the strict cookie
557
+            if(!$request->passesStrictCookieCheck()) {
558
+                self::sendSameSiteCookies();
559
+                // Debug mode gets access to the resources without strict cookie
560
+                // due to the fact that the SabreDAV browser also lives there.
561
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
562
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
563
+                    exit();
564
+                }
565
+            }
566
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
567
+            self::sendSameSiteCookies();
568
+        }
569
+    }
570
+
571
+    public static function init() {
572
+        // calculate the root directories
573
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
574
+
575
+        // register autoloader
576
+        $loaderStart = microtime(true);
577
+        require_once __DIR__ . '/autoloader.php';
578
+        self::$loader = new \OC\Autoloader([
579
+            OC::$SERVERROOT . '/lib/private/legacy',
580
+        ]);
581
+        if (defined('PHPUNIT_RUN')) {
582
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
583
+        }
584
+        spl_autoload_register(array(self::$loader, 'load'));
585
+        $loaderEnd = microtime(true);
586
+
587
+        self::$CLI = (php_sapi_name() == 'cli');
588
+
589
+        // Add default composer PSR-4 autoloader
590
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
591
+
592
+        try {
593
+            self::initPaths();
594
+            // setup 3rdparty autoloader
595
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
596
+            if (!file_exists($vendorAutoLoad)) {
597
+                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".');
598
+            }
599
+            require_once $vendorAutoLoad;
600
+
601
+        } catch (\RuntimeException $e) {
602
+            if (!self::$CLI) {
603
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
604
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
605
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
606
+            }
607
+            // we can't use the template error page here, because this needs the
608
+            // DI container which isn't available yet
609
+            print($e->getMessage());
610
+            exit();
611
+        }
612
+
613
+        // setup the basic server
614
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
615
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
616
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
617
+
618
+        // Don't display errors and log them
619
+        error_reporting(E_ALL | E_STRICT);
620
+        @ini_set('display_errors', '0');
621
+        @ini_set('log_errors', '1');
622
+
623
+        if(!date_default_timezone_set('UTC')) {
624
+            throw new \RuntimeException('Could not set timezone to UTC');
625
+        }
626
+
627
+        //try to configure php to enable big file uploads.
628
+        //this doesn´t work always depending on the webserver and php configuration.
629
+        //Let´s try to overwrite some defaults anyway
630
+
631
+        //try to set the maximum execution time to 60min
632
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
633
+            @set_time_limit(3600);
634
+        }
635
+        @ini_set('max_execution_time', '3600');
636
+        @ini_set('max_input_time', '3600');
637
+
638
+        //try to set the maximum filesize to 10G
639
+        @ini_set('upload_max_filesize', '10G');
640
+        @ini_set('post_max_size', '10G');
641
+        @ini_set('file_uploads', '50');
642
+
643
+        self::setRequiredIniValues();
644
+        self::handleAuthHeaders();
645
+        self::registerAutoloaderCache();
646
+
647
+        // initialize intl fallback is necessary
648
+        \Patchwork\Utf8\Bootup::initIntl();
649
+        OC_Util::isSetLocaleWorking();
650
+
651
+        if (!defined('PHPUNIT_RUN')) {
652
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
653
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
654
+            OC\Log\ErrorHandler::register($debug);
655
+        }
656
+
657
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
658
+        OC_App::loadApps(array('session'));
659
+        if (!self::$CLI) {
660
+            self::initSession();
661
+        }
662
+        \OC::$server->getEventLogger()->end('init_session');
663
+        self::checkConfig();
664
+        self::checkInstalled();
665
+
666
+        OC_Response::addSecurityHeaders();
667
+
668
+        self::performSameSiteCookieProtection();
669
+
670
+        if (!defined('OC_CONSOLE')) {
671
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
672
+            if (count($errors) > 0) {
673
+                if (self::$CLI) {
674
+                    // Convert l10n string into regular string for usage in database
675
+                    $staticErrors = [];
676
+                    foreach ($errors as $error) {
677
+                        echo $error['error'] . "\n";
678
+                        echo $error['hint'] . "\n\n";
679
+                        $staticErrors[] = [
680
+                            'error' => (string)$error['error'],
681
+                            'hint' => (string)$error['hint'],
682
+                        ];
683
+                    }
684
+
685
+                    try {
686
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
687
+                    } catch (\Exception $e) {
688
+                        echo('Writing to database failed');
689
+                    }
690
+                    exit(1);
691
+                } else {
692
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
693
+                    OC_Util::addStyle('guest');
694
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
695
+                    exit;
696
+                }
697
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
698
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
699
+            }
700
+        }
701
+        //try to set the session lifetime
702
+        $sessionLifeTime = self::getSessionLifeTime();
703
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
704
+
705
+        $systemConfig = \OC::$server->getSystemConfig();
706
+
707
+        // User and Groups
708
+        if (!$systemConfig->getValue("installed", false)) {
709
+            self::$server->getSession()->set('user_id', '');
710
+        }
711
+
712
+        OC_User::useBackend(new \OC\User\Database());
713
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
714
+
715
+        // Subscribe to the hook
716
+        \OCP\Util::connectHook(
717
+            '\OCA\Files_Sharing\API\Server2Server',
718
+            'preLoginNameUsedAsUserName',
719
+            '\OC\User\Database',
720
+            'preLoginNameUsedAsUserName'
721
+        );
722
+
723
+        //setup extra user backends
724
+        if (!\OCP\Util::needUpgrade()) {
725
+            OC_User::setupBackends();
726
+        } else {
727
+            // Run upgrades in incognito mode
728
+            OC_User::setIncognitoMode(true);
729
+        }
730
+
731
+        self::registerCleanupHooks();
732
+        self::registerFilesystemHooks();
733
+        self::registerShareHooks();
734
+        self::registerEncryptionWrapper();
735
+        self::registerEncryptionHooks();
736
+        self::registerAccountHooks();
737
+
738
+        // Make sure that the application class is not loaded before the database is setup
739
+        if ($systemConfig->getValue("installed", false)) {
740
+            $settings = new \OC\Settings\Application();
741
+            $settings->register();
742
+        }
743
+
744
+        //make sure temporary files are cleaned up
745
+        $tmpManager = \OC::$server->getTempManager();
746
+        register_shutdown_function(array($tmpManager, 'clean'));
747
+        $lockProvider = \OC::$server->getLockingProvider();
748
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
749
+
750
+        // Check whether the sample configuration has been copied
751
+        if($systemConfig->getValue('copied_sample_config', false)) {
752
+            $l = \OC::$server->getL10N('lib');
753
+            OC_Template::printErrorPage(
754
+                $l->t('Sample configuration detected'),
755
+                $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'),
756
+                \OC_Response::STATUS_SERVICE_UNAVAILABLE
757
+            );
758
+            return;
759
+        }
760
+
761
+        $request = \OC::$server->getRequest();
762
+        $host = $request->getInsecureServerHost();
763
+        /**
764
+         * if the host passed in headers isn't trusted
765
+         * FIXME: Should not be in here at all :see_no_evil:
766
+         */
767
+        if (!OC::$CLI
768
+            // overwritehost is always trusted, workaround to not have to make
769
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
770
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
771
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
772
+            && self::$server->getConfig()->getSystemValue('installed', false)
773
+        ) {
774
+            // Allow access to CSS resources
775
+            $isScssRequest = false;
776
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
777
+                $isScssRequest = true;
778
+            }
779
+
780
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
781
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
782
+                header('Status: 400 Bad Request');
783
+                header('Content-Type: application/json');
784
+                echo '{"error": "Trusted domain error.", "code": 15}';
785
+                exit();
786
+            }
787
+
788
+            if (!$isScssRequest) {
789
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
790
+                header('Status: 400 Bad Request');
791
+
792
+                \OC::$server->getLogger()->info(
793
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
794
+                    [
795
+                        'app' => 'core',
796
+                        'remoteAddress' => $request->getRemoteAddress(),
797
+                        'host' => $host,
798
+                    ]
799
+                );
800
+
801
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
802
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
803
+                $tmpl->printPage();
804
+
805
+                exit();
806
+            }
807
+        }
808
+        \OC::$server->getEventLogger()->end('boot');
809
+    }
810
+
811
+    /**
812
+     * register hooks for the cleanup of cache and bruteforce protection
813
+     */
814
+    public static function registerCleanupHooks() {
815
+        //don't try to do this before we are properly setup
816
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
817
+
818
+            // NOTE: This will be replaced to use OCP
819
+            $userSession = self::$server->getUserSession();
820
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
821
+                if (!defined('PHPUNIT_RUN')) {
822
+                    // reset brute force delay for this IP address and username
823
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
824
+                    $request = \OC::$server->getRequest();
825
+                    $throttler = \OC::$server->getBruteForceThrottler();
826
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
827
+                }
828
+
829
+                try {
830
+                    $cache = new \OC\Cache\File();
831
+                    $cache->gc();
832
+                } catch (\OC\ServerNotAvailableException $e) {
833
+                    // not a GC exception, pass it on
834
+                    throw $e;
835
+                } catch (\OC\ForbiddenException $e) {
836
+                    // filesystem blocked for this request, ignore
837
+                } catch (\Exception $e) {
838
+                    // a GC exception should not prevent users from using OC,
839
+                    // so log the exception
840
+                    \OC::$server->getLogger()->logException($e, [
841
+                        'message' => 'Exception when running cache gc.',
842
+                        'level' => ILogger::WARN,
843
+                        'app' => 'core',
844
+                    ]);
845
+                }
846
+            });
847
+        }
848
+    }
849
+
850
+    private static function registerEncryptionWrapper() {
851
+        $manager = self::$server->getEncryptionManager();
852
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
853
+    }
854
+
855
+    private static function registerEncryptionHooks() {
856
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
857
+        if ($enabled) {
858
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
859
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
860
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
861
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
862
+        }
863
+    }
864
+
865
+    private static function registerAccountHooks() {
866
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
867
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
868
+    }
869
+
870
+    /**
871
+     * register hooks for the filesystem
872
+     */
873
+    public static function registerFilesystemHooks() {
874
+        // Check for blacklisted files
875
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
876
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
877
+    }
878
+
879
+    /**
880
+     * register hooks for sharing
881
+     */
882
+    public static function registerShareHooks() {
883
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
884
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
885
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
886
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
887
+        }
888
+    }
889
+
890
+    protected static function registerAutoloaderCache() {
891
+        // The class loader takes an optional low-latency cache, which MUST be
892
+        // namespaced. The instanceid is used for namespacing, but might be
893
+        // unavailable at this point. Furthermore, it might not be possible to
894
+        // generate an instanceid via \OC_Util::getInstanceId() because the
895
+        // config file may not be writable. As such, we only register a class
896
+        // loader cache if instanceid is available without trying to create one.
897
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
898
+        if ($instanceId) {
899
+            try {
900
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
901
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
902
+            } catch (\Exception $ex) {
903
+            }
904
+
905
+            self::$composerAutoloader->setApcuPrefix($instanceId . '-mainComposer');
906
+        }
907
+    }
908
+
909
+    /**
910
+     * Handle the request
911
+     */
912
+    public static function handleRequest() {
913
+
914
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
915
+        $systemConfig = \OC::$server->getSystemConfig();
916
+        // load all the classpaths from the enabled apps so they are available
917
+        // in the routing files of each app
918
+        OC::loadAppClassPaths();
919
+
920
+        // Check if Nextcloud is installed or in maintenance (update) mode
921
+        if (!$systemConfig->getValue('installed', false)) {
922
+            \OC::$server->getSession()->clear();
923
+            $setupHelper = new OC\Setup(
924
+                $systemConfig,
925
+                \OC::$server->getIniWrapper(),
926
+                \OC::$server->getL10N('lib'),
927
+                \OC::$server->query(\OCP\Defaults::class),
928
+                \OC::$server->getLogger(),
929
+                \OC::$server->getSecureRandom(),
930
+                \OC::$server->query(\OC\Installer::class)
931
+            );
932
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
933
+            $controller->run($_POST);
934
+            exit();
935
+        }
936
+
937
+        $request = \OC::$server->getRequest();
938
+        $requestPath = $request->getRawPathInfo();
939
+        if ($requestPath === '/heartbeat') {
940
+            return;
941
+        }
942
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
943
+            self::checkMaintenanceMode();
944
+
945
+            if (\OCP\Util::needUpgrade()) {
946
+                if (function_exists('opcache_reset')) {
947
+                    opcache_reset();
948
+                }
949
+                if (!$systemConfig->getValue('maintenance', false)) {
950
+                    self::printUpgradePage($systemConfig);
951
+                    exit();
952
+                }
953
+            }
954
+        }
955
+
956
+        // emergency app disabling
957
+        if ($requestPath === '/disableapp'
958
+            && $request->getMethod() === 'POST'
959
+            && ((array)$request->getParam('appid')) !== ''
960
+        ) {
961
+            \OC_JSON::callCheck();
962
+            \OC_JSON::checkAdminUser();
963
+            $appIds = (array)$request->getParam('appid');
964
+            foreach($appIds as $appId) {
965
+                $appId = \OC_App::cleanAppId($appId);
966
+                \OC::$server->getAppManager()->disableApp($appId);
967
+            }
968
+            \OC_JSON::success();
969
+            exit();
970
+        }
971
+
972
+        // Always load authentication apps
973
+        OC_App::loadApps(['authentication']);
974
+
975
+        // Load minimum set of apps
976
+        if (!\OCP\Util::needUpgrade()
977
+            && !$systemConfig->getValue('maintenance', false)) {
978
+            // For logged-in users: Load everything
979
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
980
+                OC_App::loadApps();
981
+            } else {
982
+                // For guests: Load only filesystem and logging
983
+                OC_App::loadApps(array('filesystem', 'logging'));
984
+                self::handleLogin($request);
985
+            }
986
+        }
987
+
988
+        if (!self::$CLI) {
989
+            try {
990
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
991
+                    OC_App::loadApps(array('filesystem', 'logging'));
992
+                    OC_App::loadApps();
993
+                }
994
+                OC_Util::setupFS();
995
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
996
+                return;
997
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
998
+                //header('HTTP/1.0 404 Not Found');
999
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1000
+                OC_Response::setStatus(405);
1001
+                return;
1002
+            }
1003
+        }
1004
+
1005
+        // Handle WebDAV
1006
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1007
+            // not allowed any more to prevent people
1008
+            // mounting this root directly.
1009
+            // Users need to mount remote.php/webdav instead.
1010
+            header('HTTP/1.1 405 Method Not Allowed');
1011
+            header('Status: 405 Method Not Allowed');
1012
+            return;
1013
+        }
1014
+
1015
+        // Someone is logged in
1016
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1017
+            OC_App::loadApps();
1018
+            OC_User::setupBackends();
1019
+            OC_Util::setupFS();
1020
+            // FIXME
1021
+            // Redirect to default application
1022
+            OC_Util::redirectToDefaultPage();
1023
+        } else {
1024
+            // Not handled and not logged in
1025
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1026
+        }
1027
+    }
1028
+
1029
+    /**
1030
+     * Check login: apache auth, auth token, basic auth
1031
+     *
1032
+     * @param OCP\IRequest $request
1033
+     * @return boolean
1034
+     */
1035
+    static function handleLogin(OCP\IRequest $request) {
1036
+        $userSession = self::$server->getUserSession();
1037
+        if (OC_User::handleApacheAuth()) {
1038
+            return true;
1039
+        }
1040
+        if ($userSession->tryTokenLogin($request)) {
1041
+            return true;
1042
+        }
1043
+        if (isset($_COOKIE['nc_username'])
1044
+            && isset($_COOKIE['nc_token'])
1045
+            && isset($_COOKIE['nc_session_id'])
1046
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1047
+            return true;
1048
+        }
1049
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1050
+            return true;
1051
+        }
1052
+        return false;
1053
+    }
1054
+
1055
+    protected static function handleAuthHeaders() {
1056
+        //copy http auth headers for apache+php-fcgid work around
1057
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1058
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1059
+        }
1060
+
1061
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1062
+        $vars = array(
1063
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1064
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1065
+        );
1066
+        foreach ($vars as $var) {
1067
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1068
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1069
+                $_SERVER['PHP_AUTH_USER'] = $name;
1070
+                $_SERVER['PHP_AUTH_PW'] = $password;
1071
+                break;
1072
+            }
1073
+        }
1074
+    }
1075 1075
 }
1076 1076
 
1077 1077
 OC::init();
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -128,14 +128,14 @@  discard block
 block discarded – undo
128 128
 	 * the app path list is empty or contains an invalid path
129 129
 	 */
130 130
 	public static function initPaths() {
131
-		if(defined('PHPUNIT_CONFIG_DIR')) {
132
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
133
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
134
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
135
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
-			self::$configDir = rtrim($dir, '/') . '/';
131
+		if (defined('PHPUNIT_CONFIG_DIR')) {
132
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
133
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
134
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
135
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
136
+			self::$configDir = rtrim($dir, '/').'/';
137 137
 		} else {
138
-			self::$configDir = OC::$SERVERROOT . '/config/';
138
+			self::$configDir = OC::$SERVERROOT.'/config/';
139 139
 		}
140 140
 		self::$config = new \OC\Config(self::$configDir);
141 141
 
@@ -157,9 +157,9 @@  discard block
 block discarded – undo
157 157
 			//make sure suburi follows the same rules as scriptName
158 158
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
159 159
 				if (substr(OC::$SUBURI, -1) != '/') {
160
-					OC::$SUBURI = OC::$SUBURI . '/';
160
+					OC::$SUBURI = OC::$SUBURI.'/';
161 161
 				}
162
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
162
+				OC::$SUBURI = OC::$SUBURI.'index.php';
163 163
 			}
164 164
 		}
165 165
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
172 172
 
173 173
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
174
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
174
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
175 175
 				}
176 176
 			} else {
177 177
 				// The scriptName is not ending with OC::$SUBURI
@@ -200,11 +200,11 @@  discard block
 block discarded – undo
200 200
 					OC::$APPSROOTS[] = $paths;
201 201
 				}
202 202
 			}
203
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
204
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
205
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
203
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
204
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
205
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
206 206
 			OC::$APPSROOTS[] = array(
207
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
207
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
208 208
 				'url' => '/apps',
209 209
 				'writable' => true
210 210
 			);
@@ -234,8 +234,8 @@  discard block
 block discarded – undo
234 234
 		$l = \OC::$server->getL10N('lib');
235 235
 
236 236
 		// Create config if it does not already exist
237
-		$configFilePath = self::$configDir .'/config.php';
238
-		if(!file_exists($configFilePath)) {
237
+		$configFilePath = self::$configDir.'/config.php';
238
+		if (!file_exists($configFilePath)) {
239 239
 			@touch($configFilePath);
240 240
 		}
241 241
 
@@ -249,18 +249,18 @@  discard block
 block discarded – undo
249 249
 			if (self::$CLI) {
250 250
 				echo $l->t('Cannot write into "config" directory!')."\n";
251 251
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
252
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
252
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
253 253
 				echo "\n";
254 254
 				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
255
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
255
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')])."\n";
256 256
 				exit;
257 257
 			} else {
258 258
 				OC_Template::printErrorPage(
259 259
 					$l->t('Cannot write into "config" directory!'),
260 260
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
261
-					[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
261
+					[$urlGenerator->linkToDocs('admin-dir_permissions')]).'. '
262 262
 					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
263
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
263
+					[$urlGenerator->linkToDocs('admin-config')]),
264 264
 					\OC_Response::STATUS_SERVICE_UNAVAILABLE
265 265
 				);
266 266
 			}
@@ -276,8 +276,8 @@  discard block
 block discarded – undo
276 276
 			if (OC::$CLI) {
277 277
 				throw new Exception('Not installed');
278 278
 			} else {
279
-				$url = OC::$WEBROOT . '/index.php';
280
-				header('Location: ' . $url);
279
+				$url = OC::$WEBROOT.'/index.php';
280
+				header('Location: '.$url);
281 281
 			}
282 282
 			exit();
283 283
 		}
@@ -384,14 +384,14 @@  discard block
 block discarded – undo
384 384
 		$incompatibleShippedApps = [];
385 385
 		foreach ($incompatibleApps as $appInfo) {
386 386
 			if ($appManager->isShipped($appInfo['id'])) {
387
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
387
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
388 388
 			}
389 389
 		}
390 390
 
391 391
 		if (!empty($incompatibleShippedApps)) {
392 392
 			$l = \OC::$server->getL10N('core');
393 393
 			$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)]);
394
-			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);
394
+			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);
395 395
 		}
396 396
 
397 397
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
 	}
403 403
 
404 404
 	public static function initSession() {
405
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
405
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
406 406
 			ini_set('session.cookie_secure', true);
407 407
 		}
408 408
 
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		ini_set('session.cookie_httponly', 'true');
411 411
 
412 412
 		// set the cookie path to the Nextcloud directory
413
-		$cookie_path = OC::$WEBROOT ? : '/';
413
+		$cookie_path = OC::$WEBROOT ?: '/';
414 414
 		ini_set('session.cookie_path', $cookie_path);
415 415
 
416 416
 		// 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'],
@@ -539,31 +539,31 @@  discard block
 block discarded – undo
539 539
 			];
540 540
 		}
541 541
 
542
-		if($request->isUserAgent($incompatibleUserAgents)) {
542
+		if ($request->isUserAgent($incompatibleUserAgents)) {
543 543
 			return;
544 544
 		}
545 545
 
546
-		if(count($_COOKIE) > 0) {
546
+		if (count($_COOKIE) > 0) {
547 547
 			$requestUri = $request->getScriptName();
548 548
 			$processingScript = explode('/', $requestUri);
549
-			$processingScript = $processingScript[count($processingScript)-1];
549
+			$processingScript = $processingScript[count($processingScript) - 1];
550 550
 
551 551
 			// index.php routes are handled in the middleware
552
-			if($processingScript === 'index.php') {
552
+			if ($processingScript === 'index.php') {
553 553
 				return;
554 554
 			}
555 555
 
556 556
 			// All other endpoints require the lax and the strict cookie
557
-			if(!$request->passesStrictCookieCheck()) {
557
+			if (!$request->passesStrictCookieCheck()) {
558 558
 				self::sendSameSiteCookies();
559 559
 				// Debug mode gets access to the resources without strict cookie
560 560
 				// due to the fact that the SabreDAV browser also lives there.
561
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
562 562
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
563 563
 					exit();
564 564
 				}
565 565
 			}
566
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
567 567
 			self::sendSameSiteCookies();
568 568
 		}
569 569
 	}
@@ -574,12 +574,12 @@  discard block
 block discarded – undo
574 574
 
575 575
 		// register autoloader
576 576
 		$loaderStart = microtime(true);
577
-		require_once __DIR__ . '/autoloader.php';
577
+		require_once __DIR__.'/autoloader.php';
578 578
 		self::$loader = new \OC\Autoloader([
579
-			OC::$SERVERROOT . '/lib/private/legacy',
579
+			OC::$SERVERROOT.'/lib/private/legacy',
580 580
 		]);
581 581
 		if (defined('PHPUNIT_RUN')) {
582
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
583 583
 		}
584 584
 		spl_autoload_register(array(self::$loader, 'load'));
585 585
 		$loaderEnd = microtime(true);
@@ -587,12 +587,12 @@  discard block
 block discarded – undo
587 587
 		self::$CLI = (php_sapi_name() == 'cli');
588 588
 
589 589
 		// Add default composer PSR-4 autoloader
590
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
591 591
 
592 592
 		try {
593 593
 			self::initPaths();
594 594
 			// setup 3rdparty autoloader
595
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
596 596
 			if (!file_exists($vendorAutoLoad)) {
597 597
 				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".');
598 598
 			}
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
 			if (!self::$CLI) {
603 603
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
604 604
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
605
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
606 606
 			}
607 607
 			// we can't use the template error page here, because this needs the
608 608
 			// DI container which isn't available yet
@@ -620,7 +620,7 @@  discard block
 block discarded – undo
620 620
 		@ini_set('display_errors', '0');
621 621
 		@ini_set('log_errors', '1');
622 622
 
623
-		if(!date_default_timezone_set('UTC')) {
623
+		if (!date_default_timezone_set('UTC')) {
624 624
 			throw new \RuntimeException('Could not set timezone to UTC');
625 625
 		}
626 626
 
@@ -674,11 +674,11 @@  discard block
 block discarded – undo
674 674
 					// Convert l10n string into regular string for usage in database
675 675
 					$staticErrors = [];
676 676
 					foreach ($errors as $error) {
677
-						echo $error['error'] . "\n";
678
-						echo $error['hint'] . "\n\n";
677
+						echo $error['error']."\n";
678
+						echo $error['hint']."\n\n";
679 679
 						$staticErrors[] = [
680
-							'error' => (string)$error['error'],
681
-							'hint' => (string)$error['hint'],
680
+							'error' => (string) $error['error'],
681
+							'hint' => (string) $error['hint'],
682 682
 						];
683 683
 					}
684 684
 
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 		}
701 701
 		//try to set the session lifetime
702 702
 		$sessionLifeTime = self::getSessionLifeTime();
703
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
703
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
704 704
 
705 705
 		$systemConfig = \OC::$server->getSystemConfig();
706 706
 
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
749 749
 
750 750
 		// Check whether the sample configuration has been copied
751
-		if($systemConfig->getValue('copied_sample_config', false)) {
751
+		if ($systemConfig->getValue('copied_sample_config', false)) {
752 752
 			$l = \OC::$server->getL10N('lib');
753 753
 			OC_Template::printErrorPage(
754 754
 				$l->t('Sample configuration detected'),
@@ -773,11 +773,11 @@  discard block
 block discarded – undo
773 773
 		) {
774 774
 			// Allow access to CSS resources
775 775
 			$isScssRequest = false;
776
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
776
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
777 777
 				$isScssRequest = true;
778 778
 			}
779 779
 
780
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
780
+			if (substr($request->getRequestUri(), -11) === '/status.php') {
781 781
 				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
782 782
 				header('Status: 400 Bad Request');
783 783
 				header('Content-Type: application/json');
@@ -817,7 +817,7 @@  discard block
 block discarded – undo
817 817
 
818 818
 			// NOTE: This will be replaced to use OCP
819 819
 			$userSession = self::$server->getUserSession();
820
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
820
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
821 821
 				if (!defined('PHPUNIT_RUN')) {
822 822
 					// reset brute force delay for this IP address and username
823 823
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 			} catch (\Exception $ex) {
903 903
 			}
904 904
 
905
-			self::$composerAutoloader->setApcuPrefix($instanceId . '-mainComposer');
905
+			self::$composerAutoloader->setApcuPrefix($instanceId.'-mainComposer');
906 906
 		}
907 907
 	}
908 908
 
@@ -956,12 +956,12 @@  discard block
 block discarded – undo
956 956
 		// emergency app disabling
957 957
 		if ($requestPath === '/disableapp'
958 958
 			&& $request->getMethod() === 'POST'
959
-			&& ((array)$request->getParam('appid')) !== ''
959
+			&& ((array) $request->getParam('appid')) !== ''
960 960
 		) {
961 961
 			\OC_JSON::callCheck();
962 962
 			\OC_JSON::checkAdminUser();
963
-			$appIds = (array)$request->getParam('appid');
964
-			foreach($appIds as $appId) {
963
+			$appIds = (array) $request->getParam('appid');
964
+			foreach ($appIds as $appId) {
965 965
 				$appId = \OC_App::cleanAppId($appId);
966 966
 				\OC::$server->getAppManager()->disableApp($appId);
967 967
 			}
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
 		if (!\OCP\Util::needUpgrade()
977 977
 			&& !$systemConfig->getValue('maintenance', false)) {
978 978
 			// For logged-in users: Load everything
979
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
979
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
980 980
 				OC_App::loadApps();
981 981
 			} else {
982 982
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.