@@ -31,59 +31,59 @@ |
||
31 | 31 | require_once __DIR__ . '/lib/versioncheck.php'; |
32 | 32 | |
33 | 33 | try { |
34 | - require_once __DIR__ . '/lib/base.php'; |
|
34 | + require_once __DIR__ . '/lib/base.php'; |
|
35 | 35 | |
36 | - OC::handleRequest(); |
|
36 | + OC::handleRequest(); |
|
37 | 37 | } catch (\OC\ServiceUnavailableException $ex) { |
38 | - \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
38 | + \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
39 | 39 | |
40 | - //show the user a detailed error page |
|
41 | - OC_Template::printExceptionErrorPage($ex, 503); |
|
40 | + //show the user a detailed error page |
|
41 | + OC_Template::printExceptionErrorPage($ex, 503); |
|
42 | 42 | } catch (\OCP\HintException $ex) { |
43 | - try { |
|
44 | - OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), 503); |
|
45 | - } catch (Exception $ex2) { |
|
46 | - try { |
|
47 | - \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
48 | - \OC::$server->getLogger()->logException($ex2, ['app' => 'index']); |
|
49 | - } catch (Throwable $e) { |
|
50 | - // no way to log it properly - but to avoid a white page of death we try harder and ignore this one here |
|
51 | - } |
|
43 | + try { |
|
44 | + OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), 503); |
|
45 | + } catch (Exception $ex2) { |
|
46 | + try { |
|
47 | + \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
48 | + \OC::$server->getLogger()->logException($ex2, ['app' => 'index']); |
|
49 | + } catch (Throwable $e) { |
|
50 | + // no way to log it properly - but to avoid a white page of death we try harder and ignore this one here |
|
51 | + } |
|
52 | 52 | |
53 | - //show the user a detailed error page |
|
54 | - OC_Template::printExceptionErrorPage($ex, 500); |
|
55 | - } |
|
53 | + //show the user a detailed error page |
|
54 | + OC_Template::printExceptionErrorPage($ex, 500); |
|
55 | + } |
|
56 | 56 | } catch (\OC\User\LoginException $ex) { |
57 | - $request = \OC::$server->getRequest(); |
|
58 | - /** |
|
59 | - * Routes with the @CORS annotation and other API endpoints should |
|
60 | - * not return a webpage, so we only print the error page when html is accepted, |
|
61 | - * otherwise we reply with a JSON array like the SecurityMiddleware would do. |
|
62 | - */ |
|
63 | - if (stripos($request->getHeader('Accept'),'html') === false) { |
|
64 | - http_response_code(401); |
|
65 | - header('Content-Type: application/json; charset=utf-8'); |
|
66 | - echo json_encode(['message' => $ex->getMessage()]); |
|
67 | - exit(); |
|
68 | - } |
|
69 | - OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), 401); |
|
57 | + $request = \OC::$server->getRequest(); |
|
58 | + /** |
|
59 | + * Routes with the @CORS annotation and other API endpoints should |
|
60 | + * not return a webpage, so we only print the error page when html is accepted, |
|
61 | + * otherwise we reply with a JSON array like the SecurityMiddleware would do. |
|
62 | + */ |
|
63 | + if (stripos($request->getHeader('Accept'),'html') === false) { |
|
64 | + http_response_code(401); |
|
65 | + header('Content-Type: application/json; charset=utf-8'); |
|
66 | + echo json_encode(['message' => $ex->getMessage()]); |
|
67 | + exit(); |
|
68 | + } |
|
69 | + OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), 401); |
|
70 | 70 | } catch (Exception $ex) { |
71 | - \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
71 | + \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
72 | 72 | |
73 | - //show the user a detailed error page |
|
74 | - OC_Template::printExceptionErrorPage($ex, 500); |
|
73 | + //show the user a detailed error page |
|
74 | + OC_Template::printExceptionErrorPage($ex, 500); |
|
75 | 75 | } catch (Error $ex) { |
76 | - try { |
|
77 | - \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
78 | - } catch (Error $e) { |
|
79 | - http_response_code(500); |
|
80 | - header('Content-Type: text/plain; charset=utf-8'); |
|
81 | - print("Internal Server Error\n\n"); |
|
82 | - print("The server encountered an internal error and was unable to complete your request.\n"); |
|
83 | - print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n"); |
|
84 | - print("More details can be found in the webserver log.\n"); |
|
76 | + try { |
|
77 | + \OC::$server->getLogger()->logException($ex, ['app' => 'index']); |
|
78 | + } catch (Error $e) { |
|
79 | + http_response_code(500); |
|
80 | + header('Content-Type: text/plain; charset=utf-8'); |
|
81 | + print("Internal Server Error\n\n"); |
|
82 | + print("The server encountered an internal error and was unable to complete your request.\n"); |
|
83 | + print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n"); |
|
84 | + print("More details can be found in the webserver log.\n"); |
|
85 | 85 | |
86 | - throw $ex; |
|
87 | - } |
|
88 | - OC_Template::printExceptionErrorPage($ex, 500); |
|
86 | + throw $ex; |
|
87 | + } |
|
88 | + OC_Template::printExceptionErrorPage($ex, 500); |
|
89 | 89 | } |
@@ -34,49 +34,49 @@ |
||
34 | 34 | * @since 23.0.0 |
35 | 35 | */ |
36 | 36 | class HintException extends \Exception { |
37 | - private $hint; |
|
37 | + private $hint; |
|
38 | 38 | |
39 | - /** |
|
40 | - * HintException constructor. |
|
41 | - * |
|
42 | - * @since 23.0.0 |
|
43 | - * @param string $message The error message. It will be not revealed to the |
|
44 | - * the user (unless the hint is empty) and thus |
|
45 | - * should be not translated. |
|
46 | - * @param string $hint A useful message that is presented to the end |
|
47 | - * user. It should be translated, but must not |
|
48 | - * contain sensitive data. |
|
49 | - * @param int $code |
|
50 | - * @param \Exception|null $previous |
|
51 | - */ |
|
52 | - public function __construct($message, $hint = '', $code = 0, \Exception $previous = null) { |
|
53 | - $this->hint = $hint; |
|
54 | - parent::__construct($message, $code, $previous); |
|
55 | - } |
|
39 | + /** |
|
40 | + * HintException constructor. |
|
41 | + * |
|
42 | + * @since 23.0.0 |
|
43 | + * @param string $message The error message. It will be not revealed to the |
|
44 | + * the user (unless the hint is empty) and thus |
|
45 | + * should be not translated. |
|
46 | + * @param string $hint A useful message that is presented to the end |
|
47 | + * user. It should be translated, but must not |
|
48 | + * contain sensitive data. |
|
49 | + * @param int $code |
|
50 | + * @param \Exception|null $previous |
|
51 | + */ |
|
52 | + public function __construct($message, $hint = '', $code = 0, \Exception $previous = null) { |
|
53 | + $this->hint = $hint; |
|
54 | + parent::__construct($message, $code, $previous); |
|
55 | + } |
|
56 | 56 | |
57 | - /** |
|
58 | - * Returns a string representation of this Exception that includes the error |
|
59 | - * code, the message and the hint. |
|
60 | - * |
|
61 | - * @since 23.0.0 |
|
62 | - * @return string |
|
63 | - */ |
|
64 | - public function __toString(): string { |
|
65 | - return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; |
|
66 | - } |
|
57 | + /** |
|
58 | + * Returns a string representation of this Exception that includes the error |
|
59 | + * code, the message and the hint. |
|
60 | + * |
|
61 | + * @since 23.0.0 |
|
62 | + * @return string |
|
63 | + */ |
|
64 | + public function __toString(): string { |
|
65 | + return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; |
|
66 | + } |
|
67 | 67 | |
68 | - /** |
|
69 | - * Returns the hint with the intention to be presented to the end user. If |
|
70 | - * an empty hint was specified upon instatiation, the message is returned |
|
71 | - * instead. |
|
72 | - * |
|
73 | - * @since 23.0.0 |
|
74 | - * @return string |
|
75 | - */ |
|
76 | - public function getHint(): string { |
|
77 | - if (empty($this->hint)) { |
|
78 | - return $this->message; |
|
79 | - } |
|
80 | - return $this->hint; |
|
81 | - } |
|
68 | + /** |
|
69 | + * Returns the hint with the intention to be presented to the end user. If |
|
70 | + * an empty hint was specified upon instatiation, the message is returned |
|
71 | + * instead. |
|
72 | + * |
|
73 | + * @since 23.0.0 |
|
74 | + * @return string |
|
75 | + */ |
|
76 | + public function getHint(): string { |
|
77 | + if (empty($this->hint)) { |
|
78 | + return $this->message; |
|
79 | + } |
|
80 | + return $this->hint; |
|
81 | + } |
|
82 | 82 | } |
@@ -49,186 +49,186 @@ |
||
49 | 49 | */ |
50 | 50 | class App { |
51 | 51 | |
52 | - /** @var string[] */ |
|
53 | - private static $nameSpaceCache = []; |
|
54 | - |
|
55 | - /** |
|
56 | - * Turns an app id into a namespace by either reading the appinfo.xml's |
|
57 | - * namespace tag or uppercasing the appid's first letter |
|
58 | - * @param string $appId the app id |
|
59 | - * @param string $topNamespace the namespace which should be prepended to |
|
60 | - * the transformed app id, defaults to OCA\ |
|
61 | - * @return string the starting namespace for the app |
|
62 | - */ |
|
63 | - public static function buildAppNamespace(string $appId, string $topNamespace = 'OCA\\'): string { |
|
64 | - // Hit the cache! |
|
65 | - if (isset(self::$nameSpaceCache[$appId])) { |
|
66 | - return $topNamespace . self::$nameSpaceCache[$appId]; |
|
67 | - } |
|
68 | - |
|
69 | - $appInfo = \OC_App::getAppInfo($appId); |
|
70 | - if (isset($appInfo['namespace'])) { |
|
71 | - self::$nameSpaceCache[$appId] = trim($appInfo['namespace']); |
|
72 | - } else { |
|
73 | - if ($appId !== 'spreed') { |
|
74 | - // if the tag is not found, fall back to uppercasing the first letter |
|
75 | - self::$nameSpaceCache[$appId] = ucfirst($appId); |
|
76 | - } else { |
|
77 | - // For the Talk app (appid spreed) the above fallback doesn't work. |
|
78 | - // This leads to a problem when trying to install it freshly, |
|
79 | - // because the apps namespace is already registered before the |
|
80 | - // app is downloaded from the appstore, because of the hackish |
|
81 | - // global route index.php/call/{token} which is registered via |
|
82 | - // the core/routes.php so it does not have the app namespace. |
|
83 | - // @ref https://github.com/nextcloud/server/pull/19433 |
|
84 | - self::$nameSpaceCache[$appId] = 'Talk'; |
|
85 | - } |
|
86 | - } |
|
87 | - |
|
88 | - return $topNamespace . self::$nameSpaceCache[$appId]; |
|
89 | - } |
|
90 | - |
|
91 | - public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string { |
|
92 | - if (strpos($className, $topNamespace) !== 0) { |
|
93 | - return null; |
|
94 | - } |
|
95 | - |
|
96 | - foreach (self::$nameSpaceCache as $appId => $namespace) { |
|
97 | - if (strpos($className, $topNamespace . $namespace . '\\') === 0) { |
|
98 | - return $appId; |
|
99 | - } |
|
100 | - } |
|
101 | - |
|
102 | - return null; |
|
103 | - } |
|
104 | - |
|
105 | - |
|
106 | - /** |
|
107 | - * Shortcut for calling a controller method and printing the result |
|
108 | - * |
|
109 | - * @param string $controllerName the name of the controller under which it is |
|
110 | - * stored in the DI container |
|
111 | - * @param string $methodName the method that you want to call |
|
112 | - * @param DIContainer $container an instance of a pimple container. |
|
113 | - * @param array $urlParams list of URL parameters (optional) |
|
114 | - * @throws HintException |
|
115 | - */ |
|
116 | - public static function main(string $controllerName, string $methodName, DIContainer $container, array $urlParams = null) { |
|
117 | - if (!is_null($urlParams)) { |
|
118 | - /** @var Request $request */ |
|
119 | - $request = $container->query(IRequest::class); |
|
120 | - $request->setUrlParameters($urlParams); |
|
121 | - } elseif (isset($container['urlParams']) && !is_null($container['urlParams'])) { |
|
122 | - /** @var Request $request */ |
|
123 | - $request = $container->query(IRequest::class); |
|
124 | - $request->setUrlParameters($container['urlParams']); |
|
125 | - } |
|
126 | - $appName = $container['AppName']; |
|
127 | - |
|
128 | - // first try $controllerName then go for \OCA\AppName\Controller\$controllerName |
|
129 | - try { |
|
130 | - $controller = $container->query($controllerName); |
|
131 | - } catch (QueryException $e) { |
|
132 | - if (strpos($controllerName, '\\Controller\\') !== false) { |
|
133 | - // This is from a global registered app route that is not enabled. |
|
134 | - [/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3); |
|
135 | - throw new HintException('App ' . strtolower($app) . ' is not enabled'); |
|
136 | - } |
|
137 | - |
|
138 | - if ($appName === 'core') { |
|
139 | - $appNameSpace = 'OC\\Core'; |
|
140 | - } else { |
|
141 | - $appNameSpace = self::buildAppNamespace($appName); |
|
142 | - } |
|
143 | - $controllerName = $appNameSpace . '\\Controller\\' . $controllerName; |
|
144 | - $controller = $container->query($controllerName); |
|
145 | - } |
|
146 | - |
|
147 | - // initialize the dispatcher and run all the middleware before the controller |
|
148 | - /** @var Dispatcher $dispatcher */ |
|
149 | - $dispatcher = $container['Dispatcher']; |
|
150 | - |
|
151 | - [ |
|
152 | - $httpHeaders, |
|
153 | - $responseHeaders, |
|
154 | - $responseCookies, |
|
155 | - $output, |
|
156 | - $response |
|
157 | - ] = $dispatcher->dispatch($controller, $methodName); |
|
158 | - |
|
159 | - $io = $container[IOutput::class]; |
|
160 | - |
|
161 | - if (!is_null($httpHeaders)) { |
|
162 | - $io->setHeader($httpHeaders); |
|
163 | - } |
|
164 | - |
|
165 | - foreach ($responseHeaders as $name => $value) { |
|
166 | - $io->setHeader($name . ': ' . $value); |
|
167 | - } |
|
168 | - |
|
169 | - foreach ($responseCookies as $name => $value) { |
|
170 | - $expireDate = null; |
|
171 | - if ($value['expireDate'] instanceof \DateTime) { |
|
172 | - $expireDate = $value['expireDate']->getTimestamp(); |
|
173 | - } |
|
174 | - $sameSite = $value['sameSite'] ?? 'Lax'; |
|
175 | - |
|
176 | - $io->setCookie( |
|
177 | - $name, |
|
178 | - $value['value'], |
|
179 | - $expireDate, |
|
180 | - $container->getServer()->getWebRoot(), |
|
181 | - null, |
|
182 | - $container->getServer()->getRequest()->getServerProtocol() === 'https', |
|
183 | - true, |
|
184 | - $sameSite |
|
185 | - ); |
|
186 | - } |
|
187 | - |
|
188 | - /* |
|
52 | + /** @var string[] */ |
|
53 | + private static $nameSpaceCache = []; |
|
54 | + |
|
55 | + /** |
|
56 | + * Turns an app id into a namespace by either reading the appinfo.xml's |
|
57 | + * namespace tag or uppercasing the appid's first letter |
|
58 | + * @param string $appId the app id |
|
59 | + * @param string $topNamespace the namespace which should be prepended to |
|
60 | + * the transformed app id, defaults to OCA\ |
|
61 | + * @return string the starting namespace for the app |
|
62 | + */ |
|
63 | + public static function buildAppNamespace(string $appId, string $topNamespace = 'OCA\\'): string { |
|
64 | + // Hit the cache! |
|
65 | + if (isset(self::$nameSpaceCache[$appId])) { |
|
66 | + return $topNamespace . self::$nameSpaceCache[$appId]; |
|
67 | + } |
|
68 | + |
|
69 | + $appInfo = \OC_App::getAppInfo($appId); |
|
70 | + if (isset($appInfo['namespace'])) { |
|
71 | + self::$nameSpaceCache[$appId] = trim($appInfo['namespace']); |
|
72 | + } else { |
|
73 | + if ($appId !== 'spreed') { |
|
74 | + // if the tag is not found, fall back to uppercasing the first letter |
|
75 | + self::$nameSpaceCache[$appId] = ucfirst($appId); |
|
76 | + } else { |
|
77 | + // For the Talk app (appid spreed) the above fallback doesn't work. |
|
78 | + // This leads to a problem when trying to install it freshly, |
|
79 | + // because the apps namespace is already registered before the |
|
80 | + // app is downloaded from the appstore, because of the hackish |
|
81 | + // global route index.php/call/{token} which is registered via |
|
82 | + // the core/routes.php so it does not have the app namespace. |
|
83 | + // @ref https://github.com/nextcloud/server/pull/19433 |
|
84 | + self::$nameSpaceCache[$appId] = 'Talk'; |
|
85 | + } |
|
86 | + } |
|
87 | + |
|
88 | + return $topNamespace . self::$nameSpaceCache[$appId]; |
|
89 | + } |
|
90 | + |
|
91 | + public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string { |
|
92 | + if (strpos($className, $topNamespace) !== 0) { |
|
93 | + return null; |
|
94 | + } |
|
95 | + |
|
96 | + foreach (self::$nameSpaceCache as $appId => $namespace) { |
|
97 | + if (strpos($className, $topNamespace . $namespace . '\\') === 0) { |
|
98 | + return $appId; |
|
99 | + } |
|
100 | + } |
|
101 | + |
|
102 | + return null; |
|
103 | + } |
|
104 | + |
|
105 | + |
|
106 | + /** |
|
107 | + * Shortcut for calling a controller method and printing the result |
|
108 | + * |
|
109 | + * @param string $controllerName the name of the controller under which it is |
|
110 | + * stored in the DI container |
|
111 | + * @param string $methodName the method that you want to call |
|
112 | + * @param DIContainer $container an instance of a pimple container. |
|
113 | + * @param array $urlParams list of URL parameters (optional) |
|
114 | + * @throws HintException |
|
115 | + */ |
|
116 | + public static function main(string $controllerName, string $methodName, DIContainer $container, array $urlParams = null) { |
|
117 | + if (!is_null($urlParams)) { |
|
118 | + /** @var Request $request */ |
|
119 | + $request = $container->query(IRequest::class); |
|
120 | + $request->setUrlParameters($urlParams); |
|
121 | + } elseif (isset($container['urlParams']) && !is_null($container['urlParams'])) { |
|
122 | + /** @var Request $request */ |
|
123 | + $request = $container->query(IRequest::class); |
|
124 | + $request->setUrlParameters($container['urlParams']); |
|
125 | + } |
|
126 | + $appName = $container['AppName']; |
|
127 | + |
|
128 | + // first try $controllerName then go for \OCA\AppName\Controller\$controllerName |
|
129 | + try { |
|
130 | + $controller = $container->query($controllerName); |
|
131 | + } catch (QueryException $e) { |
|
132 | + if (strpos($controllerName, '\\Controller\\') !== false) { |
|
133 | + // This is from a global registered app route that is not enabled. |
|
134 | + [/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3); |
|
135 | + throw new HintException('App ' . strtolower($app) . ' is not enabled'); |
|
136 | + } |
|
137 | + |
|
138 | + if ($appName === 'core') { |
|
139 | + $appNameSpace = 'OC\\Core'; |
|
140 | + } else { |
|
141 | + $appNameSpace = self::buildAppNamespace($appName); |
|
142 | + } |
|
143 | + $controllerName = $appNameSpace . '\\Controller\\' . $controllerName; |
|
144 | + $controller = $container->query($controllerName); |
|
145 | + } |
|
146 | + |
|
147 | + // initialize the dispatcher and run all the middleware before the controller |
|
148 | + /** @var Dispatcher $dispatcher */ |
|
149 | + $dispatcher = $container['Dispatcher']; |
|
150 | + |
|
151 | + [ |
|
152 | + $httpHeaders, |
|
153 | + $responseHeaders, |
|
154 | + $responseCookies, |
|
155 | + $output, |
|
156 | + $response |
|
157 | + ] = $dispatcher->dispatch($controller, $methodName); |
|
158 | + |
|
159 | + $io = $container[IOutput::class]; |
|
160 | + |
|
161 | + if (!is_null($httpHeaders)) { |
|
162 | + $io->setHeader($httpHeaders); |
|
163 | + } |
|
164 | + |
|
165 | + foreach ($responseHeaders as $name => $value) { |
|
166 | + $io->setHeader($name . ': ' . $value); |
|
167 | + } |
|
168 | + |
|
169 | + foreach ($responseCookies as $name => $value) { |
|
170 | + $expireDate = null; |
|
171 | + if ($value['expireDate'] instanceof \DateTime) { |
|
172 | + $expireDate = $value['expireDate']->getTimestamp(); |
|
173 | + } |
|
174 | + $sameSite = $value['sameSite'] ?? 'Lax'; |
|
175 | + |
|
176 | + $io->setCookie( |
|
177 | + $name, |
|
178 | + $value['value'], |
|
179 | + $expireDate, |
|
180 | + $container->getServer()->getWebRoot(), |
|
181 | + null, |
|
182 | + $container->getServer()->getRequest()->getServerProtocol() === 'https', |
|
183 | + true, |
|
184 | + $sameSite |
|
185 | + ); |
|
186 | + } |
|
187 | + |
|
188 | + /* |
|
189 | 189 | * Status 204 does not have a body and no Content Length |
190 | 190 | * Status 304 does not have a body and does not need a Content Length |
191 | 191 | * https://tools.ietf.org/html/rfc7230#section-3.3 |
192 | 192 | * https://tools.ietf.org/html/rfc7230#section-3.3.2 |
193 | 193 | */ |
194 | - $emptyResponse = false; |
|
195 | - if (preg_match('/^HTTP\/\d\.\d (\d{3}) .*$/', $httpHeaders, $matches)) { |
|
196 | - $status = (int)$matches[1]; |
|
197 | - if ($status === Http::STATUS_NO_CONTENT || $status === Http::STATUS_NOT_MODIFIED) { |
|
198 | - $emptyResponse = true; |
|
199 | - } |
|
200 | - } |
|
201 | - |
|
202 | - if (!$emptyResponse) { |
|
203 | - if ($response instanceof ICallbackResponse) { |
|
204 | - $response->callback($io); |
|
205 | - } elseif (!is_null($output)) { |
|
206 | - $io->setHeader('Content-Length: ' . strlen($output)); |
|
207 | - $io->setOutput($output); |
|
208 | - } |
|
209 | - } |
|
210 | - } |
|
211 | - |
|
212 | - /** |
|
213 | - * Shortcut for calling a controller method and printing the result. |
|
214 | - * Similar to App:main except that no headers will be sent. |
|
215 | - * This should be used for example when registering sections via |
|
216 | - * \OC\AppFramework\Core\API::registerAdmin() |
|
217 | - * |
|
218 | - * @param string $controllerName the name of the controller under which it is |
|
219 | - * stored in the DI container |
|
220 | - * @param string $methodName the method that you want to call |
|
221 | - * @param array $urlParams an array with variables extracted from the routes |
|
222 | - * @param DIContainer $container an instance of a pimple container. |
|
223 | - */ |
|
224 | - public static function part(string $controllerName, string $methodName, array $urlParams, |
|
225 | - DIContainer $container) { |
|
226 | - $container['urlParams'] = $urlParams; |
|
227 | - $controller = $container[$controllerName]; |
|
228 | - |
|
229 | - $dispatcher = $container['Dispatcher']; |
|
230 | - |
|
231 | - [, , $output] = $dispatcher->dispatch($controller, $methodName); |
|
232 | - return $output; |
|
233 | - } |
|
194 | + $emptyResponse = false; |
|
195 | + if (preg_match('/^HTTP\/\d\.\d (\d{3}) .*$/', $httpHeaders, $matches)) { |
|
196 | + $status = (int)$matches[1]; |
|
197 | + if ($status === Http::STATUS_NO_CONTENT || $status === Http::STATUS_NOT_MODIFIED) { |
|
198 | + $emptyResponse = true; |
|
199 | + } |
|
200 | + } |
|
201 | + |
|
202 | + if (!$emptyResponse) { |
|
203 | + if ($response instanceof ICallbackResponse) { |
|
204 | + $response->callback($io); |
|
205 | + } elseif (!is_null($output)) { |
|
206 | + $io->setHeader('Content-Length: ' . strlen($output)); |
|
207 | + $io->setOutput($output); |
|
208 | + } |
|
209 | + } |
|
210 | + } |
|
211 | + |
|
212 | + /** |
|
213 | + * Shortcut for calling a controller method and printing the result. |
|
214 | + * Similar to App:main except that no headers will be sent. |
|
215 | + * This should be used for example when registering sections via |
|
216 | + * \OC\AppFramework\Core\API::registerAdmin() |
|
217 | + * |
|
218 | + * @param string $controllerName the name of the controller under which it is |
|
219 | + * stored in the DI container |
|
220 | + * @param string $methodName the method that you want to call |
|
221 | + * @param array $urlParams an array with variables extracted from the routes |
|
222 | + * @param DIContainer $container an instance of a pimple container. |
|
223 | + */ |
|
224 | + public static function part(string $controllerName, string $methodName, array $urlParams, |
|
225 | + DIContainer $container) { |
|
226 | + $container['urlParams'] = $urlParams; |
|
227 | + $controller = $container[$controllerName]; |
|
228 | + |
|
229 | + $dispatcher = $container['Dispatcher']; |
|
230 | + |
|
231 | + [, , $output] = $dispatcher->dispatch($controller, $methodName); |
|
232 | + return $output; |
|
233 | + } |
|
234 | 234 | } |
@@ -35,177 +35,177 @@ |
||
35 | 35 | use OCP\HintException; |
36 | 36 | |
37 | 37 | class ExceptionSerializer { |
38 | - public const methodsWithSensitiveParameters = [ |
|
39 | - // Session/User |
|
40 | - 'completeLogin', |
|
41 | - 'login', |
|
42 | - 'checkPassword', |
|
43 | - 'checkPasswordNoLogging', |
|
44 | - 'loginWithPassword', |
|
45 | - 'updatePrivateKeyPassword', |
|
46 | - 'validateUserPass', |
|
47 | - 'loginWithToken', |
|
48 | - '{closure}', |
|
49 | - 'createSessionToken', |
|
50 | - |
|
51 | - // Provisioning |
|
52 | - 'addUser', |
|
53 | - |
|
54 | - // TokenProvider |
|
55 | - 'getToken', |
|
56 | - 'isTokenPassword', |
|
57 | - 'getPassword', |
|
58 | - 'decryptPassword', |
|
59 | - 'logClientIn', |
|
60 | - 'generateToken', |
|
61 | - 'validateToken', |
|
62 | - |
|
63 | - // TwoFactorAuth |
|
64 | - 'solveChallenge', |
|
65 | - 'verifyChallenge', |
|
66 | - |
|
67 | - // ICrypto |
|
68 | - 'calculateHMAC', |
|
69 | - 'encrypt', |
|
70 | - 'decrypt', |
|
71 | - |
|
72 | - // LoginController |
|
73 | - 'tryLogin', |
|
74 | - 'confirmPassword', |
|
75 | - |
|
76 | - // LDAP |
|
77 | - 'bind', |
|
78 | - 'areCredentialsValid', |
|
79 | - 'invokeLDAPMethod', |
|
80 | - |
|
81 | - // Encryption |
|
82 | - 'storeKeyPair', |
|
83 | - 'setupUser', |
|
84 | - 'checkSignature', |
|
85 | - |
|
86 | - // files_external: OCA\Files_External\MountConfig |
|
87 | - 'getBackendStatus', |
|
88 | - |
|
89 | - // files_external: UserStoragesController |
|
90 | - 'update', |
|
91 | - |
|
92 | - // Preview providers, don't log big data strings |
|
93 | - 'imagecreatefromstring', |
|
94 | - ]; |
|
95 | - |
|
96 | - /** @var SystemConfig */ |
|
97 | - private $systemConfig; |
|
98 | - |
|
99 | - public function __construct(SystemConfig $systemConfig) { |
|
100 | - $this->systemConfig = $systemConfig; |
|
101 | - } |
|
102 | - |
|
103 | - public const methodsWithSensitiveParametersByClass = [ |
|
104 | - SetupController::class => [ |
|
105 | - 'run', |
|
106 | - 'display', |
|
107 | - 'loadAutoConfig', |
|
108 | - ], |
|
109 | - Setup::class => [ |
|
110 | - 'install' |
|
111 | - ], |
|
112 | - Key::class => [ |
|
113 | - '__construct' |
|
114 | - ], |
|
115 | - ]; |
|
116 | - |
|
117 | - private function editTrace(array &$sensitiveValues, array $traceLine): array { |
|
118 | - if (isset($traceLine['args'])) { |
|
119 | - $sensitiveValues = array_merge($sensitiveValues, $traceLine['args']); |
|
120 | - } |
|
121 | - $traceLine['args'] = ['*** sensitive parameters replaced ***']; |
|
122 | - return $traceLine; |
|
123 | - } |
|
124 | - |
|
125 | - private function filterTrace(array $trace) { |
|
126 | - $sensitiveValues = []; |
|
127 | - $trace = array_map(function (array $traceLine) use (&$sensitiveValues) { |
|
128 | - $className = $traceLine['class'] ?? ''; |
|
129 | - if ($className && isset(self::methodsWithSensitiveParametersByClass[$className]) |
|
130 | - && in_array($traceLine['function'], self::methodsWithSensitiveParametersByClass[$className], true)) { |
|
131 | - return $this->editTrace($sensitiveValues, $traceLine); |
|
132 | - } |
|
133 | - foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) { |
|
134 | - if (strpos($traceLine['function'], $sensitiveMethod) !== false) { |
|
135 | - return $this->editTrace($sensitiveValues, $traceLine); |
|
136 | - } |
|
137 | - } |
|
138 | - return $traceLine; |
|
139 | - }, $trace); |
|
140 | - return array_map(function (array $traceLine) use ($sensitiveValues) { |
|
141 | - if (isset($traceLine['args'])) { |
|
142 | - $traceLine['args'] = $this->removeValuesFromArgs($traceLine['args'], $sensitiveValues); |
|
143 | - } |
|
144 | - return $traceLine; |
|
145 | - }, $trace); |
|
146 | - } |
|
147 | - |
|
148 | - private function removeValuesFromArgs($args, $values) { |
|
149 | - foreach ($args as &$arg) { |
|
150 | - if (in_array($arg, $values, true)) { |
|
151 | - $arg = '*** sensitive parameter replaced ***'; |
|
152 | - } elseif (is_array($arg)) { |
|
153 | - $arg = $this->removeValuesFromArgs($arg, $values); |
|
154 | - } |
|
155 | - } |
|
156 | - return $args; |
|
157 | - } |
|
158 | - |
|
159 | - private function encodeTrace($trace) { |
|
160 | - $filteredTrace = $this->filterTrace($trace); |
|
161 | - return array_map(function (array $line) { |
|
162 | - if (isset($line['args'])) { |
|
163 | - $line['args'] = array_map([$this, 'encodeArg'], $line['args']); |
|
164 | - } |
|
165 | - return $line; |
|
166 | - }, $filteredTrace); |
|
167 | - } |
|
168 | - |
|
169 | - private function encodeArg($arg) { |
|
170 | - if (is_object($arg)) { |
|
171 | - $data = get_object_vars($arg); |
|
172 | - $data['__class__'] = get_class($arg); |
|
173 | - return array_map([$this, 'encodeArg'], $data); |
|
174 | - } |
|
175 | - |
|
176 | - if (is_array($arg)) { |
|
177 | - // Only log the first 5 elements of an array unless we are on debug |
|
178 | - if ((int)$this->systemConfig->getValue('loglevel', 2) !== 0) { |
|
179 | - $elemCount = count($arg); |
|
180 | - if ($elemCount > 5) { |
|
181 | - $arg = array_slice($arg, 0, 5); |
|
182 | - $arg[] = 'And ' . ($elemCount - 5) . ' more entries, set log level to debug to see all entries'; |
|
183 | - } |
|
184 | - } |
|
185 | - return array_map([$this, 'encodeArg'], $arg); |
|
186 | - } |
|
187 | - |
|
188 | - return $arg; |
|
189 | - } |
|
190 | - |
|
191 | - public function serializeException(\Throwable $exception) { |
|
192 | - $data = [ |
|
193 | - 'Exception' => get_class($exception), |
|
194 | - 'Message' => $exception->getMessage(), |
|
195 | - 'Code' => $exception->getCode(), |
|
196 | - 'Trace' => $this->encodeTrace($exception->getTrace()), |
|
197 | - 'File' => $exception->getFile(), |
|
198 | - 'Line' => $exception->getLine(), |
|
199 | - ]; |
|
200 | - |
|
201 | - if ($exception instanceof HintException) { |
|
202 | - $data['Hint'] = $exception->getHint(); |
|
203 | - } |
|
204 | - |
|
205 | - if ($exception->getPrevious()) { |
|
206 | - $data['Previous'] = $this->serializeException($exception->getPrevious()); |
|
207 | - } |
|
208 | - |
|
209 | - return $data; |
|
210 | - } |
|
38 | + public const methodsWithSensitiveParameters = [ |
|
39 | + // Session/User |
|
40 | + 'completeLogin', |
|
41 | + 'login', |
|
42 | + 'checkPassword', |
|
43 | + 'checkPasswordNoLogging', |
|
44 | + 'loginWithPassword', |
|
45 | + 'updatePrivateKeyPassword', |
|
46 | + 'validateUserPass', |
|
47 | + 'loginWithToken', |
|
48 | + '{closure}', |
|
49 | + 'createSessionToken', |
|
50 | + |
|
51 | + // Provisioning |
|
52 | + 'addUser', |
|
53 | + |
|
54 | + // TokenProvider |
|
55 | + 'getToken', |
|
56 | + 'isTokenPassword', |
|
57 | + 'getPassword', |
|
58 | + 'decryptPassword', |
|
59 | + 'logClientIn', |
|
60 | + 'generateToken', |
|
61 | + 'validateToken', |
|
62 | + |
|
63 | + // TwoFactorAuth |
|
64 | + 'solveChallenge', |
|
65 | + 'verifyChallenge', |
|
66 | + |
|
67 | + // ICrypto |
|
68 | + 'calculateHMAC', |
|
69 | + 'encrypt', |
|
70 | + 'decrypt', |
|
71 | + |
|
72 | + // LoginController |
|
73 | + 'tryLogin', |
|
74 | + 'confirmPassword', |
|
75 | + |
|
76 | + // LDAP |
|
77 | + 'bind', |
|
78 | + 'areCredentialsValid', |
|
79 | + 'invokeLDAPMethod', |
|
80 | + |
|
81 | + // Encryption |
|
82 | + 'storeKeyPair', |
|
83 | + 'setupUser', |
|
84 | + 'checkSignature', |
|
85 | + |
|
86 | + // files_external: OCA\Files_External\MountConfig |
|
87 | + 'getBackendStatus', |
|
88 | + |
|
89 | + // files_external: UserStoragesController |
|
90 | + 'update', |
|
91 | + |
|
92 | + // Preview providers, don't log big data strings |
|
93 | + 'imagecreatefromstring', |
|
94 | + ]; |
|
95 | + |
|
96 | + /** @var SystemConfig */ |
|
97 | + private $systemConfig; |
|
98 | + |
|
99 | + public function __construct(SystemConfig $systemConfig) { |
|
100 | + $this->systemConfig = $systemConfig; |
|
101 | + } |
|
102 | + |
|
103 | + public const methodsWithSensitiveParametersByClass = [ |
|
104 | + SetupController::class => [ |
|
105 | + 'run', |
|
106 | + 'display', |
|
107 | + 'loadAutoConfig', |
|
108 | + ], |
|
109 | + Setup::class => [ |
|
110 | + 'install' |
|
111 | + ], |
|
112 | + Key::class => [ |
|
113 | + '__construct' |
|
114 | + ], |
|
115 | + ]; |
|
116 | + |
|
117 | + private function editTrace(array &$sensitiveValues, array $traceLine): array { |
|
118 | + if (isset($traceLine['args'])) { |
|
119 | + $sensitiveValues = array_merge($sensitiveValues, $traceLine['args']); |
|
120 | + } |
|
121 | + $traceLine['args'] = ['*** sensitive parameters replaced ***']; |
|
122 | + return $traceLine; |
|
123 | + } |
|
124 | + |
|
125 | + private function filterTrace(array $trace) { |
|
126 | + $sensitiveValues = []; |
|
127 | + $trace = array_map(function (array $traceLine) use (&$sensitiveValues) { |
|
128 | + $className = $traceLine['class'] ?? ''; |
|
129 | + if ($className && isset(self::methodsWithSensitiveParametersByClass[$className]) |
|
130 | + && in_array($traceLine['function'], self::methodsWithSensitiveParametersByClass[$className], true)) { |
|
131 | + return $this->editTrace($sensitiveValues, $traceLine); |
|
132 | + } |
|
133 | + foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) { |
|
134 | + if (strpos($traceLine['function'], $sensitiveMethod) !== false) { |
|
135 | + return $this->editTrace($sensitiveValues, $traceLine); |
|
136 | + } |
|
137 | + } |
|
138 | + return $traceLine; |
|
139 | + }, $trace); |
|
140 | + return array_map(function (array $traceLine) use ($sensitiveValues) { |
|
141 | + if (isset($traceLine['args'])) { |
|
142 | + $traceLine['args'] = $this->removeValuesFromArgs($traceLine['args'], $sensitiveValues); |
|
143 | + } |
|
144 | + return $traceLine; |
|
145 | + }, $trace); |
|
146 | + } |
|
147 | + |
|
148 | + private function removeValuesFromArgs($args, $values) { |
|
149 | + foreach ($args as &$arg) { |
|
150 | + if (in_array($arg, $values, true)) { |
|
151 | + $arg = '*** sensitive parameter replaced ***'; |
|
152 | + } elseif (is_array($arg)) { |
|
153 | + $arg = $this->removeValuesFromArgs($arg, $values); |
|
154 | + } |
|
155 | + } |
|
156 | + return $args; |
|
157 | + } |
|
158 | + |
|
159 | + private function encodeTrace($trace) { |
|
160 | + $filteredTrace = $this->filterTrace($trace); |
|
161 | + return array_map(function (array $line) { |
|
162 | + if (isset($line['args'])) { |
|
163 | + $line['args'] = array_map([$this, 'encodeArg'], $line['args']); |
|
164 | + } |
|
165 | + return $line; |
|
166 | + }, $filteredTrace); |
|
167 | + } |
|
168 | + |
|
169 | + private function encodeArg($arg) { |
|
170 | + if (is_object($arg)) { |
|
171 | + $data = get_object_vars($arg); |
|
172 | + $data['__class__'] = get_class($arg); |
|
173 | + return array_map([$this, 'encodeArg'], $data); |
|
174 | + } |
|
175 | + |
|
176 | + if (is_array($arg)) { |
|
177 | + // Only log the first 5 elements of an array unless we are on debug |
|
178 | + if ((int)$this->systemConfig->getValue('loglevel', 2) !== 0) { |
|
179 | + $elemCount = count($arg); |
|
180 | + if ($elemCount > 5) { |
|
181 | + $arg = array_slice($arg, 0, 5); |
|
182 | + $arg[] = 'And ' . ($elemCount - 5) . ' more entries, set log level to debug to see all entries'; |
|
183 | + } |
|
184 | + } |
|
185 | + return array_map([$this, 'encodeArg'], $arg); |
|
186 | + } |
|
187 | + |
|
188 | + return $arg; |
|
189 | + } |
|
190 | + |
|
191 | + public function serializeException(\Throwable $exception) { |
|
192 | + $data = [ |
|
193 | + 'Exception' => get_class($exception), |
|
194 | + 'Message' => $exception->getMessage(), |
|
195 | + 'Code' => $exception->getCode(), |
|
196 | + 'Trace' => $this->encodeTrace($exception->getTrace()), |
|
197 | + 'File' => $exception->getFile(), |
|
198 | + 'Line' => $exception->getLine(), |
|
199 | + ]; |
|
200 | + |
|
201 | + if ($exception instanceof HintException) { |
|
202 | + $data['Hint'] = $exception->getHint(); |
|
203 | + } |
|
204 | + |
|
205 | + if ($exception->getPrevious()) { |
|
206 | + $data['Previous'] = $this->serializeException($exception->getPrevious()); |
|
207 | + } |
|
208 | + |
|
209 | + return $data; |
|
210 | + } |
|
211 | 211 | } |
@@ -64,538 +64,538 @@ |
||
64 | 64 | use Psr\Log\LoggerInterface; |
65 | 65 | |
66 | 66 | class Setup { |
67 | - /** @var SystemConfig */ |
|
68 | - protected $config; |
|
69 | - /** @var IniGetWrapper */ |
|
70 | - protected $iniWrapper; |
|
71 | - /** @var IL10N */ |
|
72 | - protected $l10n; |
|
73 | - /** @var Defaults */ |
|
74 | - protected $defaults; |
|
75 | - /** @var LoggerInterface */ |
|
76 | - protected $logger; |
|
77 | - /** @var ISecureRandom */ |
|
78 | - protected $random; |
|
79 | - /** @var Installer */ |
|
80 | - protected $installer; |
|
81 | - |
|
82 | - public function __construct( |
|
83 | - SystemConfig $config, |
|
84 | - IniGetWrapper $iniWrapper, |
|
85 | - IL10N $l10n, |
|
86 | - Defaults $defaults, |
|
87 | - LoggerInterface $logger, |
|
88 | - ISecureRandom $random, |
|
89 | - Installer $installer |
|
90 | - ) { |
|
91 | - $this->config = $config; |
|
92 | - $this->iniWrapper = $iniWrapper; |
|
93 | - $this->l10n = $l10n; |
|
94 | - $this->defaults = $defaults; |
|
95 | - $this->logger = $logger; |
|
96 | - $this->random = $random; |
|
97 | - $this->installer = $installer; |
|
98 | - } |
|
99 | - |
|
100 | - protected static $dbSetupClasses = [ |
|
101 | - 'mysql' => \OC\Setup\MySQL::class, |
|
102 | - 'pgsql' => \OC\Setup\PostgreSQL::class, |
|
103 | - 'oci' => \OC\Setup\OCI::class, |
|
104 | - 'sqlite' => \OC\Setup\Sqlite::class, |
|
105 | - 'sqlite3' => \OC\Setup\Sqlite::class, |
|
106 | - ]; |
|
107 | - |
|
108 | - /** |
|
109 | - * Wrapper around the "class_exists" PHP function to be able to mock it |
|
110 | - * |
|
111 | - * @param string $name |
|
112 | - * @return bool |
|
113 | - */ |
|
114 | - protected function class_exists($name) { |
|
115 | - return class_exists($name); |
|
116 | - } |
|
117 | - |
|
118 | - /** |
|
119 | - * Wrapper around the "is_callable" PHP function to be able to mock it |
|
120 | - * |
|
121 | - * @param string $name |
|
122 | - * @return bool |
|
123 | - */ |
|
124 | - protected function is_callable($name) { |
|
125 | - return is_callable($name); |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * Wrapper around \PDO::getAvailableDrivers |
|
130 | - * |
|
131 | - * @return array |
|
132 | - */ |
|
133 | - protected function getAvailableDbDriversForPdo() { |
|
134 | - return \PDO::getAvailableDrivers(); |
|
135 | - } |
|
136 | - |
|
137 | - /** |
|
138 | - * Get the available and supported databases of this instance |
|
139 | - * |
|
140 | - * @param bool $allowAllDatabases |
|
141 | - * @return array |
|
142 | - * @throws Exception |
|
143 | - */ |
|
144 | - public function getSupportedDatabases($allowAllDatabases = false) { |
|
145 | - $availableDatabases = [ |
|
146 | - 'sqlite' => [ |
|
147 | - 'type' => 'pdo', |
|
148 | - 'call' => 'sqlite', |
|
149 | - 'name' => 'SQLite', |
|
150 | - ], |
|
151 | - 'mysql' => [ |
|
152 | - 'type' => 'pdo', |
|
153 | - 'call' => 'mysql', |
|
154 | - 'name' => 'MySQL/MariaDB', |
|
155 | - ], |
|
156 | - 'pgsql' => [ |
|
157 | - 'type' => 'pdo', |
|
158 | - 'call' => 'pgsql', |
|
159 | - 'name' => 'PostgreSQL', |
|
160 | - ], |
|
161 | - 'oci' => [ |
|
162 | - 'type' => 'function', |
|
163 | - 'call' => 'oci_connect', |
|
164 | - 'name' => 'Oracle', |
|
165 | - ], |
|
166 | - ]; |
|
167 | - if ($allowAllDatabases) { |
|
168 | - $configuredDatabases = array_keys($availableDatabases); |
|
169 | - } else { |
|
170 | - $configuredDatabases = $this->config->getValue('supportedDatabases', |
|
171 | - ['sqlite', 'mysql', 'pgsql']); |
|
172 | - } |
|
173 | - if (!is_array($configuredDatabases)) { |
|
174 | - throw new Exception('Supported databases are not properly configured.'); |
|
175 | - } |
|
176 | - |
|
177 | - $supportedDatabases = []; |
|
178 | - |
|
179 | - foreach ($configuredDatabases as $database) { |
|
180 | - if (array_key_exists($database, $availableDatabases)) { |
|
181 | - $working = false; |
|
182 | - $type = $availableDatabases[$database]['type']; |
|
183 | - $call = $availableDatabases[$database]['call']; |
|
184 | - |
|
185 | - if ($type === 'function') { |
|
186 | - $working = $this->is_callable($call); |
|
187 | - } elseif ($type === 'pdo') { |
|
188 | - $working = in_array($call, $this->getAvailableDbDriversForPdo(), true); |
|
189 | - } |
|
190 | - if ($working) { |
|
191 | - $supportedDatabases[$database] = $availableDatabases[$database]['name']; |
|
192 | - } |
|
193 | - } |
|
194 | - } |
|
195 | - |
|
196 | - return $supportedDatabases; |
|
197 | - } |
|
198 | - |
|
199 | - /** |
|
200 | - * Gathers system information like database type and does |
|
201 | - * a few system checks. |
|
202 | - * |
|
203 | - * @return array of system info, including an "errors" value |
|
204 | - * in case of errors/warnings |
|
205 | - */ |
|
206 | - public function getSystemInfo($allowAllDatabases = false) { |
|
207 | - $databases = $this->getSupportedDatabases($allowAllDatabases); |
|
208 | - |
|
209 | - $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data'); |
|
210 | - |
|
211 | - $errors = []; |
|
212 | - |
|
213 | - // Create data directory to test whether the .htaccess works |
|
214 | - // Notice that this is not necessarily the same data directory as the one |
|
215 | - // that will effectively be used. |
|
216 | - if (!file_exists($dataDir)) { |
|
217 | - @mkdir($dataDir); |
|
218 | - } |
|
219 | - $htAccessWorking = true; |
|
220 | - if (is_dir($dataDir) && is_writable($dataDir)) { |
|
221 | - // Protect data directory here, so we can test if the protection is working |
|
222 | - self::protectDataDirectory(); |
|
223 | - |
|
224 | - try { |
|
225 | - $util = new \OC_Util(); |
|
226 | - $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig()); |
|
227 | - } catch (\OCP\HintException $e) { |
|
228 | - $errors[] = [ |
|
229 | - 'error' => $e->getMessage(), |
|
230 | - 'exception' => $e, |
|
231 | - 'hint' => $e->getHint(), |
|
232 | - ]; |
|
233 | - $htAccessWorking = false; |
|
234 | - } |
|
235 | - } |
|
236 | - |
|
237 | - if (\OC_Util::runningOnMac()) { |
|
238 | - $errors[] = [ |
|
239 | - 'error' => $this->l10n->t( |
|
240 | - 'Mac OS X is not supported and %s will not work properly on this platform. ' . |
|
241 | - 'Use it at your own risk! ', |
|
242 | - [$this->defaults->getProductName()] |
|
243 | - ), |
|
244 | - 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'), |
|
245 | - ]; |
|
246 | - } |
|
247 | - |
|
248 | - if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) { |
|
249 | - $errors[] = [ |
|
250 | - 'error' => $this->l10n->t( |
|
251 | - 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' . |
|
252 | - 'This will lead to problems with files over 4 GB and is highly discouraged.', |
|
253 | - [$this->defaults->getProductName()] |
|
254 | - ), |
|
255 | - 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'), |
|
256 | - ]; |
|
257 | - } |
|
258 | - |
|
259 | - return [ |
|
260 | - 'hasSQLite' => isset($databases['sqlite']), |
|
261 | - 'hasMySQL' => isset($databases['mysql']), |
|
262 | - 'hasPostgreSQL' => isset($databases['pgsql']), |
|
263 | - 'hasOracle' => isset($databases['oci']), |
|
264 | - 'databases' => $databases, |
|
265 | - 'directory' => $dataDir, |
|
266 | - 'htaccessWorking' => $htAccessWorking, |
|
267 | - 'errors' => $errors, |
|
268 | - ]; |
|
269 | - } |
|
270 | - |
|
271 | - /** |
|
272 | - * @param $options |
|
273 | - * @return array |
|
274 | - */ |
|
275 | - public function install($options) { |
|
276 | - $l = $this->l10n; |
|
277 | - |
|
278 | - $error = []; |
|
279 | - $dbType = $options['dbtype']; |
|
280 | - |
|
281 | - if (empty($options['adminlogin'])) { |
|
282 | - $error[] = $l->t('Set an admin username.'); |
|
283 | - } |
|
284 | - if (empty($options['adminpass'])) { |
|
285 | - $error[] = $l->t('Set an admin password.'); |
|
286 | - } |
|
287 | - if (empty($options['directory'])) { |
|
288 | - $options['directory'] = \OC::$SERVERROOT . "/data"; |
|
289 | - } |
|
290 | - |
|
291 | - if (!isset(self::$dbSetupClasses[$dbType])) { |
|
292 | - $dbType = 'sqlite'; |
|
293 | - } |
|
294 | - |
|
295 | - $username = htmlspecialchars_decode($options['adminlogin']); |
|
296 | - $password = htmlspecialchars_decode($options['adminpass']); |
|
297 | - $dataDir = htmlspecialchars_decode($options['directory']); |
|
298 | - |
|
299 | - $class = self::$dbSetupClasses[$dbType]; |
|
300 | - /** @var \OC\Setup\AbstractDatabase $dbSetup */ |
|
301 | - $dbSetup = new $class($l, $this->config, $this->logger, $this->random); |
|
302 | - $error = array_merge($error, $dbSetup->validate($options)); |
|
303 | - |
|
304 | - // validate the data directory |
|
305 | - if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) { |
|
306 | - $error[] = $l->t("Cannot create or write into the data directory %s", [$dataDir]); |
|
307 | - } |
|
308 | - |
|
309 | - if (!empty($error)) { |
|
310 | - return $error; |
|
311 | - } |
|
312 | - |
|
313 | - $request = \OC::$server->getRequest(); |
|
314 | - |
|
315 | - //no errors, good |
|
316 | - if (isset($options['trusted_domains']) |
|
317 | - && is_array($options['trusted_domains'])) { |
|
318 | - $trustedDomains = $options['trusted_domains']; |
|
319 | - } else { |
|
320 | - $trustedDomains = [$request->getInsecureServerHost()]; |
|
321 | - } |
|
322 | - |
|
323 | - //use sqlite3 when available, otherwise sqlite2 will be used. |
|
324 | - if ($dbType === 'sqlite' && class_exists('SQLite3')) { |
|
325 | - $dbType = 'sqlite3'; |
|
326 | - } |
|
327 | - |
|
328 | - //generate a random salt that is used to salt the local user passwords |
|
329 | - $salt = $this->random->generate(30); |
|
330 | - // generate a secret |
|
331 | - $secret = $this->random->generate(48); |
|
332 | - |
|
333 | - //write the config file |
|
334 | - $newConfigValues = [ |
|
335 | - 'passwordsalt' => $salt, |
|
336 | - 'secret' => $secret, |
|
337 | - 'trusted_domains' => $trustedDomains, |
|
338 | - 'datadirectory' => $dataDir, |
|
339 | - 'dbtype' => $dbType, |
|
340 | - 'version' => implode('.', \OCP\Util::getVersion()), |
|
341 | - ]; |
|
342 | - |
|
343 | - if ($this->config->getValue('overwrite.cli.url', null) === null) { |
|
344 | - $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT; |
|
345 | - } |
|
346 | - |
|
347 | - $this->config->setValues($newConfigValues); |
|
348 | - |
|
349 | - $dbSetup->initialize($options); |
|
350 | - try { |
|
351 | - $dbSetup->setupDatabase($username); |
|
352 | - } catch (\OC\DatabaseSetupException $e) { |
|
353 | - $error[] = [ |
|
354 | - 'error' => $e->getMessage(), |
|
355 | - 'exception' => $e, |
|
356 | - 'hint' => $e->getHint(), |
|
357 | - ]; |
|
358 | - return $error; |
|
359 | - } catch (Exception $e) { |
|
360 | - $error[] = [ |
|
361 | - 'error' => 'Error while trying to create admin user: ' . $e->getMessage(), |
|
362 | - 'exception' => $e, |
|
363 | - 'hint' => '', |
|
364 | - ]; |
|
365 | - return $error; |
|
366 | - } |
|
367 | - try { |
|
368 | - // apply necessary migrations |
|
369 | - $dbSetup->runMigrations(); |
|
370 | - } catch (Exception $e) { |
|
371 | - $error[] = [ |
|
372 | - 'error' => 'Error while trying to initialise the database: ' . $e->getMessage(), |
|
373 | - 'exception' => $e, |
|
374 | - 'hint' => '', |
|
375 | - ]; |
|
376 | - return $error; |
|
377 | - } |
|
378 | - |
|
379 | - //create the user and group |
|
380 | - $user = null; |
|
381 | - try { |
|
382 | - $user = \OC::$server->getUserManager()->createUser($username, $password); |
|
383 | - if (!$user) { |
|
384 | - $error[] = "User <$username> could not be created."; |
|
385 | - } |
|
386 | - } catch (Exception $exception) { |
|
387 | - $error[] = $exception->getMessage(); |
|
388 | - } |
|
389 | - |
|
390 | - if (empty($error)) { |
|
391 | - $config = \OC::$server->getConfig(); |
|
392 | - $config->setAppValue('core', 'installedat', microtime(true)); |
|
393 | - $config->setAppValue('core', 'lastupdatedat', microtime(true)); |
|
394 | - $config->setAppValue('core', 'vendor', $this->getVendor()); |
|
395 | - |
|
396 | - $group = \OC::$server->getGroupManager()->createGroup('admin'); |
|
397 | - if ($group instanceof IGroup) { |
|
398 | - $group->addUser($user); |
|
399 | - } |
|
400 | - |
|
401 | - // Install shipped apps and specified app bundles |
|
402 | - Installer::installShippedApps(); |
|
403 | - $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib')); |
|
404 | - $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle(); |
|
405 | - foreach ($defaultInstallationBundles as $bundle) { |
|
406 | - try { |
|
407 | - $this->installer->installAppBundle($bundle); |
|
408 | - } catch (Exception $e) { |
|
409 | - } |
|
410 | - } |
|
411 | - |
|
412 | - // create empty file in data dir, so we can later find |
|
413 | - // out that this is indeed an ownCloud data directory |
|
414 | - file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', ''); |
|
415 | - |
|
416 | - // Update .htaccess files |
|
417 | - self::updateHtaccess(); |
|
418 | - self::protectDataDirectory(); |
|
419 | - |
|
420 | - self::installBackgroundJobs(); |
|
421 | - |
|
422 | - //and we are done |
|
423 | - $config->setSystemValue('installed', true); |
|
424 | - |
|
425 | - // Create a session token for the newly created user |
|
426 | - // The token provider requires a working db, so it's not injected on setup |
|
427 | - /* @var $userSession User\Session */ |
|
428 | - $userSession = \OC::$server->getUserSession(); |
|
429 | - $defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class); |
|
430 | - $userSession->setTokenProvider($defaultTokenProvider); |
|
431 | - $userSession->login($username, $password); |
|
432 | - $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password); |
|
433 | - |
|
434 | - $session = $userSession->getSession(); |
|
435 | - $session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime()); |
|
436 | - |
|
437 | - // Set email for admin |
|
438 | - if (!empty($options['adminemail'])) { |
|
439 | - $config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']); |
|
440 | - } |
|
441 | - } |
|
442 | - |
|
443 | - return $error; |
|
444 | - } |
|
445 | - |
|
446 | - public static function installBackgroundJobs() { |
|
447 | - $jobList = \OC::$server->getJobList(); |
|
448 | - $jobList->add(DefaultTokenCleanupJob::class); |
|
449 | - $jobList->add(Rotate::class); |
|
450 | - $jobList->add(BackgroundCleanupJob::class); |
|
451 | - } |
|
452 | - |
|
453 | - /** |
|
454 | - * @return string Absolute path to htaccess |
|
455 | - */ |
|
456 | - private function pathToHtaccess() { |
|
457 | - return \OC::$SERVERROOT . '/.htaccess'; |
|
458 | - } |
|
459 | - |
|
460 | - /** |
|
461 | - * Find webroot from config |
|
462 | - * |
|
463 | - * @param SystemConfig $config |
|
464 | - * @return string |
|
465 | - * @throws InvalidArgumentException when invalid value for overwrite.cli.url |
|
466 | - */ |
|
467 | - private static function findWebRoot(SystemConfig $config): string { |
|
468 | - // For CLI read the value from overwrite.cli.url |
|
469 | - if (\OC::$CLI) { |
|
470 | - $webRoot = $config->getValue('overwrite.cli.url', ''); |
|
471 | - if ($webRoot === '') { |
|
472 | - throw new InvalidArgumentException('overwrite.cli.url is empty'); |
|
473 | - } |
|
474 | - if (!filter_var($webRoot, FILTER_VALIDATE_URL)) { |
|
475 | - throw new InvalidArgumentException('invalid value for overwrite.cli.url'); |
|
476 | - } |
|
477 | - $webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/'); |
|
478 | - } else { |
|
479 | - $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/'; |
|
480 | - } |
|
481 | - |
|
482 | - return $webRoot; |
|
483 | - } |
|
484 | - |
|
485 | - /** |
|
486 | - * Append the correct ErrorDocument path for Apache hosts |
|
487 | - * |
|
488 | - * @return bool True when success, False otherwise |
|
489 | - * @throws \OCP\AppFramework\QueryException |
|
490 | - */ |
|
491 | - public static function updateHtaccess() { |
|
492 | - $config = \OC::$server->getSystemConfig(); |
|
493 | - |
|
494 | - try { |
|
495 | - $webRoot = self::findWebRoot($config); |
|
496 | - } catch (InvalidArgumentException $e) { |
|
497 | - return false; |
|
498 | - } |
|
499 | - |
|
500 | - $setupHelper = new \OC\Setup( |
|
501 | - $config, |
|
502 | - \OC::$server->get(IniGetWrapper::class), |
|
503 | - \OC::$server->getL10N('lib'), |
|
504 | - \OC::$server->query(Defaults::class), |
|
505 | - \OC::$server->get(LoggerInterface::class), |
|
506 | - \OC::$server->getSecureRandom(), |
|
507 | - \OC::$server->query(Installer::class) |
|
508 | - ); |
|
509 | - |
|
510 | - $htaccessContent = file_get_contents($setupHelper->pathToHtaccess()); |
|
511 | - $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n"; |
|
512 | - $htaccessContent = explode($content, $htaccessContent, 2)[0]; |
|
513 | - |
|
514 | - //custom 403 error page |
|
515 | - $content .= "\nErrorDocument 403 " . $webRoot . '/'; |
|
516 | - |
|
517 | - //custom 404 error page |
|
518 | - $content .= "\nErrorDocument 404 " . $webRoot . '/'; |
|
519 | - |
|
520 | - // Add rewrite rules if the RewriteBase is configured |
|
521 | - $rewriteBase = $config->getValue('htaccess.RewriteBase', ''); |
|
522 | - if ($rewriteBase !== '') { |
|
523 | - $content .= "\n<IfModule mod_rewrite.c>"; |
|
524 | - $content .= "\n Options -MultiViews"; |
|
525 | - $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]"; |
|
526 | - $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]"; |
|
527 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav)$"; |
|
528 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php"; |
|
529 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$"; |
|
530 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php"; |
|
531 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php"; |
|
532 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots\\.txt"; |
|
533 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(ocm-provider|ocs-provider|updater)/"; |
|
534 | - $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*"; |
|
535 | - $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$"; |
|
536 | - $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]"; |
|
537 | - $content .= "\n RewriteBase " . $rewriteBase; |
|
538 | - $content .= "\n <IfModule mod_env.c>"; |
|
539 | - $content .= "\n SetEnv front_controller_active true"; |
|
540 | - $content .= "\n <IfModule mod_dir.c>"; |
|
541 | - $content .= "\n DirectorySlash off"; |
|
542 | - $content .= "\n </IfModule>"; |
|
543 | - $content .= "\n </IfModule>"; |
|
544 | - $content .= "\n</IfModule>"; |
|
545 | - } |
|
546 | - |
|
547 | - if ($content !== '') { |
|
548 | - //suppress errors in case we don't have permissions for it |
|
549 | - return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n"); |
|
550 | - } |
|
551 | - |
|
552 | - return false; |
|
553 | - } |
|
554 | - |
|
555 | - public static function protectDataDirectory() { |
|
556 | - //Require all denied |
|
557 | - $now = date('Y-m-d H:i:s'); |
|
558 | - $content = "# Generated by Nextcloud on $now\n"; |
|
559 | - $content .= "# Section for Apache 2.4 to 2.6\n"; |
|
560 | - $content .= "<IfModule mod_authz_core.c>\n"; |
|
561 | - $content .= " Require all denied\n"; |
|
562 | - $content .= "</IfModule>\n"; |
|
563 | - $content .= "<IfModule mod_access_compat.c>\n"; |
|
564 | - $content .= " Order Allow,Deny\n"; |
|
565 | - $content .= " Deny from all\n"; |
|
566 | - $content .= " Satisfy All\n"; |
|
567 | - $content .= "</IfModule>\n\n"; |
|
568 | - $content .= "# Section for Apache 2.2\n"; |
|
569 | - $content .= "<IfModule !mod_authz_core.c>\n"; |
|
570 | - $content .= " <IfModule !mod_access_compat.c>\n"; |
|
571 | - $content .= " <IfModule mod_authz_host.c>\n"; |
|
572 | - $content .= " Order Allow,Deny\n"; |
|
573 | - $content .= " Deny from all\n"; |
|
574 | - $content .= " </IfModule>\n"; |
|
575 | - $content .= " Satisfy All\n"; |
|
576 | - $content .= " </IfModule>\n"; |
|
577 | - $content .= "</IfModule>\n\n"; |
|
578 | - $content .= "# Section for Apache 2.2 to 2.6\n"; |
|
579 | - $content .= "<IfModule mod_autoindex.c>\n"; |
|
580 | - $content .= " IndexIgnore *\n"; |
|
581 | - $content .= "</IfModule>"; |
|
582 | - |
|
583 | - $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); |
|
584 | - file_put_contents($baseDir . '/.htaccess', $content); |
|
585 | - file_put_contents($baseDir . '/index.html', ''); |
|
586 | - } |
|
587 | - |
|
588 | - /** |
|
589 | - * Return vendor from which this version was published |
|
590 | - * |
|
591 | - * @return string Get the vendor |
|
592 | - * |
|
593 | - * Copy of \OC\Updater::getVendor() |
|
594 | - */ |
|
595 | - private function getVendor() { |
|
596 | - // this should really be a JSON file |
|
597 | - require \OC::$SERVERROOT . '/version.php'; |
|
598 | - /** @var string $vendor */ |
|
599 | - return (string)$vendor; |
|
600 | - } |
|
67 | + /** @var SystemConfig */ |
|
68 | + protected $config; |
|
69 | + /** @var IniGetWrapper */ |
|
70 | + protected $iniWrapper; |
|
71 | + /** @var IL10N */ |
|
72 | + protected $l10n; |
|
73 | + /** @var Defaults */ |
|
74 | + protected $defaults; |
|
75 | + /** @var LoggerInterface */ |
|
76 | + protected $logger; |
|
77 | + /** @var ISecureRandom */ |
|
78 | + protected $random; |
|
79 | + /** @var Installer */ |
|
80 | + protected $installer; |
|
81 | + |
|
82 | + public function __construct( |
|
83 | + SystemConfig $config, |
|
84 | + IniGetWrapper $iniWrapper, |
|
85 | + IL10N $l10n, |
|
86 | + Defaults $defaults, |
|
87 | + LoggerInterface $logger, |
|
88 | + ISecureRandom $random, |
|
89 | + Installer $installer |
|
90 | + ) { |
|
91 | + $this->config = $config; |
|
92 | + $this->iniWrapper = $iniWrapper; |
|
93 | + $this->l10n = $l10n; |
|
94 | + $this->defaults = $defaults; |
|
95 | + $this->logger = $logger; |
|
96 | + $this->random = $random; |
|
97 | + $this->installer = $installer; |
|
98 | + } |
|
99 | + |
|
100 | + protected static $dbSetupClasses = [ |
|
101 | + 'mysql' => \OC\Setup\MySQL::class, |
|
102 | + 'pgsql' => \OC\Setup\PostgreSQL::class, |
|
103 | + 'oci' => \OC\Setup\OCI::class, |
|
104 | + 'sqlite' => \OC\Setup\Sqlite::class, |
|
105 | + 'sqlite3' => \OC\Setup\Sqlite::class, |
|
106 | + ]; |
|
107 | + |
|
108 | + /** |
|
109 | + * Wrapper around the "class_exists" PHP function to be able to mock it |
|
110 | + * |
|
111 | + * @param string $name |
|
112 | + * @return bool |
|
113 | + */ |
|
114 | + protected function class_exists($name) { |
|
115 | + return class_exists($name); |
|
116 | + } |
|
117 | + |
|
118 | + /** |
|
119 | + * Wrapper around the "is_callable" PHP function to be able to mock it |
|
120 | + * |
|
121 | + * @param string $name |
|
122 | + * @return bool |
|
123 | + */ |
|
124 | + protected function is_callable($name) { |
|
125 | + return is_callable($name); |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * Wrapper around \PDO::getAvailableDrivers |
|
130 | + * |
|
131 | + * @return array |
|
132 | + */ |
|
133 | + protected function getAvailableDbDriversForPdo() { |
|
134 | + return \PDO::getAvailableDrivers(); |
|
135 | + } |
|
136 | + |
|
137 | + /** |
|
138 | + * Get the available and supported databases of this instance |
|
139 | + * |
|
140 | + * @param bool $allowAllDatabases |
|
141 | + * @return array |
|
142 | + * @throws Exception |
|
143 | + */ |
|
144 | + public function getSupportedDatabases($allowAllDatabases = false) { |
|
145 | + $availableDatabases = [ |
|
146 | + 'sqlite' => [ |
|
147 | + 'type' => 'pdo', |
|
148 | + 'call' => 'sqlite', |
|
149 | + 'name' => 'SQLite', |
|
150 | + ], |
|
151 | + 'mysql' => [ |
|
152 | + 'type' => 'pdo', |
|
153 | + 'call' => 'mysql', |
|
154 | + 'name' => 'MySQL/MariaDB', |
|
155 | + ], |
|
156 | + 'pgsql' => [ |
|
157 | + 'type' => 'pdo', |
|
158 | + 'call' => 'pgsql', |
|
159 | + 'name' => 'PostgreSQL', |
|
160 | + ], |
|
161 | + 'oci' => [ |
|
162 | + 'type' => 'function', |
|
163 | + 'call' => 'oci_connect', |
|
164 | + 'name' => 'Oracle', |
|
165 | + ], |
|
166 | + ]; |
|
167 | + if ($allowAllDatabases) { |
|
168 | + $configuredDatabases = array_keys($availableDatabases); |
|
169 | + } else { |
|
170 | + $configuredDatabases = $this->config->getValue('supportedDatabases', |
|
171 | + ['sqlite', 'mysql', 'pgsql']); |
|
172 | + } |
|
173 | + if (!is_array($configuredDatabases)) { |
|
174 | + throw new Exception('Supported databases are not properly configured.'); |
|
175 | + } |
|
176 | + |
|
177 | + $supportedDatabases = []; |
|
178 | + |
|
179 | + foreach ($configuredDatabases as $database) { |
|
180 | + if (array_key_exists($database, $availableDatabases)) { |
|
181 | + $working = false; |
|
182 | + $type = $availableDatabases[$database]['type']; |
|
183 | + $call = $availableDatabases[$database]['call']; |
|
184 | + |
|
185 | + if ($type === 'function') { |
|
186 | + $working = $this->is_callable($call); |
|
187 | + } elseif ($type === 'pdo') { |
|
188 | + $working = in_array($call, $this->getAvailableDbDriversForPdo(), true); |
|
189 | + } |
|
190 | + if ($working) { |
|
191 | + $supportedDatabases[$database] = $availableDatabases[$database]['name']; |
|
192 | + } |
|
193 | + } |
|
194 | + } |
|
195 | + |
|
196 | + return $supportedDatabases; |
|
197 | + } |
|
198 | + |
|
199 | + /** |
|
200 | + * Gathers system information like database type and does |
|
201 | + * a few system checks. |
|
202 | + * |
|
203 | + * @return array of system info, including an "errors" value |
|
204 | + * in case of errors/warnings |
|
205 | + */ |
|
206 | + public function getSystemInfo($allowAllDatabases = false) { |
|
207 | + $databases = $this->getSupportedDatabases($allowAllDatabases); |
|
208 | + |
|
209 | + $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data'); |
|
210 | + |
|
211 | + $errors = []; |
|
212 | + |
|
213 | + // Create data directory to test whether the .htaccess works |
|
214 | + // Notice that this is not necessarily the same data directory as the one |
|
215 | + // that will effectively be used. |
|
216 | + if (!file_exists($dataDir)) { |
|
217 | + @mkdir($dataDir); |
|
218 | + } |
|
219 | + $htAccessWorking = true; |
|
220 | + if (is_dir($dataDir) && is_writable($dataDir)) { |
|
221 | + // Protect data directory here, so we can test if the protection is working |
|
222 | + self::protectDataDirectory(); |
|
223 | + |
|
224 | + try { |
|
225 | + $util = new \OC_Util(); |
|
226 | + $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig()); |
|
227 | + } catch (\OCP\HintException $e) { |
|
228 | + $errors[] = [ |
|
229 | + 'error' => $e->getMessage(), |
|
230 | + 'exception' => $e, |
|
231 | + 'hint' => $e->getHint(), |
|
232 | + ]; |
|
233 | + $htAccessWorking = false; |
|
234 | + } |
|
235 | + } |
|
236 | + |
|
237 | + if (\OC_Util::runningOnMac()) { |
|
238 | + $errors[] = [ |
|
239 | + 'error' => $this->l10n->t( |
|
240 | + 'Mac OS X is not supported and %s will not work properly on this platform. ' . |
|
241 | + 'Use it at your own risk! ', |
|
242 | + [$this->defaults->getProductName()] |
|
243 | + ), |
|
244 | + 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'), |
|
245 | + ]; |
|
246 | + } |
|
247 | + |
|
248 | + if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) { |
|
249 | + $errors[] = [ |
|
250 | + 'error' => $this->l10n->t( |
|
251 | + 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' . |
|
252 | + 'This will lead to problems with files over 4 GB and is highly discouraged.', |
|
253 | + [$this->defaults->getProductName()] |
|
254 | + ), |
|
255 | + 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'), |
|
256 | + ]; |
|
257 | + } |
|
258 | + |
|
259 | + return [ |
|
260 | + 'hasSQLite' => isset($databases['sqlite']), |
|
261 | + 'hasMySQL' => isset($databases['mysql']), |
|
262 | + 'hasPostgreSQL' => isset($databases['pgsql']), |
|
263 | + 'hasOracle' => isset($databases['oci']), |
|
264 | + 'databases' => $databases, |
|
265 | + 'directory' => $dataDir, |
|
266 | + 'htaccessWorking' => $htAccessWorking, |
|
267 | + 'errors' => $errors, |
|
268 | + ]; |
|
269 | + } |
|
270 | + |
|
271 | + /** |
|
272 | + * @param $options |
|
273 | + * @return array |
|
274 | + */ |
|
275 | + public function install($options) { |
|
276 | + $l = $this->l10n; |
|
277 | + |
|
278 | + $error = []; |
|
279 | + $dbType = $options['dbtype']; |
|
280 | + |
|
281 | + if (empty($options['adminlogin'])) { |
|
282 | + $error[] = $l->t('Set an admin username.'); |
|
283 | + } |
|
284 | + if (empty($options['adminpass'])) { |
|
285 | + $error[] = $l->t('Set an admin password.'); |
|
286 | + } |
|
287 | + if (empty($options['directory'])) { |
|
288 | + $options['directory'] = \OC::$SERVERROOT . "/data"; |
|
289 | + } |
|
290 | + |
|
291 | + if (!isset(self::$dbSetupClasses[$dbType])) { |
|
292 | + $dbType = 'sqlite'; |
|
293 | + } |
|
294 | + |
|
295 | + $username = htmlspecialchars_decode($options['adminlogin']); |
|
296 | + $password = htmlspecialchars_decode($options['adminpass']); |
|
297 | + $dataDir = htmlspecialchars_decode($options['directory']); |
|
298 | + |
|
299 | + $class = self::$dbSetupClasses[$dbType]; |
|
300 | + /** @var \OC\Setup\AbstractDatabase $dbSetup */ |
|
301 | + $dbSetup = new $class($l, $this->config, $this->logger, $this->random); |
|
302 | + $error = array_merge($error, $dbSetup->validate($options)); |
|
303 | + |
|
304 | + // validate the data directory |
|
305 | + if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) { |
|
306 | + $error[] = $l->t("Cannot create or write into the data directory %s", [$dataDir]); |
|
307 | + } |
|
308 | + |
|
309 | + if (!empty($error)) { |
|
310 | + return $error; |
|
311 | + } |
|
312 | + |
|
313 | + $request = \OC::$server->getRequest(); |
|
314 | + |
|
315 | + //no errors, good |
|
316 | + if (isset($options['trusted_domains']) |
|
317 | + && is_array($options['trusted_domains'])) { |
|
318 | + $trustedDomains = $options['trusted_domains']; |
|
319 | + } else { |
|
320 | + $trustedDomains = [$request->getInsecureServerHost()]; |
|
321 | + } |
|
322 | + |
|
323 | + //use sqlite3 when available, otherwise sqlite2 will be used. |
|
324 | + if ($dbType === 'sqlite' && class_exists('SQLite3')) { |
|
325 | + $dbType = 'sqlite3'; |
|
326 | + } |
|
327 | + |
|
328 | + //generate a random salt that is used to salt the local user passwords |
|
329 | + $salt = $this->random->generate(30); |
|
330 | + // generate a secret |
|
331 | + $secret = $this->random->generate(48); |
|
332 | + |
|
333 | + //write the config file |
|
334 | + $newConfigValues = [ |
|
335 | + 'passwordsalt' => $salt, |
|
336 | + 'secret' => $secret, |
|
337 | + 'trusted_domains' => $trustedDomains, |
|
338 | + 'datadirectory' => $dataDir, |
|
339 | + 'dbtype' => $dbType, |
|
340 | + 'version' => implode('.', \OCP\Util::getVersion()), |
|
341 | + ]; |
|
342 | + |
|
343 | + if ($this->config->getValue('overwrite.cli.url', null) === null) { |
|
344 | + $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT; |
|
345 | + } |
|
346 | + |
|
347 | + $this->config->setValues($newConfigValues); |
|
348 | + |
|
349 | + $dbSetup->initialize($options); |
|
350 | + try { |
|
351 | + $dbSetup->setupDatabase($username); |
|
352 | + } catch (\OC\DatabaseSetupException $e) { |
|
353 | + $error[] = [ |
|
354 | + 'error' => $e->getMessage(), |
|
355 | + 'exception' => $e, |
|
356 | + 'hint' => $e->getHint(), |
|
357 | + ]; |
|
358 | + return $error; |
|
359 | + } catch (Exception $e) { |
|
360 | + $error[] = [ |
|
361 | + 'error' => 'Error while trying to create admin user: ' . $e->getMessage(), |
|
362 | + 'exception' => $e, |
|
363 | + 'hint' => '', |
|
364 | + ]; |
|
365 | + return $error; |
|
366 | + } |
|
367 | + try { |
|
368 | + // apply necessary migrations |
|
369 | + $dbSetup->runMigrations(); |
|
370 | + } catch (Exception $e) { |
|
371 | + $error[] = [ |
|
372 | + 'error' => 'Error while trying to initialise the database: ' . $e->getMessage(), |
|
373 | + 'exception' => $e, |
|
374 | + 'hint' => '', |
|
375 | + ]; |
|
376 | + return $error; |
|
377 | + } |
|
378 | + |
|
379 | + //create the user and group |
|
380 | + $user = null; |
|
381 | + try { |
|
382 | + $user = \OC::$server->getUserManager()->createUser($username, $password); |
|
383 | + if (!$user) { |
|
384 | + $error[] = "User <$username> could not be created."; |
|
385 | + } |
|
386 | + } catch (Exception $exception) { |
|
387 | + $error[] = $exception->getMessage(); |
|
388 | + } |
|
389 | + |
|
390 | + if (empty($error)) { |
|
391 | + $config = \OC::$server->getConfig(); |
|
392 | + $config->setAppValue('core', 'installedat', microtime(true)); |
|
393 | + $config->setAppValue('core', 'lastupdatedat', microtime(true)); |
|
394 | + $config->setAppValue('core', 'vendor', $this->getVendor()); |
|
395 | + |
|
396 | + $group = \OC::$server->getGroupManager()->createGroup('admin'); |
|
397 | + if ($group instanceof IGroup) { |
|
398 | + $group->addUser($user); |
|
399 | + } |
|
400 | + |
|
401 | + // Install shipped apps and specified app bundles |
|
402 | + Installer::installShippedApps(); |
|
403 | + $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib')); |
|
404 | + $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle(); |
|
405 | + foreach ($defaultInstallationBundles as $bundle) { |
|
406 | + try { |
|
407 | + $this->installer->installAppBundle($bundle); |
|
408 | + } catch (Exception $e) { |
|
409 | + } |
|
410 | + } |
|
411 | + |
|
412 | + // create empty file in data dir, so we can later find |
|
413 | + // out that this is indeed an ownCloud data directory |
|
414 | + file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', ''); |
|
415 | + |
|
416 | + // Update .htaccess files |
|
417 | + self::updateHtaccess(); |
|
418 | + self::protectDataDirectory(); |
|
419 | + |
|
420 | + self::installBackgroundJobs(); |
|
421 | + |
|
422 | + //and we are done |
|
423 | + $config->setSystemValue('installed', true); |
|
424 | + |
|
425 | + // Create a session token for the newly created user |
|
426 | + // The token provider requires a working db, so it's not injected on setup |
|
427 | + /* @var $userSession User\Session */ |
|
428 | + $userSession = \OC::$server->getUserSession(); |
|
429 | + $defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class); |
|
430 | + $userSession->setTokenProvider($defaultTokenProvider); |
|
431 | + $userSession->login($username, $password); |
|
432 | + $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password); |
|
433 | + |
|
434 | + $session = $userSession->getSession(); |
|
435 | + $session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime()); |
|
436 | + |
|
437 | + // Set email for admin |
|
438 | + if (!empty($options['adminemail'])) { |
|
439 | + $config->setUserValue($user->getUID(), 'settings', 'email', $options['adminemail']); |
|
440 | + } |
|
441 | + } |
|
442 | + |
|
443 | + return $error; |
|
444 | + } |
|
445 | + |
|
446 | + public static function installBackgroundJobs() { |
|
447 | + $jobList = \OC::$server->getJobList(); |
|
448 | + $jobList->add(DefaultTokenCleanupJob::class); |
|
449 | + $jobList->add(Rotate::class); |
|
450 | + $jobList->add(BackgroundCleanupJob::class); |
|
451 | + } |
|
452 | + |
|
453 | + /** |
|
454 | + * @return string Absolute path to htaccess |
|
455 | + */ |
|
456 | + private function pathToHtaccess() { |
|
457 | + return \OC::$SERVERROOT . '/.htaccess'; |
|
458 | + } |
|
459 | + |
|
460 | + /** |
|
461 | + * Find webroot from config |
|
462 | + * |
|
463 | + * @param SystemConfig $config |
|
464 | + * @return string |
|
465 | + * @throws InvalidArgumentException when invalid value for overwrite.cli.url |
|
466 | + */ |
|
467 | + private static function findWebRoot(SystemConfig $config): string { |
|
468 | + // For CLI read the value from overwrite.cli.url |
|
469 | + if (\OC::$CLI) { |
|
470 | + $webRoot = $config->getValue('overwrite.cli.url', ''); |
|
471 | + if ($webRoot === '') { |
|
472 | + throw new InvalidArgumentException('overwrite.cli.url is empty'); |
|
473 | + } |
|
474 | + if (!filter_var($webRoot, FILTER_VALIDATE_URL)) { |
|
475 | + throw new InvalidArgumentException('invalid value for overwrite.cli.url'); |
|
476 | + } |
|
477 | + $webRoot = rtrim(parse_url($webRoot, PHP_URL_PATH), '/'); |
|
478 | + } else { |
|
479 | + $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/'; |
|
480 | + } |
|
481 | + |
|
482 | + return $webRoot; |
|
483 | + } |
|
484 | + |
|
485 | + /** |
|
486 | + * Append the correct ErrorDocument path for Apache hosts |
|
487 | + * |
|
488 | + * @return bool True when success, False otherwise |
|
489 | + * @throws \OCP\AppFramework\QueryException |
|
490 | + */ |
|
491 | + public static function updateHtaccess() { |
|
492 | + $config = \OC::$server->getSystemConfig(); |
|
493 | + |
|
494 | + try { |
|
495 | + $webRoot = self::findWebRoot($config); |
|
496 | + } catch (InvalidArgumentException $e) { |
|
497 | + return false; |
|
498 | + } |
|
499 | + |
|
500 | + $setupHelper = new \OC\Setup( |
|
501 | + $config, |
|
502 | + \OC::$server->get(IniGetWrapper::class), |
|
503 | + \OC::$server->getL10N('lib'), |
|
504 | + \OC::$server->query(Defaults::class), |
|
505 | + \OC::$server->get(LoggerInterface::class), |
|
506 | + \OC::$server->getSecureRandom(), |
|
507 | + \OC::$server->query(Installer::class) |
|
508 | + ); |
|
509 | + |
|
510 | + $htaccessContent = file_get_contents($setupHelper->pathToHtaccess()); |
|
511 | + $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n"; |
|
512 | + $htaccessContent = explode($content, $htaccessContent, 2)[0]; |
|
513 | + |
|
514 | + //custom 403 error page |
|
515 | + $content .= "\nErrorDocument 403 " . $webRoot . '/'; |
|
516 | + |
|
517 | + //custom 404 error page |
|
518 | + $content .= "\nErrorDocument 404 " . $webRoot . '/'; |
|
519 | + |
|
520 | + // Add rewrite rules if the RewriteBase is configured |
|
521 | + $rewriteBase = $config->getValue('htaccess.RewriteBase', ''); |
|
522 | + if ($rewriteBase !== '') { |
|
523 | + $content .= "\n<IfModule mod_rewrite.c>"; |
|
524 | + $content .= "\n Options -MultiViews"; |
|
525 | + $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]"; |
|
526 | + $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]"; |
|
527 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav)$"; |
|
528 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php"; |
|
529 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$"; |
|
530 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php"; |
|
531 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php"; |
|
532 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots\\.txt"; |
|
533 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(ocm-provider|ocs-provider|updater)/"; |
|
534 | + $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*"; |
|
535 | + $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$"; |
|
536 | + $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]"; |
|
537 | + $content .= "\n RewriteBase " . $rewriteBase; |
|
538 | + $content .= "\n <IfModule mod_env.c>"; |
|
539 | + $content .= "\n SetEnv front_controller_active true"; |
|
540 | + $content .= "\n <IfModule mod_dir.c>"; |
|
541 | + $content .= "\n DirectorySlash off"; |
|
542 | + $content .= "\n </IfModule>"; |
|
543 | + $content .= "\n </IfModule>"; |
|
544 | + $content .= "\n</IfModule>"; |
|
545 | + } |
|
546 | + |
|
547 | + if ($content !== '') { |
|
548 | + //suppress errors in case we don't have permissions for it |
|
549 | + return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n"); |
|
550 | + } |
|
551 | + |
|
552 | + return false; |
|
553 | + } |
|
554 | + |
|
555 | + public static function protectDataDirectory() { |
|
556 | + //Require all denied |
|
557 | + $now = date('Y-m-d H:i:s'); |
|
558 | + $content = "# Generated by Nextcloud on $now\n"; |
|
559 | + $content .= "# Section for Apache 2.4 to 2.6\n"; |
|
560 | + $content .= "<IfModule mod_authz_core.c>\n"; |
|
561 | + $content .= " Require all denied\n"; |
|
562 | + $content .= "</IfModule>\n"; |
|
563 | + $content .= "<IfModule mod_access_compat.c>\n"; |
|
564 | + $content .= " Order Allow,Deny\n"; |
|
565 | + $content .= " Deny from all\n"; |
|
566 | + $content .= " Satisfy All\n"; |
|
567 | + $content .= "</IfModule>\n\n"; |
|
568 | + $content .= "# Section for Apache 2.2\n"; |
|
569 | + $content .= "<IfModule !mod_authz_core.c>\n"; |
|
570 | + $content .= " <IfModule !mod_access_compat.c>\n"; |
|
571 | + $content .= " <IfModule mod_authz_host.c>\n"; |
|
572 | + $content .= " Order Allow,Deny\n"; |
|
573 | + $content .= " Deny from all\n"; |
|
574 | + $content .= " </IfModule>\n"; |
|
575 | + $content .= " Satisfy All\n"; |
|
576 | + $content .= " </IfModule>\n"; |
|
577 | + $content .= "</IfModule>\n\n"; |
|
578 | + $content .= "# Section for Apache 2.2 to 2.6\n"; |
|
579 | + $content .= "<IfModule mod_autoindex.c>\n"; |
|
580 | + $content .= " IndexIgnore *\n"; |
|
581 | + $content .= "</IfModule>"; |
|
582 | + |
|
583 | + $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); |
|
584 | + file_put_contents($baseDir . '/.htaccess', $content); |
|
585 | + file_put_contents($baseDir . '/index.html', ''); |
|
586 | + } |
|
587 | + |
|
588 | + /** |
|
589 | + * Return vendor from which this version was published |
|
590 | + * |
|
591 | + * @return string Get the vendor |
|
592 | + * |
|
593 | + * Copy of \OC\Updater::getVendor() |
|
594 | + */ |
|
595 | + private function getVendor() { |
|
596 | + // this should really be a JSON file |
|
597 | + require \OC::$SERVERROOT . '/version.php'; |
|
598 | + /** @var string $vendor */ |
|
599 | + return (string)$vendor; |
|
600 | + } |
|
601 | 601 | } |
@@ -77,1405 +77,1405 @@ |
||
77 | 77 | use Psr\Log\LoggerInterface; |
78 | 78 | |
79 | 79 | class OC_Util { |
80 | - public static $scripts = []; |
|
81 | - public static $styles = []; |
|
82 | - public static $headers = []; |
|
83 | - private static $rootMounted = false; |
|
84 | - private static $fsSetup = false; |
|
85 | - |
|
86 | - /** @var array Local cache of version.php */ |
|
87 | - private static $versionCache = null; |
|
88 | - |
|
89 | - protected static function getAppManager() { |
|
90 | - return \OC::$server->getAppManager(); |
|
91 | - } |
|
92 | - |
|
93 | - private static function initLocalStorageRootFS() { |
|
94 | - // mount local file backend as root |
|
95 | - $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data"); |
|
96 | - //first set up the local "root" storage |
|
97 | - \OC\Files\Filesystem::initMountManager(); |
|
98 | - if (!self::$rootMounted) { |
|
99 | - \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/'); |
|
100 | - self::$rootMounted = true; |
|
101 | - } |
|
102 | - } |
|
103 | - |
|
104 | - /** |
|
105 | - * mounting an object storage as the root fs will in essence remove the |
|
106 | - * necessity of a data folder being present. |
|
107 | - * TODO make home storage aware of this and use the object storage instead of local disk access |
|
108 | - * |
|
109 | - * @param array $config containing 'class' and optional 'arguments' |
|
110 | - * @suppress PhanDeprecatedFunction |
|
111 | - */ |
|
112 | - private static function initObjectStoreRootFS($config) { |
|
113 | - // check misconfiguration |
|
114 | - if (empty($config['class'])) { |
|
115 | - \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR); |
|
116 | - } |
|
117 | - if (!isset($config['arguments'])) { |
|
118 | - $config['arguments'] = []; |
|
119 | - } |
|
120 | - |
|
121 | - // instantiate object store implementation |
|
122 | - $name = $config['class']; |
|
123 | - if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) { |
|
124 | - $segments = explode('\\', $name); |
|
125 | - OC_App::loadApp(strtolower($segments[1])); |
|
126 | - } |
|
127 | - $config['arguments']['objectstore'] = new $config['class']($config['arguments']); |
|
128 | - // mount with plain / root object store implementation |
|
129 | - $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage'; |
|
130 | - |
|
131 | - // mount object storage as root |
|
132 | - \OC\Files\Filesystem::initMountManager(); |
|
133 | - if (!self::$rootMounted) { |
|
134 | - \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/'); |
|
135 | - self::$rootMounted = true; |
|
136 | - } |
|
137 | - } |
|
138 | - |
|
139 | - /** |
|
140 | - * mounting an object storage as the root fs will in essence remove the |
|
141 | - * necessity of a data folder being present. |
|
142 | - * |
|
143 | - * @param array $config containing 'class' and optional 'arguments' |
|
144 | - * @suppress PhanDeprecatedFunction |
|
145 | - */ |
|
146 | - private static function initObjectStoreMultibucketRootFS($config) { |
|
147 | - // check misconfiguration |
|
148 | - if (empty($config['class'])) { |
|
149 | - \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR); |
|
150 | - } |
|
151 | - if (!isset($config['arguments'])) { |
|
152 | - $config['arguments'] = []; |
|
153 | - } |
|
154 | - |
|
155 | - // instantiate object store implementation |
|
156 | - $name = $config['class']; |
|
157 | - if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) { |
|
158 | - $segments = explode('\\', $name); |
|
159 | - OC_App::loadApp(strtolower($segments[1])); |
|
160 | - } |
|
161 | - |
|
162 | - if (!isset($config['arguments']['bucket'])) { |
|
163 | - $config['arguments']['bucket'] = ''; |
|
164 | - } |
|
165 | - // put the root FS always in first bucket for multibucket configuration |
|
166 | - $config['arguments']['bucket'] .= '0'; |
|
167 | - |
|
168 | - $config['arguments']['objectstore'] = new $config['class']($config['arguments']); |
|
169 | - // mount with plain / root object store implementation |
|
170 | - $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage'; |
|
171 | - |
|
172 | - // mount object storage as root |
|
173 | - \OC\Files\Filesystem::initMountManager(); |
|
174 | - if (!self::$rootMounted) { |
|
175 | - \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/'); |
|
176 | - self::$rootMounted = true; |
|
177 | - } |
|
178 | - } |
|
179 | - |
|
180 | - /** |
|
181 | - * Can be set up |
|
182 | - * |
|
183 | - * @param string $user |
|
184 | - * @return boolean |
|
185 | - * @description configure the initial filesystem based on the configuration |
|
186 | - * @suppress PhanDeprecatedFunction |
|
187 | - * @suppress PhanAccessMethodInternal |
|
188 | - */ |
|
189 | - public static function setupFS($user = '') { |
|
190 | - //setting up the filesystem twice can only lead to trouble |
|
191 | - if (self::$fsSetup) { |
|
192 | - return false; |
|
193 | - } |
|
194 | - |
|
195 | - \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem'); |
|
196 | - |
|
197 | - // If we are not forced to load a specific user we load the one that is logged in |
|
198 | - if ($user === null) { |
|
199 | - $user = ''; |
|
200 | - } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) { |
|
201 | - $user = OC_User::getUser(); |
|
202 | - } |
|
203 | - |
|
204 | - // load all filesystem apps before, so no setup-hook gets lost |
|
205 | - OC_App::loadApps(['filesystem']); |
|
206 | - |
|
207 | - // the filesystem will finish when $user is not empty, |
|
208 | - // mark fs setup here to avoid doing the setup from loading |
|
209 | - // OC_Filesystem |
|
210 | - if ($user != '') { |
|
211 | - self::$fsSetup = true; |
|
212 | - } |
|
213 | - |
|
214 | - \OC\Files\Filesystem::initMountManager(); |
|
215 | - |
|
216 | - $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false); |
|
217 | - \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
218 | - if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) { |
|
219 | - /** @var \OC\Files\Storage\Common $storage */ |
|
220 | - $storage->setMountOptions($mount->getOptions()); |
|
221 | - } |
|
222 | - return $storage; |
|
223 | - }); |
|
224 | - |
|
225 | - \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
226 | - if (!$mount->getOption('enable_sharing', true)) { |
|
227 | - return new \OC\Files\Storage\Wrapper\PermissionsMask([ |
|
228 | - 'storage' => $storage, |
|
229 | - 'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE |
|
230 | - ]); |
|
231 | - } |
|
232 | - return $storage; |
|
233 | - }); |
|
234 | - |
|
235 | - // install storage availability wrapper, before most other wrappers |
|
236 | - \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) { |
|
237 | - if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) { |
|
238 | - return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]); |
|
239 | - } |
|
240 | - return $storage; |
|
241 | - }); |
|
242 | - |
|
243 | - \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
244 | - if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) { |
|
245 | - return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]); |
|
246 | - } |
|
247 | - return $storage; |
|
248 | - }); |
|
249 | - |
|
250 | - \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) { |
|
251 | - // set up quota for home storages, even for other users |
|
252 | - // which can happen when using sharing |
|
253 | - |
|
254 | - /** |
|
255 | - * @var \OC\Files\Storage\Storage $storage |
|
256 | - */ |
|
257 | - if ($storage->instanceOfStorage('\OC\Files\Storage\Home') |
|
258 | - || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage') |
|
259 | - ) { |
|
260 | - /** @var \OC\Files\Storage\Home $storage */ |
|
261 | - if (is_object($storage->getUser())) { |
|
262 | - $quota = OC_Util::getUserQuota($storage->getUser()); |
|
263 | - if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { |
|
264 | - return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']); |
|
265 | - } |
|
266 | - } |
|
267 | - } |
|
268 | - |
|
269 | - return $storage; |
|
270 | - }); |
|
271 | - |
|
272 | - \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
273 | - /* |
|
80 | + public static $scripts = []; |
|
81 | + public static $styles = []; |
|
82 | + public static $headers = []; |
|
83 | + private static $rootMounted = false; |
|
84 | + private static $fsSetup = false; |
|
85 | + |
|
86 | + /** @var array Local cache of version.php */ |
|
87 | + private static $versionCache = null; |
|
88 | + |
|
89 | + protected static function getAppManager() { |
|
90 | + return \OC::$server->getAppManager(); |
|
91 | + } |
|
92 | + |
|
93 | + private static function initLocalStorageRootFS() { |
|
94 | + // mount local file backend as root |
|
95 | + $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data"); |
|
96 | + //first set up the local "root" storage |
|
97 | + \OC\Files\Filesystem::initMountManager(); |
|
98 | + if (!self::$rootMounted) { |
|
99 | + \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/'); |
|
100 | + self::$rootMounted = true; |
|
101 | + } |
|
102 | + } |
|
103 | + |
|
104 | + /** |
|
105 | + * mounting an object storage as the root fs will in essence remove the |
|
106 | + * necessity of a data folder being present. |
|
107 | + * TODO make home storage aware of this and use the object storage instead of local disk access |
|
108 | + * |
|
109 | + * @param array $config containing 'class' and optional 'arguments' |
|
110 | + * @suppress PhanDeprecatedFunction |
|
111 | + */ |
|
112 | + private static function initObjectStoreRootFS($config) { |
|
113 | + // check misconfiguration |
|
114 | + if (empty($config['class'])) { |
|
115 | + \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR); |
|
116 | + } |
|
117 | + if (!isset($config['arguments'])) { |
|
118 | + $config['arguments'] = []; |
|
119 | + } |
|
120 | + |
|
121 | + // instantiate object store implementation |
|
122 | + $name = $config['class']; |
|
123 | + if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) { |
|
124 | + $segments = explode('\\', $name); |
|
125 | + OC_App::loadApp(strtolower($segments[1])); |
|
126 | + } |
|
127 | + $config['arguments']['objectstore'] = new $config['class']($config['arguments']); |
|
128 | + // mount with plain / root object store implementation |
|
129 | + $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage'; |
|
130 | + |
|
131 | + // mount object storage as root |
|
132 | + \OC\Files\Filesystem::initMountManager(); |
|
133 | + if (!self::$rootMounted) { |
|
134 | + \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/'); |
|
135 | + self::$rootMounted = true; |
|
136 | + } |
|
137 | + } |
|
138 | + |
|
139 | + /** |
|
140 | + * mounting an object storage as the root fs will in essence remove the |
|
141 | + * necessity of a data folder being present. |
|
142 | + * |
|
143 | + * @param array $config containing 'class' and optional 'arguments' |
|
144 | + * @suppress PhanDeprecatedFunction |
|
145 | + */ |
|
146 | + private static function initObjectStoreMultibucketRootFS($config) { |
|
147 | + // check misconfiguration |
|
148 | + if (empty($config['class'])) { |
|
149 | + \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR); |
|
150 | + } |
|
151 | + if (!isset($config['arguments'])) { |
|
152 | + $config['arguments'] = []; |
|
153 | + } |
|
154 | + |
|
155 | + // instantiate object store implementation |
|
156 | + $name = $config['class']; |
|
157 | + if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) { |
|
158 | + $segments = explode('\\', $name); |
|
159 | + OC_App::loadApp(strtolower($segments[1])); |
|
160 | + } |
|
161 | + |
|
162 | + if (!isset($config['arguments']['bucket'])) { |
|
163 | + $config['arguments']['bucket'] = ''; |
|
164 | + } |
|
165 | + // put the root FS always in first bucket for multibucket configuration |
|
166 | + $config['arguments']['bucket'] .= '0'; |
|
167 | + |
|
168 | + $config['arguments']['objectstore'] = new $config['class']($config['arguments']); |
|
169 | + // mount with plain / root object store implementation |
|
170 | + $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage'; |
|
171 | + |
|
172 | + // mount object storage as root |
|
173 | + \OC\Files\Filesystem::initMountManager(); |
|
174 | + if (!self::$rootMounted) { |
|
175 | + \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/'); |
|
176 | + self::$rootMounted = true; |
|
177 | + } |
|
178 | + } |
|
179 | + |
|
180 | + /** |
|
181 | + * Can be set up |
|
182 | + * |
|
183 | + * @param string $user |
|
184 | + * @return boolean |
|
185 | + * @description configure the initial filesystem based on the configuration |
|
186 | + * @suppress PhanDeprecatedFunction |
|
187 | + * @suppress PhanAccessMethodInternal |
|
188 | + */ |
|
189 | + public static function setupFS($user = '') { |
|
190 | + //setting up the filesystem twice can only lead to trouble |
|
191 | + if (self::$fsSetup) { |
|
192 | + return false; |
|
193 | + } |
|
194 | + |
|
195 | + \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem'); |
|
196 | + |
|
197 | + // If we are not forced to load a specific user we load the one that is logged in |
|
198 | + if ($user === null) { |
|
199 | + $user = ''; |
|
200 | + } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) { |
|
201 | + $user = OC_User::getUser(); |
|
202 | + } |
|
203 | + |
|
204 | + // load all filesystem apps before, so no setup-hook gets lost |
|
205 | + OC_App::loadApps(['filesystem']); |
|
206 | + |
|
207 | + // the filesystem will finish when $user is not empty, |
|
208 | + // mark fs setup here to avoid doing the setup from loading |
|
209 | + // OC_Filesystem |
|
210 | + if ($user != '') { |
|
211 | + self::$fsSetup = true; |
|
212 | + } |
|
213 | + |
|
214 | + \OC\Files\Filesystem::initMountManager(); |
|
215 | + |
|
216 | + $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false); |
|
217 | + \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
218 | + if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) { |
|
219 | + /** @var \OC\Files\Storage\Common $storage */ |
|
220 | + $storage->setMountOptions($mount->getOptions()); |
|
221 | + } |
|
222 | + return $storage; |
|
223 | + }); |
|
224 | + |
|
225 | + \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
226 | + if (!$mount->getOption('enable_sharing', true)) { |
|
227 | + return new \OC\Files\Storage\Wrapper\PermissionsMask([ |
|
228 | + 'storage' => $storage, |
|
229 | + 'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE |
|
230 | + ]); |
|
231 | + } |
|
232 | + return $storage; |
|
233 | + }); |
|
234 | + |
|
235 | + // install storage availability wrapper, before most other wrappers |
|
236 | + \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) { |
|
237 | + if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) { |
|
238 | + return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]); |
|
239 | + } |
|
240 | + return $storage; |
|
241 | + }); |
|
242 | + |
|
243 | + \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
244 | + if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) { |
|
245 | + return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]); |
|
246 | + } |
|
247 | + return $storage; |
|
248 | + }); |
|
249 | + |
|
250 | + \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) { |
|
251 | + // set up quota for home storages, even for other users |
|
252 | + // which can happen when using sharing |
|
253 | + |
|
254 | + /** |
|
255 | + * @var \OC\Files\Storage\Storage $storage |
|
256 | + */ |
|
257 | + if ($storage->instanceOfStorage('\OC\Files\Storage\Home') |
|
258 | + || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage') |
|
259 | + ) { |
|
260 | + /** @var \OC\Files\Storage\Home $storage */ |
|
261 | + if (is_object($storage->getUser())) { |
|
262 | + $quota = OC_Util::getUserQuota($storage->getUser()); |
|
263 | + if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { |
|
264 | + return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']); |
|
265 | + } |
|
266 | + } |
|
267 | + } |
|
268 | + |
|
269 | + return $storage; |
|
270 | + }); |
|
271 | + |
|
272 | + \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) { |
|
273 | + /* |
|
274 | 274 | * Do not allow any operations that modify the storage |
275 | 275 | */ |
276 | - if ($mount->getOption('readonly', false)) { |
|
277 | - return new \OC\Files\Storage\Wrapper\PermissionsMask([ |
|
278 | - 'storage' => $storage, |
|
279 | - 'mask' => \OCP\Constants::PERMISSION_ALL & ~( |
|
280 | - \OCP\Constants::PERMISSION_UPDATE | |
|
281 | - \OCP\Constants::PERMISSION_CREATE | |
|
282 | - \OCP\Constants::PERMISSION_DELETE |
|
283 | - ), |
|
284 | - ]); |
|
285 | - } |
|
286 | - return $storage; |
|
287 | - }); |
|
288 | - |
|
289 | - OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]); |
|
290 | - |
|
291 | - \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging); |
|
292 | - |
|
293 | - //check if we are using an object storage |
|
294 | - $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null); |
|
295 | - $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null); |
|
296 | - |
|
297 | - // use the same order as in ObjectHomeMountProvider |
|
298 | - if (isset($objectStoreMultibucket)) { |
|
299 | - self::initObjectStoreMultibucketRootFS($objectStoreMultibucket); |
|
300 | - } elseif (isset($objectStore)) { |
|
301 | - self::initObjectStoreRootFS($objectStore); |
|
302 | - } else { |
|
303 | - self::initLocalStorageRootFS(); |
|
304 | - } |
|
305 | - |
|
306 | - /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */ |
|
307 | - $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class); |
|
308 | - $rootMountProviders = $mountProviderCollection->getRootMounts(); |
|
309 | - |
|
310 | - /** @var \OC\Files\Mount\Manager $mountManager */ |
|
311 | - $mountManager = \OC\Files\Filesystem::getMountManager(); |
|
312 | - foreach ($rootMountProviders as $rootMountProvider) { |
|
313 | - $mountManager->addMount($rootMountProvider); |
|
314 | - } |
|
315 | - |
|
316 | - if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) { |
|
317 | - \OC::$server->getEventLogger()->end('setup_fs'); |
|
318 | - return false; |
|
319 | - } |
|
320 | - |
|
321 | - //if we aren't logged in, there is no use to set up the filesystem |
|
322 | - if ($user != "") { |
|
323 | - $userDir = '/' . $user . '/files'; |
|
324 | - |
|
325 | - //jail the user into his "home" directory |
|
326 | - \OC\Files\Filesystem::init($user, $userDir); |
|
327 | - |
|
328 | - OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]); |
|
329 | - } |
|
330 | - \OC::$server->getEventLogger()->end('setup_fs'); |
|
331 | - return true; |
|
332 | - } |
|
333 | - |
|
334 | - /** |
|
335 | - * check if a password is required for each public link |
|
336 | - * |
|
337 | - * @return boolean |
|
338 | - * @suppress PhanDeprecatedFunction |
|
339 | - */ |
|
340 | - public static function isPublicLinkPasswordRequired() { |
|
341 | - /** @var IManager $shareManager */ |
|
342 | - $shareManager = \OC::$server->get(IManager::class); |
|
343 | - return $shareManager->shareApiLinkEnforcePassword(); |
|
344 | - } |
|
345 | - |
|
346 | - /** |
|
347 | - * check if sharing is disabled for the current user |
|
348 | - * @param IConfig $config |
|
349 | - * @param IGroupManager $groupManager |
|
350 | - * @param IUser|null $user |
|
351 | - * @return bool |
|
352 | - */ |
|
353 | - public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) { |
|
354 | - /** @var IManager $shareManager */ |
|
355 | - $shareManager = \OC::$server->get(IManager::class); |
|
356 | - $userId = $user ? $user->getUID() : null; |
|
357 | - return $shareManager->sharingDisabledForUser($userId); |
|
358 | - } |
|
359 | - |
|
360 | - /** |
|
361 | - * check if share API enforces a default expire date |
|
362 | - * |
|
363 | - * @return boolean |
|
364 | - * @suppress PhanDeprecatedFunction |
|
365 | - */ |
|
366 | - public static function isDefaultExpireDateEnforced() { |
|
367 | - /** @var IManager $shareManager */ |
|
368 | - $shareManager = \OC::$server->get(IManager::class); |
|
369 | - return $shareManager->shareApiLinkDefaultExpireDateEnforced(); |
|
370 | - } |
|
371 | - |
|
372 | - /** |
|
373 | - * Get the quota of a user |
|
374 | - * |
|
375 | - * @param IUser|null $user |
|
376 | - * @return float Quota bytes |
|
377 | - */ |
|
378 | - public static function getUserQuota(?IUser $user) { |
|
379 | - if (is_null($user)) { |
|
380 | - return \OCP\Files\FileInfo::SPACE_UNLIMITED; |
|
381 | - } |
|
382 | - $userQuota = $user->getQuota(); |
|
383 | - if ($userQuota === 'none') { |
|
384 | - return \OCP\Files\FileInfo::SPACE_UNLIMITED; |
|
385 | - } |
|
386 | - return OC_Helper::computerFileSize($userQuota); |
|
387 | - } |
|
388 | - |
|
389 | - /** |
|
390 | - * copies the skeleton to the users /files |
|
391 | - * |
|
392 | - * @param string $userId |
|
393 | - * @param \OCP\Files\Folder $userDirectory |
|
394 | - * @throws \OCP\Files\NotFoundException |
|
395 | - * @throws \OCP\Files\NotPermittedException |
|
396 | - * @suppress PhanDeprecatedFunction |
|
397 | - */ |
|
398 | - public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { |
|
399 | - /** @var LoggerInterface $logger */ |
|
400 | - $logger = \OC::$server->get(LoggerInterface::class); |
|
401 | - |
|
402 | - $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton'); |
|
403 | - $userLang = \OC::$server->getL10NFactory()->findLanguage(); |
|
404 | - $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory); |
|
405 | - |
|
406 | - if (!file_exists($skeletonDirectory)) { |
|
407 | - $dialectStart = strpos($userLang, '_'); |
|
408 | - if ($dialectStart !== false) { |
|
409 | - $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory); |
|
410 | - } |
|
411 | - if ($dialectStart === false || !file_exists($skeletonDirectory)) { |
|
412 | - $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory); |
|
413 | - } |
|
414 | - if (!file_exists($skeletonDirectory)) { |
|
415 | - $skeletonDirectory = ''; |
|
416 | - } |
|
417 | - } |
|
418 | - |
|
419 | - $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', ''); |
|
420 | - |
|
421 | - if ($instanceId === null) { |
|
422 | - throw new \RuntimeException('no instance id!'); |
|
423 | - } |
|
424 | - $appdata = 'appdata_' . $instanceId; |
|
425 | - if ($userId === $appdata) { |
|
426 | - throw new \RuntimeException('username is reserved name: ' . $appdata); |
|
427 | - } |
|
428 | - |
|
429 | - if (!empty($skeletonDirectory)) { |
|
430 | - $logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']); |
|
431 | - self::copyr($skeletonDirectory, $userDirectory); |
|
432 | - // update the file cache |
|
433 | - $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE); |
|
434 | - |
|
435 | - /** @var ITemplateManager $templateManager */ |
|
436 | - $templateManager = \OC::$server->get(ITemplateManager::class); |
|
437 | - $templateManager->initializeTemplateDirectory(null, $userId); |
|
438 | - } |
|
439 | - } |
|
440 | - |
|
441 | - /** |
|
442 | - * copies a directory recursively by using streams |
|
443 | - * |
|
444 | - * @param string $source |
|
445 | - * @param \OCP\Files\Folder $target |
|
446 | - * @return void |
|
447 | - */ |
|
448 | - public static function copyr($source, \OCP\Files\Folder $target) { |
|
449 | - $logger = \OC::$server->getLogger(); |
|
450 | - |
|
451 | - // Verify if folder exists |
|
452 | - $dir = opendir($source); |
|
453 | - if ($dir === false) { |
|
454 | - $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']); |
|
455 | - return; |
|
456 | - } |
|
457 | - |
|
458 | - // Copy the files |
|
459 | - while (false !== ($file = readdir($dir))) { |
|
460 | - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { |
|
461 | - if (is_dir($source . '/' . $file)) { |
|
462 | - $child = $target->newFolder($file); |
|
463 | - self::copyr($source . '/' . $file, $child); |
|
464 | - } else { |
|
465 | - $child = $target->newFile($file); |
|
466 | - $sourceStream = fopen($source . '/' . $file, 'r'); |
|
467 | - if ($sourceStream === false) { |
|
468 | - $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']); |
|
469 | - closedir($dir); |
|
470 | - return; |
|
471 | - } |
|
472 | - stream_copy_to_stream($sourceStream, $child->fopen('w')); |
|
473 | - } |
|
474 | - } |
|
475 | - } |
|
476 | - closedir($dir); |
|
477 | - } |
|
478 | - |
|
479 | - /** |
|
480 | - * @return void |
|
481 | - * @suppress PhanUndeclaredMethod |
|
482 | - */ |
|
483 | - public static function tearDownFS() { |
|
484 | - \OC\Files\Filesystem::tearDown(); |
|
485 | - \OC::$server->getRootFolder()->clearCache(); |
|
486 | - self::$fsSetup = false; |
|
487 | - self::$rootMounted = false; |
|
488 | - } |
|
489 | - |
|
490 | - /** |
|
491 | - * get the current installed version of ownCloud |
|
492 | - * |
|
493 | - * @return array |
|
494 | - */ |
|
495 | - public static function getVersion() { |
|
496 | - OC_Util::loadVersion(); |
|
497 | - return self::$versionCache['OC_Version']; |
|
498 | - } |
|
499 | - |
|
500 | - /** |
|
501 | - * get the current installed version string of ownCloud |
|
502 | - * |
|
503 | - * @return string |
|
504 | - */ |
|
505 | - public static function getVersionString() { |
|
506 | - OC_Util::loadVersion(); |
|
507 | - return self::$versionCache['OC_VersionString']; |
|
508 | - } |
|
509 | - |
|
510 | - /** |
|
511 | - * @deprecated the value is of no use anymore |
|
512 | - * @return string |
|
513 | - */ |
|
514 | - public static function getEditionString() { |
|
515 | - return ''; |
|
516 | - } |
|
517 | - |
|
518 | - /** |
|
519 | - * @description get the update channel of the current installed of ownCloud. |
|
520 | - * @return string |
|
521 | - */ |
|
522 | - public static function getChannel() { |
|
523 | - OC_Util::loadVersion(); |
|
524 | - return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']); |
|
525 | - } |
|
526 | - |
|
527 | - /** |
|
528 | - * @description get the build number of the current installed of ownCloud. |
|
529 | - * @return string |
|
530 | - */ |
|
531 | - public static function getBuild() { |
|
532 | - OC_Util::loadVersion(); |
|
533 | - return self::$versionCache['OC_Build']; |
|
534 | - } |
|
535 | - |
|
536 | - /** |
|
537 | - * @description load the version.php into the session as cache |
|
538 | - * @suppress PhanUndeclaredVariable |
|
539 | - */ |
|
540 | - private static function loadVersion() { |
|
541 | - if (self::$versionCache !== null) { |
|
542 | - return; |
|
543 | - } |
|
544 | - |
|
545 | - $timestamp = filemtime(OC::$SERVERROOT . '/version.php'); |
|
546 | - require OC::$SERVERROOT . '/version.php'; |
|
547 | - /** @var int $timestamp */ |
|
548 | - self::$versionCache['OC_Version_Timestamp'] = $timestamp; |
|
549 | - /** @var string $OC_Version */ |
|
550 | - self::$versionCache['OC_Version'] = $OC_Version; |
|
551 | - /** @var string $OC_VersionString */ |
|
552 | - self::$versionCache['OC_VersionString'] = $OC_VersionString; |
|
553 | - /** @var string $OC_Build */ |
|
554 | - self::$versionCache['OC_Build'] = $OC_Build; |
|
555 | - |
|
556 | - /** @var string $OC_Channel */ |
|
557 | - self::$versionCache['OC_Channel'] = $OC_Channel; |
|
558 | - } |
|
559 | - |
|
560 | - /** |
|
561 | - * generates a path for JS/CSS files. If no application is provided it will create the path for core. |
|
562 | - * |
|
563 | - * @param string $application application to get the files from |
|
564 | - * @param string $directory directory within this application (css, js, vendor, etc) |
|
565 | - * @param string $file the file inside of the above folder |
|
566 | - * @return string the path |
|
567 | - */ |
|
568 | - private static function generatePath($application, $directory, $file) { |
|
569 | - if (is_null($file)) { |
|
570 | - $file = $application; |
|
571 | - $application = ""; |
|
572 | - } |
|
573 | - if (!empty($application)) { |
|
574 | - return "$application/$directory/$file"; |
|
575 | - } else { |
|
576 | - return "$directory/$file"; |
|
577 | - } |
|
578 | - } |
|
579 | - |
|
580 | - /** |
|
581 | - * add a javascript file |
|
582 | - * |
|
583 | - * @param string $application application id |
|
584 | - * @param string|null $file filename |
|
585 | - * @param bool $prepend prepend the Script to the beginning of the list |
|
586 | - * @return void |
|
587 | - */ |
|
588 | - public static function addScript($application, $file = null, $prepend = false) { |
|
589 | - $path = OC_Util::generatePath($application, 'js', $file); |
|
590 | - |
|
591 | - // core js files need separate handling |
|
592 | - if ($application !== 'core' && $file !== null) { |
|
593 | - self::addTranslations($application); |
|
594 | - } |
|
595 | - self::addExternalResource($application, $prepend, $path, "script"); |
|
596 | - } |
|
597 | - |
|
598 | - /** |
|
599 | - * add a javascript file from the vendor sub folder |
|
600 | - * |
|
601 | - * @param string $application application id |
|
602 | - * @param string|null $file filename |
|
603 | - * @param bool $prepend prepend the Script to the beginning of the list |
|
604 | - * @return void |
|
605 | - */ |
|
606 | - public static function addVendorScript($application, $file = null, $prepend = false) { |
|
607 | - $path = OC_Util::generatePath($application, 'vendor', $file); |
|
608 | - self::addExternalResource($application, $prepend, $path, "script"); |
|
609 | - } |
|
610 | - |
|
611 | - /** |
|
612 | - * add a translation JS file |
|
613 | - * |
|
614 | - * @param string $application application id |
|
615 | - * @param string|null $languageCode language code, defaults to the current language |
|
616 | - * @param bool|null $prepend prepend the Script to the beginning of the list |
|
617 | - */ |
|
618 | - public static function addTranslations($application, $languageCode = null, $prepend = false) { |
|
619 | - if (is_null($languageCode)) { |
|
620 | - $languageCode = \OC::$server->getL10NFactory()->findLanguage($application); |
|
621 | - } |
|
622 | - if (!empty($application)) { |
|
623 | - $path = "$application/l10n/$languageCode"; |
|
624 | - } else { |
|
625 | - $path = "l10n/$languageCode"; |
|
626 | - } |
|
627 | - self::addExternalResource($application, $prepend, $path, "script"); |
|
628 | - } |
|
629 | - |
|
630 | - /** |
|
631 | - * add a css file |
|
632 | - * |
|
633 | - * @param string $application application id |
|
634 | - * @param string|null $file filename |
|
635 | - * @param bool $prepend prepend the Style to the beginning of the list |
|
636 | - * @return void |
|
637 | - */ |
|
638 | - public static function addStyle($application, $file = null, $prepend = false) { |
|
639 | - $path = OC_Util::generatePath($application, 'css', $file); |
|
640 | - self::addExternalResource($application, $prepend, $path, "style"); |
|
641 | - } |
|
642 | - |
|
643 | - /** |
|
644 | - * add a css file from the vendor sub folder |
|
645 | - * |
|
646 | - * @param string $application application id |
|
647 | - * @param string|null $file filename |
|
648 | - * @param bool $prepend prepend the Style to the beginning of the list |
|
649 | - * @return void |
|
650 | - */ |
|
651 | - public static function addVendorStyle($application, $file = null, $prepend = false) { |
|
652 | - $path = OC_Util::generatePath($application, 'vendor', $file); |
|
653 | - self::addExternalResource($application, $prepend, $path, "style"); |
|
654 | - } |
|
655 | - |
|
656 | - /** |
|
657 | - * add an external resource css/js file |
|
658 | - * |
|
659 | - * @param string $application application id |
|
660 | - * @param bool $prepend prepend the file to the beginning of the list |
|
661 | - * @param string $path |
|
662 | - * @param string $type (script or style) |
|
663 | - * @return void |
|
664 | - */ |
|
665 | - private static function addExternalResource($application, $prepend, $path, $type = "script") { |
|
666 | - if ($type === "style") { |
|
667 | - if (!in_array($path, self::$styles)) { |
|
668 | - if ($prepend === true) { |
|
669 | - array_unshift(self::$styles, $path); |
|
670 | - } else { |
|
671 | - self::$styles[] = $path; |
|
672 | - } |
|
673 | - } |
|
674 | - } elseif ($type === "script") { |
|
675 | - if (!in_array($path, self::$scripts)) { |
|
676 | - if ($prepend === true) { |
|
677 | - array_unshift(self::$scripts, $path); |
|
678 | - } else { |
|
679 | - self::$scripts [] = $path; |
|
680 | - } |
|
681 | - } |
|
682 | - } |
|
683 | - } |
|
684 | - |
|
685 | - /** |
|
686 | - * Add a custom element to the header |
|
687 | - * If $text is null then the element will be written as empty element. |
|
688 | - * So use "" to get a closing tag. |
|
689 | - * @param string $tag tag name of the element |
|
690 | - * @param array $attributes array of attributes for the element |
|
691 | - * @param string $text the text content for the element |
|
692 | - * @param bool $prepend prepend the header to the beginning of the list |
|
693 | - */ |
|
694 | - public static function addHeader($tag, $attributes, $text = null, $prepend = false) { |
|
695 | - $header = [ |
|
696 | - 'tag' => $tag, |
|
697 | - 'attributes' => $attributes, |
|
698 | - 'text' => $text |
|
699 | - ]; |
|
700 | - if ($prepend === true) { |
|
701 | - array_unshift(self::$headers, $header); |
|
702 | - } else { |
|
703 | - self::$headers[] = $header; |
|
704 | - } |
|
705 | - } |
|
706 | - |
|
707 | - /** |
|
708 | - * check if the current server configuration is suitable for ownCloud |
|
709 | - * |
|
710 | - * @param \OC\SystemConfig $config |
|
711 | - * @return array arrays with error messages and hints |
|
712 | - */ |
|
713 | - public static function checkServer(\OC\SystemConfig $config) { |
|
714 | - $l = \OC::$server->getL10N('lib'); |
|
715 | - $errors = []; |
|
716 | - $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data'); |
|
717 | - |
|
718 | - if (!self::needUpgrade($config) && $config->getValue('installed', false)) { |
|
719 | - // this check needs to be done every time |
|
720 | - $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY); |
|
721 | - } |
|
722 | - |
|
723 | - // Assume that if checkServer() succeeded before in this session, then all is fine. |
|
724 | - if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) { |
|
725 | - return $errors; |
|
726 | - } |
|
727 | - |
|
728 | - $webServerRestart = false; |
|
729 | - $setup = new \OC\Setup( |
|
730 | - $config, |
|
731 | - \OC::$server->get(IniGetWrapper::class), |
|
732 | - \OC::$server->getL10N('lib'), |
|
733 | - \OC::$server->get(\OCP\Defaults::class), |
|
734 | - \OC::$server->get(LoggerInterface::class), |
|
735 | - \OC::$server->getSecureRandom(), |
|
736 | - \OC::$server->get(\OC\Installer::class) |
|
737 | - ); |
|
738 | - |
|
739 | - $urlGenerator = \OC::$server->getURLGenerator(); |
|
740 | - |
|
741 | - $availableDatabases = $setup->getSupportedDatabases(); |
|
742 | - if (empty($availableDatabases)) { |
|
743 | - $errors[] = [ |
|
744 | - 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'), |
|
745 | - 'hint' => '' //TODO: sane hint |
|
746 | - ]; |
|
747 | - $webServerRestart = true; |
|
748 | - } |
|
749 | - |
|
750 | - // Check if config folder is writable. |
|
751 | - if (!OC_Helper::isReadOnlyConfigEnabled()) { |
|
752 | - if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) { |
|
753 | - $errors[] = [ |
|
754 | - 'error' => $l->t('Cannot write into "config" directory'), |
|
755 | - 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s', |
|
756 | - [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. ' |
|
757 | - . $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', |
|
758 | - [ $urlGenerator->linkToDocs('admin-config') ]) |
|
759 | - ]; |
|
760 | - } |
|
761 | - } |
|
762 | - |
|
763 | - // Check if there is a writable install folder. |
|
764 | - if ($config->getValue('appstoreenabled', true)) { |
|
765 | - if (OC_App::getInstallPath() === null |
|
766 | - || !is_writable(OC_App::getInstallPath()) |
|
767 | - || !is_readable(OC_App::getInstallPath()) |
|
768 | - ) { |
|
769 | - $errors[] = [ |
|
770 | - 'error' => $l->t('Cannot write into "apps" directory'), |
|
771 | - 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory' |
|
772 | - . ' or disabling the App Store in the config file.') |
|
773 | - ]; |
|
774 | - } |
|
775 | - } |
|
776 | - // Create root dir. |
|
777 | - if ($config->getValue('installed', false)) { |
|
778 | - if (!is_dir($CONFIG_DATADIRECTORY)) { |
|
779 | - $success = @mkdir($CONFIG_DATADIRECTORY); |
|
780 | - if ($success) { |
|
781 | - $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY)); |
|
782 | - } else { |
|
783 | - $errors[] = [ |
|
784 | - 'error' => $l->t('Cannot create "data" directory'), |
|
785 | - 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s', |
|
786 | - [$urlGenerator->linkToDocs('admin-dir_permissions')]) |
|
787 | - ]; |
|
788 | - } |
|
789 | - } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) { |
|
790 | - // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists. |
|
791 | - $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_')); |
|
792 | - $handle = fopen($testFile, 'w'); |
|
793 | - if (!$handle || fwrite($handle, 'Test write operation') === false) { |
|
794 | - $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.', |
|
795 | - [$urlGenerator->linkToDocs('admin-dir_permissions')]); |
|
796 | - $errors[] = [ |
|
797 | - 'error' => 'Your data directory is not writable', |
|
798 | - 'hint' => $permissionsHint |
|
799 | - ]; |
|
800 | - } else { |
|
801 | - fclose($handle); |
|
802 | - unlink($testFile); |
|
803 | - } |
|
804 | - } else { |
|
805 | - $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY)); |
|
806 | - } |
|
807 | - } |
|
808 | - |
|
809 | - if (!OC_Util::isSetLocaleWorking()) { |
|
810 | - $errors[] = [ |
|
811 | - 'error' => $l->t('Setting locale to %s failed', |
|
812 | - ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/' |
|
813 | - . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']), |
|
814 | - 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.') |
|
815 | - ]; |
|
816 | - } |
|
817 | - |
|
818 | - // Contains the dependencies that should be checked against |
|
819 | - // classes = class_exists |
|
820 | - // functions = function_exists |
|
821 | - // defined = defined |
|
822 | - // ini = ini_get |
|
823 | - // If the dependency is not found the missing module name is shown to the EndUser |
|
824 | - // When adding new checks always verify that they pass on Travis as well |
|
825 | - // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini |
|
826 | - $dependencies = [ |
|
827 | - 'classes' => [ |
|
828 | - 'ZipArchive' => 'zip', |
|
829 | - 'DOMDocument' => 'dom', |
|
830 | - 'XMLWriter' => 'XMLWriter', |
|
831 | - 'XMLReader' => 'XMLReader', |
|
832 | - ], |
|
833 | - 'functions' => [ |
|
834 | - 'xml_parser_create' => 'libxml', |
|
835 | - 'mb_strcut' => 'mbstring', |
|
836 | - 'ctype_digit' => 'ctype', |
|
837 | - 'json_encode' => 'JSON', |
|
838 | - 'gd_info' => 'GD', |
|
839 | - 'gzencode' => 'zlib', |
|
840 | - 'iconv' => 'iconv', |
|
841 | - 'simplexml_load_string' => 'SimpleXML', |
|
842 | - 'hash' => 'HASH Message Digest Framework', |
|
843 | - 'curl_init' => 'cURL', |
|
844 | - 'openssl_verify' => 'OpenSSL', |
|
845 | - ], |
|
846 | - 'defined' => [ |
|
847 | - 'PDO::ATTR_DRIVER_NAME' => 'PDO' |
|
848 | - ], |
|
849 | - 'ini' => [ |
|
850 | - 'default_charset' => 'UTF-8', |
|
851 | - ], |
|
852 | - ]; |
|
853 | - $missingDependencies = []; |
|
854 | - $invalidIniSettings = []; |
|
855 | - |
|
856 | - $iniWrapper = \OC::$server->get(IniGetWrapper::class); |
|
857 | - foreach ($dependencies['classes'] as $class => $module) { |
|
858 | - if (!class_exists($class)) { |
|
859 | - $missingDependencies[] = $module; |
|
860 | - } |
|
861 | - } |
|
862 | - foreach ($dependencies['functions'] as $function => $module) { |
|
863 | - if (!function_exists($function)) { |
|
864 | - $missingDependencies[] = $module; |
|
865 | - } |
|
866 | - } |
|
867 | - foreach ($dependencies['defined'] as $defined => $module) { |
|
868 | - if (!defined($defined)) { |
|
869 | - $missingDependencies[] = $module; |
|
870 | - } |
|
871 | - } |
|
872 | - foreach ($dependencies['ini'] as $setting => $expected) { |
|
873 | - if (is_bool($expected)) { |
|
874 | - if ($iniWrapper->getBool($setting) !== $expected) { |
|
875 | - $invalidIniSettings[] = [$setting, $expected]; |
|
876 | - } |
|
877 | - } |
|
878 | - if (is_int($expected)) { |
|
879 | - if ($iniWrapper->getNumeric($setting) !== $expected) { |
|
880 | - $invalidIniSettings[] = [$setting, $expected]; |
|
881 | - } |
|
882 | - } |
|
883 | - if (is_string($expected)) { |
|
884 | - if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) { |
|
885 | - $invalidIniSettings[] = [$setting, $expected]; |
|
886 | - } |
|
887 | - } |
|
888 | - } |
|
889 | - |
|
890 | - foreach ($missingDependencies as $missingDependency) { |
|
891 | - $errors[] = [ |
|
892 | - 'error' => $l->t('PHP module %s not installed.', [$missingDependency]), |
|
893 | - 'hint' => $l->t('Please ask your server administrator to install the module.'), |
|
894 | - ]; |
|
895 | - $webServerRestart = true; |
|
896 | - } |
|
897 | - foreach ($invalidIniSettings as $setting) { |
|
898 | - if (is_bool($setting[1])) { |
|
899 | - $setting[1] = $setting[1] ? 'on' : 'off'; |
|
900 | - } |
|
901 | - $errors[] = [ |
|
902 | - 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]), |
|
903 | - 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again') |
|
904 | - ]; |
|
905 | - $webServerRestart = true; |
|
906 | - } |
|
907 | - |
|
908 | - /** |
|
909 | - * The mbstring.func_overload check can only be performed if the mbstring |
|
910 | - * module is installed as it will return null if the checking setting is |
|
911 | - * not available and thus a check on the boolean value fails. |
|
912 | - * |
|
913 | - * TODO: Should probably be implemented in the above generic dependency |
|
914 | - * check somehow in the long-term. |
|
915 | - */ |
|
916 | - if ($iniWrapper->getBool('mbstring.func_overload') !== null && |
|
917 | - $iniWrapper->getBool('mbstring.func_overload') === true) { |
|
918 | - $errors[] = [ |
|
919 | - 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]), |
|
920 | - 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini') |
|
921 | - ]; |
|
922 | - } |
|
923 | - |
|
924 | - if (function_exists('xml_parser_create') && |
|
925 | - LIBXML_LOADED_VERSION < 20700) { |
|
926 | - $version = LIBXML_LOADED_VERSION; |
|
927 | - $major = floor($version / 10000); |
|
928 | - $version -= ($major * 10000); |
|
929 | - $minor = floor($version / 100); |
|
930 | - $version -= ($minor * 100); |
|
931 | - $patch = $version; |
|
932 | - $errors[] = [ |
|
933 | - 'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]), |
|
934 | - 'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.') |
|
935 | - ]; |
|
936 | - } |
|
937 | - |
|
938 | - if (!self::isAnnotationsWorking()) { |
|
939 | - $errors[] = [ |
|
940 | - 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'), |
|
941 | - 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.') |
|
942 | - ]; |
|
943 | - } |
|
944 | - |
|
945 | - if (!\OC::$CLI && $webServerRestart) { |
|
946 | - $errors[] = [ |
|
947 | - 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'), |
|
948 | - 'hint' => $l->t('Please ask your server administrator to restart the web server.') |
|
949 | - ]; |
|
950 | - } |
|
951 | - |
|
952 | - $errors = array_merge($errors, self::checkDatabaseVersion()); |
|
953 | - |
|
954 | - // Cache the result of this function |
|
955 | - \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0); |
|
956 | - |
|
957 | - return $errors; |
|
958 | - } |
|
959 | - |
|
960 | - /** |
|
961 | - * Check the database version |
|
962 | - * |
|
963 | - * @return array errors array |
|
964 | - */ |
|
965 | - public static function checkDatabaseVersion() { |
|
966 | - $l = \OC::$server->getL10N('lib'); |
|
967 | - $errors = []; |
|
968 | - $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite'); |
|
969 | - if ($dbType === 'pgsql') { |
|
970 | - // check PostgreSQL version |
|
971 | - try { |
|
972 | - $result = \OC_DB::executeAudited('SHOW SERVER_VERSION'); |
|
973 | - $data = $result->fetchRow(); |
|
974 | - $result->closeCursor(); |
|
975 | - if (isset($data['server_version'])) { |
|
976 | - $version = $data['server_version']; |
|
977 | - if (version_compare($version, '9.0.0', '<')) { |
|
978 | - $errors[] = [ |
|
979 | - 'error' => $l->t('PostgreSQL >= 9 required'), |
|
980 | - 'hint' => $l->t('Please upgrade your database version') |
|
981 | - ]; |
|
982 | - } |
|
983 | - } |
|
984 | - } catch (\Doctrine\DBAL\Exception $e) { |
|
985 | - $logger = \OC::$server->getLogger(); |
|
986 | - $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9'); |
|
987 | - $logger->logException($e); |
|
988 | - } |
|
989 | - } |
|
990 | - return $errors; |
|
991 | - } |
|
992 | - |
|
993 | - /** |
|
994 | - * Check for correct file permissions of data directory |
|
995 | - * |
|
996 | - * @param string $dataDirectory |
|
997 | - * @return array arrays with error messages and hints |
|
998 | - */ |
|
999 | - public static function checkDataDirectoryPermissions($dataDirectory) { |
|
1000 | - if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) { |
|
1001 | - return []; |
|
1002 | - } |
|
1003 | - |
|
1004 | - $perms = substr(decoct(@fileperms($dataDirectory)), -3); |
|
1005 | - if (substr($perms, -1) !== '0') { |
|
1006 | - chmod($dataDirectory, 0770); |
|
1007 | - clearstatcache(); |
|
1008 | - $perms = substr(decoct(@fileperms($dataDirectory)), -3); |
|
1009 | - if ($perms[2] !== '0') { |
|
1010 | - $l = \OC::$server->getL10N('lib'); |
|
1011 | - return [[ |
|
1012 | - 'error' => $l->t('Your data directory is readable by other users'), |
|
1013 | - 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'), |
|
1014 | - ]]; |
|
1015 | - } |
|
1016 | - } |
|
1017 | - return []; |
|
1018 | - } |
|
1019 | - |
|
1020 | - /** |
|
1021 | - * Check that the data directory exists and is valid by |
|
1022 | - * checking the existence of the ".ocdata" file. |
|
1023 | - * |
|
1024 | - * @param string $dataDirectory data directory path |
|
1025 | - * @return array errors found |
|
1026 | - */ |
|
1027 | - public static function checkDataDirectoryValidity($dataDirectory) { |
|
1028 | - $l = \OC::$server->getL10N('lib'); |
|
1029 | - $errors = []; |
|
1030 | - if ($dataDirectory[0] !== '/') { |
|
1031 | - $errors[] = [ |
|
1032 | - 'error' => $l->t('Your data directory must be an absolute path'), |
|
1033 | - 'hint' => $l->t('Check the value of "datadirectory" in your configuration') |
|
1034 | - ]; |
|
1035 | - } |
|
1036 | - if (!file_exists($dataDirectory . '/.ocdata')) { |
|
1037 | - $errors[] = [ |
|
1038 | - 'error' => $l->t('Your data directory is invalid'), |
|
1039 | - 'hint' => $l->t('Ensure there is a file called ".ocdata"' . |
|
1040 | - ' in the root of the data directory.') |
|
1041 | - ]; |
|
1042 | - } |
|
1043 | - return $errors; |
|
1044 | - } |
|
1045 | - |
|
1046 | - /** |
|
1047 | - * Check if the user is logged in, redirects to home if not. With |
|
1048 | - * redirect URL parameter to the request URI. |
|
1049 | - * |
|
1050 | - * @return void |
|
1051 | - */ |
|
1052 | - public static function checkLoggedIn() { |
|
1053 | - // Check if we are a user |
|
1054 | - if (!\OC::$server->getUserSession()->isLoggedIn()) { |
|
1055 | - header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute( |
|
1056 | - 'core.login.showLoginForm', |
|
1057 | - [ |
|
1058 | - 'redirect_url' => \OC::$server->getRequest()->getRequestUri(), |
|
1059 | - ] |
|
1060 | - ) |
|
1061 | - ); |
|
1062 | - exit(); |
|
1063 | - } |
|
1064 | - // Redirect to 2FA challenge selection if 2FA challenge was not solved yet |
|
1065 | - if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { |
|
1066 | - header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge')); |
|
1067 | - exit(); |
|
1068 | - } |
|
1069 | - } |
|
1070 | - |
|
1071 | - /** |
|
1072 | - * Check if the user is a admin, redirects to home if not |
|
1073 | - * |
|
1074 | - * @return void |
|
1075 | - */ |
|
1076 | - public static function checkAdminUser() { |
|
1077 | - OC_Util::checkLoggedIn(); |
|
1078 | - if (!OC_User::isAdminUser(OC_User::getUser())) { |
|
1079 | - header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php')); |
|
1080 | - exit(); |
|
1081 | - } |
|
1082 | - } |
|
1083 | - |
|
1084 | - /** |
|
1085 | - * Returns the URL of the default page |
|
1086 | - * based on the system configuration and |
|
1087 | - * the apps visible for the current user |
|
1088 | - * |
|
1089 | - * @return string URL |
|
1090 | - * @suppress PhanDeprecatedFunction |
|
1091 | - */ |
|
1092 | - public static function getDefaultPageUrl() { |
|
1093 | - /** @var IConfig $config */ |
|
1094 | - $config = \OC::$server->get(IConfig::class); |
|
1095 | - $urlGenerator = \OC::$server->getURLGenerator(); |
|
1096 | - // Deny the redirect if the URL contains a @ |
|
1097 | - // This prevents unvalidated redirects like ?redirect_url=:[email protected] |
|
1098 | - if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) { |
|
1099 | - $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url'])); |
|
1100 | - } else { |
|
1101 | - $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage'); |
|
1102 | - if ($defaultPage) { |
|
1103 | - $location = $urlGenerator->getAbsoluteURL($defaultPage); |
|
1104 | - } else { |
|
1105 | - $appId = 'files'; |
|
1106 | - $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files')); |
|
1107 | - |
|
1108 | - /** @var IUserSession $userSession */ |
|
1109 | - $userSession = \OC::$server->get(IUserSession::class); |
|
1110 | - $user = $userSession->getUser(); |
|
1111 | - if ($user) { |
|
1112 | - $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp')); |
|
1113 | - $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps)); |
|
1114 | - } |
|
1115 | - |
|
1116 | - // find the first app that is enabled for the current user |
|
1117 | - foreach ($defaultApps as $defaultApp) { |
|
1118 | - $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp)); |
|
1119 | - if (static::getAppManager()->isEnabledForUser($defaultApp)) { |
|
1120 | - $appId = $defaultApp; |
|
1121 | - break; |
|
1122 | - } |
|
1123 | - } |
|
1124 | - |
|
1125 | - if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') { |
|
1126 | - $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/'); |
|
1127 | - } else { |
|
1128 | - $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/'); |
|
1129 | - } |
|
1130 | - } |
|
1131 | - } |
|
1132 | - return $location; |
|
1133 | - } |
|
1134 | - |
|
1135 | - /** |
|
1136 | - * Redirect to the user default page |
|
1137 | - * |
|
1138 | - * @return void |
|
1139 | - */ |
|
1140 | - public static function redirectToDefaultPage() { |
|
1141 | - $location = self::getDefaultPageUrl(); |
|
1142 | - header('Location: ' . $location); |
|
1143 | - exit(); |
|
1144 | - } |
|
1145 | - |
|
1146 | - /** |
|
1147 | - * get an id unique for this instance |
|
1148 | - * |
|
1149 | - * @return string |
|
1150 | - */ |
|
1151 | - public static function getInstanceId() { |
|
1152 | - $id = \OC::$server->getSystemConfig()->getValue('instanceid', null); |
|
1153 | - if (is_null($id)) { |
|
1154 | - // We need to guarantee at least one letter in instanceid so it can be used as the session_name |
|
1155 | - $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS); |
|
1156 | - \OC::$server->getSystemConfig()->setValue('instanceid', $id); |
|
1157 | - } |
|
1158 | - return $id; |
|
1159 | - } |
|
1160 | - |
|
1161 | - /** |
|
1162 | - * Public function to sanitize HTML |
|
1163 | - * |
|
1164 | - * This function is used to sanitize HTML and should be applied on any |
|
1165 | - * string or array of strings before displaying it on a web page. |
|
1166 | - * |
|
1167 | - * @param string|array $value |
|
1168 | - * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter. |
|
1169 | - */ |
|
1170 | - public static function sanitizeHTML($value) { |
|
1171 | - if (is_array($value)) { |
|
1172 | - $value = array_map(function ($value) { |
|
1173 | - return self::sanitizeHTML($value); |
|
1174 | - }, $value); |
|
1175 | - } else { |
|
1176 | - // Specify encoding for PHP<5.4 |
|
1177 | - $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); |
|
1178 | - } |
|
1179 | - return $value; |
|
1180 | - } |
|
1181 | - |
|
1182 | - /** |
|
1183 | - * Public function to encode url parameters |
|
1184 | - * |
|
1185 | - * This function is used to encode path to file before output. |
|
1186 | - * Encoding is done according to RFC 3986 with one exception: |
|
1187 | - * Character '/' is preserved as is. |
|
1188 | - * |
|
1189 | - * @param string $component part of URI to encode |
|
1190 | - * @return string |
|
1191 | - */ |
|
1192 | - public static function encodePath($component) { |
|
1193 | - $encoded = rawurlencode($component); |
|
1194 | - $encoded = str_replace('%2F', '/', $encoded); |
|
1195 | - return $encoded; |
|
1196 | - } |
|
1197 | - |
|
1198 | - |
|
1199 | - public function createHtaccessTestFile(\OCP\IConfig $config) { |
|
1200 | - // php dev server does not support htaccess |
|
1201 | - if (php_sapi_name() === 'cli-server') { |
|
1202 | - return false; |
|
1203 | - } |
|
1204 | - |
|
1205 | - // testdata |
|
1206 | - $fileName = '/htaccesstest.txt'; |
|
1207 | - $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.'; |
|
1208 | - |
|
1209 | - // creating a test file |
|
1210 | - $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName; |
|
1211 | - |
|
1212 | - if (file_exists($testFile)) {// already running this test, possible recursive call |
|
1213 | - return false; |
|
1214 | - } |
|
1215 | - |
|
1216 | - $fp = @fopen($testFile, 'w'); |
|
1217 | - if (!$fp) { |
|
1218 | - throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.', |
|
1219 | - 'Make sure it is possible for the webserver to write to ' . $testFile); |
|
1220 | - } |
|
1221 | - fwrite($fp, $testContent); |
|
1222 | - fclose($fp); |
|
1223 | - |
|
1224 | - return $testContent; |
|
1225 | - } |
|
1226 | - |
|
1227 | - /** |
|
1228 | - * Check if the .htaccess file is working |
|
1229 | - * |
|
1230 | - * @param \OCP\IConfig $config |
|
1231 | - * @return bool |
|
1232 | - * @throws Exception |
|
1233 | - * @throws \OCP\HintException If the test file can't get written. |
|
1234 | - */ |
|
1235 | - public function isHtaccessWorking(\OCP\IConfig $config) { |
|
1236 | - if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) { |
|
1237 | - return true; |
|
1238 | - } |
|
1239 | - |
|
1240 | - $testContent = $this->createHtaccessTestFile($config); |
|
1241 | - if ($testContent === false) { |
|
1242 | - return false; |
|
1243 | - } |
|
1244 | - |
|
1245 | - $fileName = '/htaccesstest.txt'; |
|
1246 | - $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName; |
|
1247 | - |
|
1248 | - // accessing the file via http |
|
1249 | - $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName); |
|
1250 | - try { |
|
1251 | - $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody(); |
|
1252 | - } catch (\Exception $e) { |
|
1253 | - $content = false; |
|
1254 | - } |
|
1255 | - |
|
1256 | - if (strpos($url, 'https:') === 0) { |
|
1257 | - $url = 'http:' . substr($url, 6); |
|
1258 | - } else { |
|
1259 | - $url = 'https:' . substr($url, 5); |
|
1260 | - } |
|
1261 | - |
|
1262 | - try { |
|
1263 | - $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody(); |
|
1264 | - } catch (\Exception $e) { |
|
1265 | - $fallbackContent = false; |
|
1266 | - } |
|
1267 | - |
|
1268 | - // cleanup |
|
1269 | - @unlink($testFile); |
|
1270 | - |
|
1271 | - /* |
|
276 | + if ($mount->getOption('readonly', false)) { |
|
277 | + return new \OC\Files\Storage\Wrapper\PermissionsMask([ |
|
278 | + 'storage' => $storage, |
|
279 | + 'mask' => \OCP\Constants::PERMISSION_ALL & ~( |
|
280 | + \OCP\Constants::PERMISSION_UPDATE | |
|
281 | + \OCP\Constants::PERMISSION_CREATE | |
|
282 | + \OCP\Constants::PERMISSION_DELETE |
|
283 | + ), |
|
284 | + ]); |
|
285 | + } |
|
286 | + return $storage; |
|
287 | + }); |
|
288 | + |
|
289 | + OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]); |
|
290 | + |
|
291 | + \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging); |
|
292 | + |
|
293 | + //check if we are using an object storage |
|
294 | + $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null); |
|
295 | + $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null); |
|
296 | + |
|
297 | + // use the same order as in ObjectHomeMountProvider |
|
298 | + if (isset($objectStoreMultibucket)) { |
|
299 | + self::initObjectStoreMultibucketRootFS($objectStoreMultibucket); |
|
300 | + } elseif (isset($objectStore)) { |
|
301 | + self::initObjectStoreRootFS($objectStore); |
|
302 | + } else { |
|
303 | + self::initLocalStorageRootFS(); |
|
304 | + } |
|
305 | + |
|
306 | + /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */ |
|
307 | + $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class); |
|
308 | + $rootMountProviders = $mountProviderCollection->getRootMounts(); |
|
309 | + |
|
310 | + /** @var \OC\Files\Mount\Manager $mountManager */ |
|
311 | + $mountManager = \OC\Files\Filesystem::getMountManager(); |
|
312 | + foreach ($rootMountProviders as $rootMountProvider) { |
|
313 | + $mountManager->addMount($rootMountProvider); |
|
314 | + } |
|
315 | + |
|
316 | + if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) { |
|
317 | + \OC::$server->getEventLogger()->end('setup_fs'); |
|
318 | + return false; |
|
319 | + } |
|
320 | + |
|
321 | + //if we aren't logged in, there is no use to set up the filesystem |
|
322 | + if ($user != "") { |
|
323 | + $userDir = '/' . $user . '/files'; |
|
324 | + |
|
325 | + //jail the user into his "home" directory |
|
326 | + \OC\Files\Filesystem::init($user, $userDir); |
|
327 | + |
|
328 | + OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]); |
|
329 | + } |
|
330 | + \OC::$server->getEventLogger()->end('setup_fs'); |
|
331 | + return true; |
|
332 | + } |
|
333 | + |
|
334 | + /** |
|
335 | + * check if a password is required for each public link |
|
336 | + * |
|
337 | + * @return boolean |
|
338 | + * @suppress PhanDeprecatedFunction |
|
339 | + */ |
|
340 | + public static function isPublicLinkPasswordRequired() { |
|
341 | + /** @var IManager $shareManager */ |
|
342 | + $shareManager = \OC::$server->get(IManager::class); |
|
343 | + return $shareManager->shareApiLinkEnforcePassword(); |
|
344 | + } |
|
345 | + |
|
346 | + /** |
|
347 | + * check if sharing is disabled for the current user |
|
348 | + * @param IConfig $config |
|
349 | + * @param IGroupManager $groupManager |
|
350 | + * @param IUser|null $user |
|
351 | + * @return bool |
|
352 | + */ |
|
353 | + public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) { |
|
354 | + /** @var IManager $shareManager */ |
|
355 | + $shareManager = \OC::$server->get(IManager::class); |
|
356 | + $userId = $user ? $user->getUID() : null; |
|
357 | + return $shareManager->sharingDisabledForUser($userId); |
|
358 | + } |
|
359 | + |
|
360 | + /** |
|
361 | + * check if share API enforces a default expire date |
|
362 | + * |
|
363 | + * @return boolean |
|
364 | + * @suppress PhanDeprecatedFunction |
|
365 | + */ |
|
366 | + public static function isDefaultExpireDateEnforced() { |
|
367 | + /** @var IManager $shareManager */ |
|
368 | + $shareManager = \OC::$server->get(IManager::class); |
|
369 | + return $shareManager->shareApiLinkDefaultExpireDateEnforced(); |
|
370 | + } |
|
371 | + |
|
372 | + /** |
|
373 | + * Get the quota of a user |
|
374 | + * |
|
375 | + * @param IUser|null $user |
|
376 | + * @return float Quota bytes |
|
377 | + */ |
|
378 | + public static function getUserQuota(?IUser $user) { |
|
379 | + if (is_null($user)) { |
|
380 | + return \OCP\Files\FileInfo::SPACE_UNLIMITED; |
|
381 | + } |
|
382 | + $userQuota = $user->getQuota(); |
|
383 | + if ($userQuota === 'none') { |
|
384 | + return \OCP\Files\FileInfo::SPACE_UNLIMITED; |
|
385 | + } |
|
386 | + return OC_Helper::computerFileSize($userQuota); |
|
387 | + } |
|
388 | + |
|
389 | + /** |
|
390 | + * copies the skeleton to the users /files |
|
391 | + * |
|
392 | + * @param string $userId |
|
393 | + * @param \OCP\Files\Folder $userDirectory |
|
394 | + * @throws \OCP\Files\NotFoundException |
|
395 | + * @throws \OCP\Files\NotPermittedException |
|
396 | + * @suppress PhanDeprecatedFunction |
|
397 | + */ |
|
398 | + public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) { |
|
399 | + /** @var LoggerInterface $logger */ |
|
400 | + $logger = \OC::$server->get(LoggerInterface::class); |
|
401 | + |
|
402 | + $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton'); |
|
403 | + $userLang = \OC::$server->getL10NFactory()->findLanguage(); |
|
404 | + $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory); |
|
405 | + |
|
406 | + if (!file_exists($skeletonDirectory)) { |
|
407 | + $dialectStart = strpos($userLang, '_'); |
|
408 | + if ($dialectStart !== false) { |
|
409 | + $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory); |
|
410 | + } |
|
411 | + if ($dialectStart === false || !file_exists($skeletonDirectory)) { |
|
412 | + $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory); |
|
413 | + } |
|
414 | + if (!file_exists($skeletonDirectory)) { |
|
415 | + $skeletonDirectory = ''; |
|
416 | + } |
|
417 | + } |
|
418 | + |
|
419 | + $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', ''); |
|
420 | + |
|
421 | + if ($instanceId === null) { |
|
422 | + throw new \RuntimeException('no instance id!'); |
|
423 | + } |
|
424 | + $appdata = 'appdata_' . $instanceId; |
|
425 | + if ($userId === $appdata) { |
|
426 | + throw new \RuntimeException('username is reserved name: ' . $appdata); |
|
427 | + } |
|
428 | + |
|
429 | + if (!empty($skeletonDirectory)) { |
|
430 | + $logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']); |
|
431 | + self::copyr($skeletonDirectory, $userDirectory); |
|
432 | + // update the file cache |
|
433 | + $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE); |
|
434 | + |
|
435 | + /** @var ITemplateManager $templateManager */ |
|
436 | + $templateManager = \OC::$server->get(ITemplateManager::class); |
|
437 | + $templateManager->initializeTemplateDirectory(null, $userId); |
|
438 | + } |
|
439 | + } |
|
440 | + |
|
441 | + /** |
|
442 | + * copies a directory recursively by using streams |
|
443 | + * |
|
444 | + * @param string $source |
|
445 | + * @param \OCP\Files\Folder $target |
|
446 | + * @return void |
|
447 | + */ |
|
448 | + public static function copyr($source, \OCP\Files\Folder $target) { |
|
449 | + $logger = \OC::$server->getLogger(); |
|
450 | + |
|
451 | + // Verify if folder exists |
|
452 | + $dir = opendir($source); |
|
453 | + if ($dir === false) { |
|
454 | + $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']); |
|
455 | + return; |
|
456 | + } |
|
457 | + |
|
458 | + // Copy the files |
|
459 | + while (false !== ($file = readdir($dir))) { |
|
460 | + if (!\OC\Files\Filesystem::isIgnoredDir($file)) { |
|
461 | + if (is_dir($source . '/' . $file)) { |
|
462 | + $child = $target->newFolder($file); |
|
463 | + self::copyr($source . '/' . $file, $child); |
|
464 | + } else { |
|
465 | + $child = $target->newFile($file); |
|
466 | + $sourceStream = fopen($source . '/' . $file, 'r'); |
|
467 | + if ($sourceStream === false) { |
|
468 | + $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']); |
|
469 | + closedir($dir); |
|
470 | + return; |
|
471 | + } |
|
472 | + stream_copy_to_stream($sourceStream, $child->fopen('w')); |
|
473 | + } |
|
474 | + } |
|
475 | + } |
|
476 | + closedir($dir); |
|
477 | + } |
|
478 | + |
|
479 | + /** |
|
480 | + * @return void |
|
481 | + * @suppress PhanUndeclaredMethod |
|
482 | + */ |
|
483 | + public static function tearDownFS() { |
|
484 | + \OC\Files\Filesystem::tearDown(); |
|
485 | + \OC::$server->getRootFolder()->clearCache(); |
|
486 | + self::$fsSetup = false; |
|
487 | + self::$rootMounted = false; |
|
488 | + } |
|
489 | + |
|
490 | + /** |
|
491 | + * get the current installed version of ownCloud |
|
492 | + * |
|
493 | + * @return array |
|
494 | + */ |
|
495 | + public static function getVersion() { |
|
496 | + OC_Util::loadVersion(); |
|
497 | + return self::$versionCache['OC_Version']; |
|
498 | + } |
|
499 | + |
|
500 | + /** |
|
501 | + * get the current installed version string of ownCloud |
|
502 | + * |
|
503 | + * @return string |
|
504 | + */ |
|
505 | + public static function getVersionString() { |
|
506 | + OC_Util::loadVersion(); |
|
507 | + return self::$versionCache['OC_VersionString']; |
|
508 | + } |
|
509 | + |
|
510 | + /** |
|
511 | + * @deprecated the value is of no use anymore |
|
512 | + * @return string |
|
513 | + */ |
|
514 | + public static function getEditionString() { |
|
515 | + return ''; |
|
516 | + } |
|
517 | + |
|
518 | + /** |
|
519 | + * @description get the update channel of the current installed of ownCloud. |
|
520 | + * @return string |
|
521 | + */ |
|
522 | + public static function getChannel() { |
|
523 | + OC_Util::loadVersion(); |
|
524 | + return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']); |
|
525 | + } |
|
526 | + |
|
527 | + /** |
|
528 | + * @description get the build number of the current installed of ownCloud. |
|
529 | + * @return string |
|
530 | + */ |
|
531 | + public static function getBuild() { |
|
532 | + OC_Util::loadVersion(); |
|
533 | + return self::$versionCache['OC_Build']; |
|
534 | + } |
|
535 | + |
|
536 | + /** |
|
537 | + * @description load the version.php into the session as cache |
|
538 | + * @suppress PhanUndeclaredVariable |
|
539 | + */ |
|
540 | + private static function loadVersion() { |
|
541 | + if (self::$versionCache !== null) { |
|
542 | + return; |
|
543 | + } |
|
544 | + |
|
545 | + $timestamp = filemtime(OC::$SERVERROOT . '/version.php'); |
|
546 | + require OC::$SERVERROOT . '/version.php'; |
|
547 | + /** @var int $timestamp */ |
|
548 | + self::$versionCache['OC_Version_Timestamp'] = $timestamp; |
|
549 | + /** @var string $OC_Version */ |
|
550 | + self::$versionCache['OC_Version'] = $OC_Version; |
|
551 | + /** @var string $OC_VersionString */ |
|
552 | + self::$versionCache['OC_VersionString'] = $OC_VersionString; |
|
553 | + /** @var string $OC_Build */ |
|
554 | + self::$versionCache['OC_Build'] = $OC_Build; |
|
555 | + |
|
556 | + /** @var string $OC_Channel */ |
|
557 | + self::$versionCache['OC_Channel'] = $OC_Channel; |
|
558 | + } |
|
559 | + |
|
560 | + /** |
|
561 | + * generates a path for JS/CSS files. If no application is provided it will create the path for core. |
|
562 | + * |
|
563 | + * @param string $application application to get the files from |
|
564 | + * @param string $directory directory within this application (css, js, vendor, etc) |
|
565 | + * @param string $file the file inside of the above folder |
|
566 | + * @return string the path |
|
567 | + */ |
|
568 | + private static function generatePath($application, $directory, $file) { |
|
569 | + if (is_null($file)) { |
|
570 | + $file = $application; |
|
571 | + $application = ""; |
|
572 | + } |
|
573 | + if (!empty($application)) { |
|
574 | + return "$application/$directory/$file"; |
|
575 | + } else { |
|
576 | + return "$directory/$file"; |
|
577 | + } |
|
578 | + } |
|
579 | + |
|
580 | + /** |
|
581 | + * add a javascript file |
|
582 | + * |
|
583 | + * @param string $application application id |
|
584 | + * @param string|null $file filename |
|
585 | + * @param bool $prepend prepend the Script to the beginning of the list |
|
586 | + * @return void |
|
587 | + */ |
|
588 | + public static function addScript($application, $file = null, $prepend = false) { |
|
589 | + $path = OC_Util::generatePath($application, 'js', $file); |
|
590 | + |
|
591 | + // core js files need separate handling |
|
592 | + if ($application !== 'core' && $file !== null) { |
|
593 | + self::addTranslations($application); |
|
594 | + } |
|
595 | + self::addExternalResource($application, $prepend, $path, "script"); |
|
596 | + } |
|
597 | + |
|
598 | + /** |
|
599 | + * add a javascript file from the vendor sub folder |
|
600 | + * |
|
601 | + * @param string $application application id |
|
602 | + * @param string|null $file filename |
|
603 | + * @param bool $prepend prepend the Script to the beginning of the list |
|
604 | + * @return void |
|
605 | + */ |
|
606 | + public static function addVendorScript($application, $file = null, $prepend = false) { |
|
607 | + $path = OC_Util::generatePath($application, 'vendor', $file); |
|
608 | + self::addExternalResource($application, $prepend, $path, "script"); |
|
609 | + } |
|
610 | + |
|
611 | + /** |
|
612 | + * add a translation JS file |
|
613 | + * |
|
614 | + * @param string $application application id |
|
615 | + * @param string|null $languageCode language code, defaults to the current language |
|
616 | + * @param bool|null $prepend prepend the Script to the beginning of the list |
|
617 | + */ |
|
618 | + public static function addTranslations($application, $languageCode = null, $prepend = false) { |
|
619 | + if (is_null($languageCode)) { |
|
620 | + $languageCode = \OC::$server->getL10NFactory()->findLanguage($application); |
|
621 | + } |
|
622 | + if (!empty($application)) { |
|
623 | + $path = "$application/l10n/$languageCode"; |
|
624 | + } else { |
|
625 | + $path = "l10n/$languageCode"; |
|
626 | + } |
|
627 | + self::addExternalResource($application, $prepend, $path, "script"); |
|
628 | + } |
|
629 | + |
|
630 | + /** |
|
631 | + * add a css file |
|
632 | + * |
|
633 | + * @param string $application application id |
|
634 | + * @param string|null $file filename |
|
635 | + * @param bool $prepend prepend the Style to the beginning of the list |
|
636 | + * @return void |
|
637 | + */ |
|
638 | + public static function addStyle($application, $file = null, $prepend = false) { |
|
639 | + $path = OC_Util::generatePath($application, 'css', $file); |
|
640 | + self::addExternalResource($application, $prepend, $path, "style"); |
|
641 | + } |
|
642 | + |
|
643 | + /** |
|
644 | + * add a css file from the vendor sub folder |
|
645 | + * |
|
646 | + * @param string $application application id |
|
647 | + * @param string|null $file filename |
|
648 | + * @param bool $prepend prepend the Style to the beginning of the list |
|
649 | + * @return void |
|
650 | + */ |
|
651 | + public static function addVendorStyle($application, $file = null, $prepend = false) { |
|
652 | + $path = OC_Util::generatePath($application, 'vendor', $file); |
|
653 | + self::addExternalResource($application, $prepend, $path, "style"); |
|
654 | + } |
|
655 | + |
|
656 | + /** |
|
657 | + * add an external resource css/js file |
|
658 | + * |
|
659 | + * @param string $application application id |
|
660 | + * @param bool $prepend prepend the file to the beginning of the list |
|
661 | + * @param string $path |
|
662 | + * @param string $type (script or style) |
|
663 | + * @return void |
|
664 | + */ |
|
665 | + private static function addExternalResource($application, $prepend, $path, $type = "script") { |
|
666 | + if ($type === "style") { |
|
667 | + if (!in_array($path, self::$styles)) { |
|
668 | + if ($prepend === true) { |
|
669 | + array_unshift(self::$styles, $path); |
|
670 | + } else { |
|
671 | + self::$styles[] = $path; |
|
672 | + } |
|
673 | + } |
|
674 | + } elseif ($type === "script") { |
|
675 | + if (!in_array($path, self::$scripts)) { |
|
676 | + if ($prepend === true) { |
|
677 | + array_unshift(self::$scripts, $path); |
|
678 | + } else { |
|
679 | + self::$scripts [] = $path; |
|
680 | + } |
|
681 | + } |
|
682 | + } |
|
683 | + } |
|
684 | + |
|
685 | + /** |
|
686 | + * Add a custom element to the header |
|
687 | + * If $text is null then the element will be written as empty element. |
|
688 | + * So use "" to get a closing tag. |
|
689 | + * @param string $tag tag name of the element |
|
690 | + * @param array $attributes array of attributes for the element |
|
691 | + * @param string $text the text content for the element |
|
692 | + * @param bool $prepend prepend the header to the beginning of the list |
|
693 | + */ |
|
694 | + public static function addHeader($tag, $attributes, $text = null, $prepend = false) { |
|
695 | + $header = [ |
|
696 | + 'tag' => $tag, |
|
697 | + 'attributes' => $attributes, |
|
698 | + 'text' => $text |
|
699 | + ]; |
|
700 | + if ($prepend === true) { |
|
701 | + array_unshift(self::$headers, $header); |
|
702 | + } else { |
|
703 | + self::$headers[] = $header; |
|
704 | + } |
|
705 | + } |
|
706 | + |
|
707 | + /** |
|
708 | + * check if the current server configuration is suitable for ownCloud |
|
709 | + * |
|
710 | + * @param \OC\SystemConfig $config |
|
711 | + * @return array arrays with error messages and hints |
|
712 | + */ |
|
713 | + public static function checkServer(\OC\SystemConfig $config) { |
|
714 | + $l = \OC::$server->getL10N('lib'); |
|
715 | + $errors = []; |
|
716 | + $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data'); |
|
717 | + |
|
718 | + if (!self::needUpgrade($config) && $config->getValue('installed', false)) { |
|
719 | + // this check needs to be done every time |
|
720 | + $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY); |
|
721 | + } |
|
722 | + |
|
723 | + // Assume that if checkServer() succeeded before in this session, then all is fine. |
|
724 | + if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) { |
|
725 | + return $errors; |
|
726 | + } |
|
727 | + |
|
728 | + $webServerRestart = false; |
|
729 | + $setup = new \OC\Setup( |
|
730 | + $config, |
|
731 | + \OC::$server->get(IniGetWrapper::class), |
|
732 | + \OC::$server->getL10N('lib'), |
|
733 | + \OC::$server->get(\OCP\Defaults::class), |
|
734 | + \OC::$server->get(LoggerInterface::class), |
|
735 | + \OC::$server->getSecureRandom(), |
|
736 | + \OC::$server->get(\OC\Installer::class) |
|
737 | + ); |
|
738 | + |
|
739 | + $urlGenerator = \OC::$server->getURLGenerator(); |
|
740 | + |
|
741 | + $availableDatabases = $setup->getSupportedDatabases(); |
|
742 | + if (empty($availableDatabases)) { |
|
743 | + $errors[] = [ |
|
744 | + 'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'), |
|
745 | + 'hint' => '' //TODO: sane hint |
|
746 | + ]; |
|
747 | + $webServerRestart = true; |
|
748 | + } |
|
749 | + |
|
750 | + // Check if config folder is writable. |
|
751 | + if (!OC_Helper::isReadOnlyConfigEnabled()) { |
|
752 | + if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) { |
|
753 | + $errors[] = [ |
|
754 | + 'error' => $l->t('Cannot write into "config" directory'), |
|
755 | + 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s', |
|
756 | + [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. ' |
|
757 | + . $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', |
|
758 | + [ $urlGenerator->linkToDocs('admin-config') ]) |
|
759 | + ]; |
|
760 | + } |
|
761 | + } |
|
762 | + |
|
763 | + // Check if there is a writable install folder. |
|
764 | + if ($config->getValue('appstoreenabled', true)) { |
|
765 | + if (OC_App::getInstallPath() === null |
|
766 | + || !is_writable(OC_App::getInstallPath()) |
|
767 | + || !is_readable(OC_App::getInstallPath()) |
|
768 | + ) { |
|
769 | + $errors[] = [ |
|
770 | + 'error' => $l->t('Cannot write into "apps" directory'), |
|
771 | + 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory' |
|
772 | + . ' or disabling the App Store in the config file.') |
|
773 | + ]; |
|
774 | + } |
|
775 | + } |
|
776 | + // Create root dir. |
|
777 | + if ($config->getValue('installed', false)) { |
|
778 | + if (!is_dir($CONFIG_DATADIRECTORY)) { |
|
779 | + $success = @mkdir($CONFIG_DATADIRECTORY); |
|
780 | + if ($success) { |
|
781 | + $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY)); |
|
782 | + } else { |
|
783 | + $errors[] = [ |
|
784 | + 'error' => $l->t('Cannot create "data" directory'), |
|
785 | + 'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s', |
|
786 | + [$urlGenerator->linkToDocs('admin-dir_permissions')]) |
|
787 | + ]; |
|
788 | + } |
|
789 | + } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) { |
|
790 | + // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists. |
|
791 | + $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_')); |
|
792 | + $handle = fopen($testFile, 'w'); |
|
793 | + if (!$handle || fwrite($handle, 'Test write operation') === false) { |
|
794 | + $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.', |
|
795 | + [$urlGenerator->linkToDocs('admin-dir_permissions')]); |
|
796 | + $errors[] = [ |
|
797 | + 'error' => 'Your data directory is not writable', |
|
798 | + 'hint' => $permissionsHint |
|
799 | + ]; |
|
800 | + } else { |
|
801 | + fclose($handle); |
|
802 | + unlink($testFile); |
|
803 | + } |
|
804 | + } else { |
|
805 | + $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY)); |
|
806 | + } |
|
807 | + } |
|
808 | + |
|
809 | + if (!OC_Util::isSetLocaleWorking()) { |
|
810 | + $errors[] = [ |
|
811 | + 'error' => $l->t('Setting locale to %s failed', |
|
812 | + ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/' |
|
813 | + . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']), |
|
814 | + 'hint' => $l->t('Please install one of these locales on your system and restart your webserver.') |
|
815 | + ]; |
|
816 | + } |
|
817 | + |
|
818 | + // Contains the dependencies that should be checked against |
|
819 | + // classes = class_exists |
|
820 | + // functions = function_exists |
|
821 | + // defined = defined |
|
822 | + // ini = ini_get |
|
823 | + // If the dependency is not found the missing module name is shown to the EndUser |
|
824 | + // When adding new checks always verify that they pass on Travis as well |
|
825 | + // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini |
|
826 | + $dependencies = [ |
|
827 | + 'classes' => [ |
|
828 | + 'ZipArchive' => 'zip', |
|
829 | + 'DOMDocument' => 'dom', |
|
830 | + 'XMLWriter' => 'XMLWriter', |
|
831 | + 'XMLReader' => 'XMLReader', |
|
832 | + ], |
|
833 | + 'functions' => [ |
|
834 | + 'xml_parser_create' => 'libxml', |
|
835 | + 'mb_strcut' => 'mbstring', |
|
836 | + 'ctype_digit' => 'ctype', |
|
837 | + 'json_encode' => 'JSON', |
|
838 | + 'gd_info' => 'GD', |
|
839 | + 'gzencode' => 'zlib', |
|
840 | + 'iconv' => 'iconv', |
|
841 | + 'simplexml_load_string' => 'SimpleXML', |
|
842 | + 'hash' => 'HASH Message Digest Framework', |
|
843 | + 'curl_init' => 'cURL', |
|
844 | + 'openssl_verify' => 'OpenSSL', |
|
845 | + ], |
|
846 | + 'defined' => [ |
|
847 | + 'PDO::ATTR_DRIVER_NAME' => 'PDO' |
|
848 | + ], |
|
849 | + 'ini' => [ |
|
850 | + 'default_charset' => 'UTF-8', |
|
851 | + ], |
|
852 | + ]; |
|
853 | + $missingDependencies = []; |
|
854 | + $invalidIniSettings = []; |
|
855 | + |
|
856 | + $iniWrapper = \OC::$server->get(IniGetWrapper::class); |
|
857 | + foreach ($dependencies['classes'] as $class => $module) { |
|
858 | + if (!class_exists($class)) { |
|
859 | + $missingDependencies[] = $module; |
|
860 | + } |
|
861 | + } |
|
862 | + foreach ($dependencies['functions'] as $function => $module) { |
|
863 | + if (!function_exists($function)) { |
|
864 | + $missingDependencies[] = $module; |
|
865 | + } |
|
866 | + } |
|
867 | + foreach ($dependencies['defined'] as $defined => $module) { |
|
868 | + if (!defined($defined)) { |
|
869 | + $missingDependencies[] = $module; |
|
870 | + } |
|
871 | + } |
|
872 | + foreach ($dependencies['ini'] as $setting => $expected) { |
|
873 | + if (is_bool($expected)) { |
|
874 | + if ($iniWrapper->getBool($setting) !== $expected) { |
|
875 | + $invalidIniSettings[] = [$setting, $expected]; |
|
876 | + } |
|
877 | + } |
|
878 | + if (is_int($expected)) { |
|
879 | + if ($iniWrapper->getNumeric($setting) !== $expected) { |
|
880 | + $invalidIniSettings[] = [$setting, $expected]; |
|
881 | + } |
|
882 | + } |
|
883 | + if (is_string($expected)) { |
|
884 | + if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) { |
|
885 | + $invalidIniSettings[] = [$setting, $expected]; |
|
886 | + } |
|
887 | + } |
|
888 | + } |
|
889 | + |
|
890 | + foreach ($missingDependencies as $missingDependency) { |
|
891 | + $errors[] = [ |
|
892 | + 'error' => $l->t('PHP module %s not installed.', [$missingDependency]), |
|
893 | + 'hint' => $l->t('Please ask your server administrator to install the module.'), |
|
894 | + ]; |
|
895 | + $webServerRestart = true; |
|
896 | + } |
|
897 | + foreach ($invalidIniSettings as $setting) { |
|
898 | + if (is_bool($setting[1])) { |
|
899 | + $setting[1] = $setting[1] ? 'on' : 'off'; |
|
900 | + } |
|
901 | + $errors[] = [ |
|
902 | + 'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]), |
|
903 | + 'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again') |
|
904 | + ]; |
|
905 | + $webServerRestart = true; |
|
906 | + } |
|
907 | + |
|
908 | + /** |
|
909 | + * The mbstring.func_overload check can only be performed if the mbstring |
|
910 | + * module is installed as it will return null if the checking setting is |
|
911 | + * not available and thus a check on the boolean value fails. |
|
912 | + * |
|
913 | + * TODO: Should probably be implemented in the above generic dependency |
|
914 | + * check somehow in the long-term. |
|
915 | + */ |
|
916 | + if ($iniWrapper->getBool('mbstring.func_overload') !== null && |
|
917 | + $iniWrapper->getBool('mbstring.func_overload') === true) { |
|
918 | + $errors[] = [ |
|
919 | + 'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]), |
|
920 | + 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini') |
|
921 | + ]; |
|
922 | + } |
|
923 | + |
|
924 | + if (function_exists('xml_parser_create') && |
|
925 | + LIBXML_LOADED_VERSION < 20700) { |
|
926 | + $version = LIBXML_LOADED_VERSION; |
|
927 | + $major = floor($version / 10000); |
|
928 | + $version -= ($major * 10000); |
|
929 | + $minor = floor($version / 100); |
|
930 | + $version -= ($minor * 100); |
|
931 | + $patch = $version; |
|
932 | + $errors[] = [ |
|
933 | + 'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]), |
|
934 | + 'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.') |
|
935 | + ]; |
|
936 | + } |
|
937 | + |
|
938 | + if (!self::isAnnotationsWorking()) { |
|
939 | + $errors[] = [ |
|
940 | + 'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'), |
|
941 | + 'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.') |
|
942 | + ]; |
|
943 | + } |
|
944 | + |
|
945 | + if (!\OC::$CLI && $webServerRestart) { |
|
946 | + $errors[] = [ |
|
947 | + 'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'), |
|
948 | + 'hint' => $l->t('Please ask your server administrator to restart the web server.') |
|
949 | + ]; |
|
950 | + } |
|
951 | + |
|
952 | + $errors = array_merge($errors, self::checkDatabaseVersion()); |
|
953 | + |
|
954 | + // Cache the result of this function |
|
955 | + \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0); |
|
956 | + |
|
957 | + return $errors; |
|
958 | + } |
|
959 | + |
|
960 | + /** |
|
961 | + * Check the database version |
|
962 | + * |
|
963 | + * @return array errors array |
|
964 | + */ |
|
965 | + public static function checkDatabaseVersion() { |
|
966 | + $l = \OC::$server->getL10N('lib'); |
|
967 | + $errors = []; |
|
968 | + $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite'); |
|
969 | + if ($dbType === 'pgsql') { |
|
970 | + // check PostgreSQL version |
|
971 | + try { |
|
972 | + $result = \OC_DB::executeAudited('SHOW SERVER_VERSION'); |
|
973 | + $data = $result->fetchRow(); |
|
974 | + $result->closeCursor(); |
|
975 | + if (isset($data['server_version'])) { |
|
976 | + $version = $data['server_version']; |
|
977 | + if (version_compare($version, '9.0.0', '<')) { |
|
978 | + $errors[] = [ |
|
979 | + 'error' => $l->t('PostgreSQL >= 9 required'), |
|
980 | + 'hint' => $l->t('Please upgrade your database version') |
|
981 | + ]; |
|
982 | + } |
|
983 | + } |
|
984 | + } catch (\Doctrine\DBAL\Exception $e) { |
|
985 | + $logger = \OC::$server->getLogger(); |
|
986 | + $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9'); |
|
987 | + $logger->logException($e); |
|
988 | + } |
|
989 | + } |
|
990 | + return $errors; |
|
991 | + } |
|
992 | + |
|
993 | + /** |
|
994 | + * Check for correct file permissions of data directory |
|
995 | + * |
|
996 | + * @param string $dataDirectory |
|
997 | + * @return array arrays with error messages and hints |
|
998 | + */ |
|
999 | + public static function checkDataDirectoryPermissions($dataDirectory) { |
|
1000 | + if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) { |
|
1001 | + return []; |
|
1002 | + } |
|
1003 | + |
|
1004 | + $perms = substr(decoct(@fileperms($dataDirectory)), -3); |
|
1005 | + if (substr($perms, -1) !== '0') { |
|
1006 | + chmod($dataDirectory, 0770); |
|
1007 | + clearstatcache(); |
|
1008 | + $perms = substr(decoct(@fileperms($dataDirectory)), -3); |
|
1009 | + if ($perms[2] !== '0') { |
|
1010 | + $l = \OC::$server->getL10N('lib'); |
|
1011 | + return [[ |
|
1012 | + 'error' => $l->t('Your data directory is readable by other users'), |
|
1013 | + 'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'), |
|
1014 | + ]]; |
|
1015 | + } |
|
1016 | + } |
|
1017 | + return []; |
|
1018 | + } |
|
1019 | + |
|
1020 | + /** |
|
1021 | + * Check that the data directory exists and is valid by |
|
1022 | + * checking the existence of the ".ocdata" file. |
|
1023 | + * |
|
1024 | + * @param string $dataDirectory data directory path |
|
1025 | + * @return array errors found |
|
1026 | + */ |
|
1027 | + public static function checkDataDirectoryValidity($dataDirectory) { |
|
1028 | + $l = \OC::$server->getL10N('lib'); |
|
1029 | + $errors = []; |
|
1030 | + if ($dataDirectory[0] !== '/') { |
|
1031 | + $errors[] = [ |
|
1032 | + 'error' => $l->t('Your data directory must be an absolute path'), |
|
1033 | + 'hint' => $l->t('Check the value of "datadirectory" in your configuration') |
|
1034 | + ]; |
|
1035 | + } |
|
1036 | + if (!file_exists($dataDirectory . '/.ocdata')) { |
|
1037 | + $errors[] = [ |
|
1038 | + 'error' => $l->t('Your data directory is invalid'), |
|
1039 | + 'hint' => $l->t('Ensure there is a file called ".ocdata"' . |
|
1040 | + ' in the root of the data directory.') |
|
1041 | + ]; |
|
1042 | + } |
|
1043 | + return $errors; |
|
1044 | + } |
|
1045 | + |
|
1046 | + /** |
|
1047 | + * Check if the user is logged in, redirects to home if not. With |
|
1048 | + * redirect URL parameter to the request URI. |
|
1049 | + * |
|
1050 | + * @return void |
|
1051 | + */ |
|
1052 | + public static function checkLoggedIn() { |
|
1053 | + // Check if we are a user |
|
1054 | + if (!\OC::$server->getUserSession()->isLoggedIn()) { |
|
1055 | + header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute( |
|
1056 | + 'core.login.showLoginForm', |
|
1057 | + [ |
|
1058 | + 'redirect_url' => \OC::$server->getRequest()->getRequestUri(), |
|
1059 | + ] |
|
1060 | + ) |
|
1061 | + ); |
|
1062 | + exit(); |
|
1063 | + } |
|
1064 | + // Redirect to 2FA challenge selection if 2FA challenge was not solved yet |
|
1065 | + if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) { |
|
1066 | + header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge')); |
|
1067 | + exit(); |
|
1068 | + } |
|
1069 | + } |
|
1070 | + |
|
1071 | + /** |
|
1072 | + * Check if the user is a admin, redirects to home if not |
|
1073 | + * |
|
1074 | + * @return void |
|
1075 | + */ |
|
1076 | + public static function checkAdminUser() { |
|
1077 | + OC_Util::checkLoggedIn(); |
|
1078 | + if (!OC_User::isAdminUser(OC_User::getUser())) { |
|
1079 | + header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php')); |
|
1080 | + exit(); |
|
1081 | + } |
|
1082 | + } |
|
1083 | + |
|
1084 | + /** |
|
1085 | + * Returns the URL of the default page |
|
1086 | + * based on the system configuration and |
|
1087 | + * the apps visible for the current user |
|
1088 | + * |
|
1089 | + * @return string URL |
|
1090 | + * @suppress PhanDeprecatedFunction |
|
1091 | + */ |
|
1092 | + public static function getDefaultPageUrl() { |
|
1093 | + /** @var IConfig $config */ |
|
1094 | + $config = \OC::$server->get(IConfig::class); |
|
1095 | + $urlGenerator = \OC::$server->getURLGenerator(); |
|
1096 | + // Deny the redirect if the URL contains a @ |
|
1097 | + // This prevents unvalidated redirects like ?redirect_url=:[email protected] |
|
1098 | + if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) { |
|
1099 | + $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url'])); |
|
1100 | + } else { |
|
1101 | + $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage'); |
|
1102 | + if ($defaultPage) { |
|
1103 | + $location = $urlGenerator->getAbsoluteURL($defaultPage); |
|
1104 | + } else { |
|
1105 | + $appId = 'files'; |
|
1106 | + $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files')); |
|
1107 | + |
|
1108 | + /** @var IUserSession $userSession */ |
|
1109 | + $userSession = \OC::$server->get(IUserSession::class); |
|
1110 | + $user = $userSession->getUser(); |
|
1111 | + if ($user) { |
|
1112 | + $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp')); |
|
1113 | + $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps)); |
|
1114 | + } |
|
1115 | + |
|
1116 | + // find the first app that is enabled for the current user |
|
1117 | + foreach ($defaultApps as $defaultApp) { |
|
1118 | + $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp)); |
|
1119 | + if (static::getAppManager()->isEnabledForUser($defaultApp)) { |
|
1120 | + $appId = $defaultApp; |
|
1121 | + break; |
|
1122 | + } |
|
1123 | + } |
|
1124 | + |
|
1125 | + if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') { |
|
1126 | + $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/'); |
|
1127 | + } else { |
|
1128 | + $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/'); |
|
1129 | + } |
|
1130 | + } |
|
1131 | + } |
|
1132 | + return $location; |
|
1133 | + } |
|
1134 | + |
|
1135 | + /** |
|
1136 | + * Redirect to the user default page |
|
1137 | + * |
|
1138 | + * @return void |
|
1139 | + */ |
|
1140 | + public static function redirectToDefaultPage() { |
|
1141 | + $location = self::getDefaultPageUrl(); |
|
1142 | + header('Location: ' . $location); |
|
1143 | + exit(); |
|
1144 | + } |
|
1145 | + |
|
1146 | + /** |
|
1147 | + * get an id unique for this instance |
|
1148 | + * |
|
1149 | + * @return string |
|
1150 | + */ |
|
1151 | + public static function getInstanceId() { |
|
1152 | + $id = \OC::$server->getSystemConfig()->getValue('instanceid', null); |
|
1153 | + if (is_null($id)) { |
|
1154 | + // We need to guarantee at least one letter in instanceid so it can be used as the session_name |
|
1155 | + $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS); |
|
1156 | + \OC::$server->getSystemConfig()->setValue('instanceid', $id); |
|
1157 | + } |
|
1158 | + return $id; |
|
1159 | + } |
|
1160 | + |
|
1161 | + /** |
|
1162 | + * Public function to sanitize HTML |
|
1163 | + * |
|
1164 | + * This function is used to sanitize HTML and should be applied on any |
|
1165 | + * string or array of strings before displaying it on a web page. |
|
1166 | + * |
|
1167 | + * @param string|array $value |
|
1168 | + * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter. |
|
1169 | + */ |
|
1170 | + public static function sanitizeHTML($value) { |
|
1171 | + if (is_array($value)) { |
|
1172 | + $value = array_map(function ($value) { |
|
1173 | + return self::sanitizeHTML($value); |
|
1174 | + }, $value); |
|
1175 | + } else { |
|
1176 | + // Specify encoding for PHP<5.4 |
|
1177 | + $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); |
|
1178 | + } |
|
1179 | + return $value; |
|
1180 | + } |
|
1181 | + |
|
1182 | + /** |
|
1183 | + * Public function to encode url parameters |
|
1184 | + * |
|
1185 | + * This function is used to encode path to file before output. |
|
1186 | + * Encoding is done according to RFC 3986 with one exception: |
|
1187 | + * Character '/' is preserved as is. |
|
1188 | + * |
|
1189 | + * @param string $component part of URI to encode |
|
1190 | + * @return string |
|
1191 | + */ |
|
1192 | + public static function encodePath($component) { |
|
1193 | + $encoded = rawurlencode($component); |
|
1194 | + $encoded = str_replace('%2F', '/', $encoded); |
|
1195 | + return $encoded; |
|
1196 | + } |
|
1197 | + |
|
1198 | + |
|
1199 | + public function createHtaccessTestFile(\OCP\IConfig $config) { |
|
1200 | + // php dev server does not support htaccess |
|
1201 | + if (php_sapi_name() === 'cli-server') { |
|
1202 | + return false; |
|
1203 | + } |
|
1204 | + |
|
1205 | + // testdata |
|
1206 | + $fileName = '/htaccesstest.txt'; |
|
1207 | + $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.'; |
|
1208 | + |
|
1209 | + // creating a test file |
|
1210 | + $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName; |
|
1211 | + |
|
1212 | + if (file_exists($testFile)) {// already running this test, possible recursive call |
|
1213 | + return false; |
|
1214 | + } |
|
1215 | + |
|
1216 | + $fp = @fopen($testFile, 'w'); |
|
1217 | + if (!$fp) { |
|
1218 | + throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.', |
|
1219 | + 'Make sure it is possible for the webserver to write to ' . $testFile); |
|
1220 | + } |
|
1221 | + fwrite($fp, $testContent); |
|
1222 | + fclose($fp); |
|
1223 | + |
|
1224 | + return $testContent; |
|
1225 | + } |
|
1226 | + |
|
1227 | + /** |
|
1228 | + * Check if the .htaccess file is working |
|
1229 | + * |
|
1230 | + * @param \OCP\IConfig $config |
|
1231 | + * @return bool |
|
1232 | + * @throws Exception |
|
1233 | + * @throws \OCP\HintException If the test file can't get written. |
|
1234 | + */ |
|
1235 | + public function isHtaccessWorking(\OCP\IConfig $config) { |
|
1236 | + if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) { |
|
1237 | + return true; |
|
1238 | + } |
|
1239 | + |
|
1240 | + $testContent = $this->createHtaccessTestFile($config); |
|
1241 | + if ($testContent === false) { |
|
1242 | + return false; |
|
1243 | + } |
|
1244 | + |
|
1245 | + $fileName = '/htaccesstest.txt'; |
|
1246 | + $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName; |
|
1247 | + |
|
1248 | + // accessing the file via http |
|
1249 | + $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName); |
|
1250 | + try { |
|
1251 | + $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody(); |
|
1252 | + } catch (\Exception $e) { |
|
1253 | + $content = false; |
|
1254 | + } |
|
1255 | + |
|
1256 | + if (strpos($url, 'https:') === 0) { |
|
1257 | + $url = 'http:' . substr($url, 6); |
|
1258 | + } else { |
|
1259 | + $url = 'https:' . substr($url, 5); |
|
1260 | + } |
|
1261 | + |
|
1262 | + try { |
|
1263 | + $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody(); |
|
1264 | + } catch (\Exception $e) { |
|
1265 | + $fallbackContent = false; |
|
1266 | + } |
|
1267 | + |
|
1268 | + // cleanup |
|
1269 | + @unlink($testFile); |
|
1270 | + |
|
1271 | + /* |
|
1272 | 1272 | * If the content is not equal to test content our .htaccess |
1273 | 1273 | * is working as required |
1274 | 1274 | */ |
1275 | - return $content !== $testContent && $fallbackContent !== $testContent; |
|
1276 | - } |
|
1277 | - |
|
1278 | - /** |
|
1279 | - * Check if the setlocal call does not work. This can happen if the right |
|
1280 | - * local packages are not available on the server. |
|
1281 | - * |
|
1282 | - * @return bool |
|
1283 | - */ |
|
1284 | - public static function isSetLocaleWorking() { |
|
1285 | - if ('' === basename('§')) { |
|
1286 | - // Borrowed from \Patchwork\Utf8\Bootup::initLocale |
|
1287 | - setlocale(LC_ALL, 'C.UTF-8', 'C'); |
|
1288 | - setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0'); |
|
1289 | - } |
|
1290 | - |
|
1291 | - // Check again |
|
1292 | - if ('' === basename('§')) { |
|
1293 | - return false; |
|
1294 | - } |
|
1295 | - return true; |
|
1296 | - } |
|
1297 | - |
|
1298 | - /** |
|
1299 | - * Check if it's possible to get the inline annotations |
|
1300 | - * |
|
1301 | - * @return bool |
|
1302 | - */ |
|
1303 | - public static function isAnnotationsWorking() { |
|
1304 | - $reflection = new \ReflectionMethod(__METHOD__); |
|
1305 | - $docs = $reflection->getDocComment(); |
|
1306 | - |
|
1307 | - return (is_string($docs) && strlen($docs) > 50); |
|
1308 | - } |
|
1309 | - |
|
1310 | - /** |
|
1311 | - * Check if the PHP module fileinfo is loaded. |
|
1312 | - * |
|
1313 | - * @return bool |
|
1314 | - */ |
|
1315 | - public static function fileInfoLoaded() { |
|
1316 | - return function_exists('finfo_open'); |
|
1317 | - } |
|
1318 | - |
|
1319 | - /** |
|
1320 | - * clear all levels of output buffering |
|
1321 | - * |
|
1322 | - * @return void |
|
1323 | - */ |
|
1324 | - public static function obEnd() { |
|
1325 | - while (ob_get_level()) { |
|
1326 | - ob_end_clean(); |
|
1327 | - } |
|
1328 | - } |
|
1329 | - |
|
1330 | - /** |
|
1331 | - * Checks whether the server is running on Mac OS X |
|
1332 | - * |
|
1333 | - * @return bool true if running on Mac OS X, false otherwise |
|
1334 | - */ |
|
1335 | - public static function runningOnMac() { |
|
1336 | - return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN'); |
|
1337 | - } |
|
1338 | - |
|
1339 | - /** |
|
1340 | - * Handles the case that there may not be a theme, then check if a "default" |
|
1341 | - * theme exists and take that one |
|
1342 | - * |
|
1343 | - * @return string the theme |
|
1344 | - */ |
|
1345 | - public static function getTheme() { |
|
1346 | - $theme = \OC::$server->getSystemConfig()->getValue("theme", ''); |
|
1347 | - |
|
1348 | - if ($theme === '') { |
|
1349 | - if (is_dir(OC::$SERVERROOT . '/themes/default')) { |
|
1350 | - $theme = 'default'; |
|
1351 | - } |
|
1352 | - } |
|
1353 | - |
|
1354 | - return $theme; |
|
1355 | - } |
|
1356 | - |
|
1357 | - /** |
|
1358 | - * Normalize a unicode string |
|
1359 | - * |
|
1360 | - * @param string $value a not normalized string |
|
1361 | - * @return bool|string |
|
1362 | - */ |
|
1363 | - public static function normalizeUnicode($value) { |
|
1364 | - if (Normalizer::isNormalized($value)) { |
|
1365 | - return $value; |
|
1366 | - } |
|
1367 | - |
|
1368 | - $normalizedValue = Normalizer::normalize($value); |
|
1369 | - if ($normalizedValue === null || $normalizedValue === false) { |
|
1370 | - \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']); |
|
1371 | - return $value; |
|
1372 | - } |
|
1373 | - |
|
1374 | - return $normalizedValue; |
|
1375 | - } |
|
1376 | - |
|
1377 | - /** |
|
1378 | - * A human readable string is generated based on version and build number |
|
1379 | - * |
|
1380 | - * @return string |
|
1381 | - */ |
|
1382 | - public static function getHumanVersion() { |
|
1383 | - $version = OC_Util::getVersionString(); |
|
1384 | - $build = OC_Util::getBuild(); |
|
1385 | - if (!empty($build) and OC_Util::getChannel() === 'daily') { |
|
1386 | - $version .= ' Build:' . $build; |
|
1387 | - } |
|
1388 | - return $version; |
|
1389 | - } |
|
1390 | - |
|
1391 | - /** |
|
1392 | - * Returns whether the given file name is valid |
|
1393 | - * |
|
1394 | - * @param string $file file name to check |
|
1395 | - * @return bool true if the file name is valid, false otherwise |
|
1396 | - * @deprecated use \OC\Files\View::verifyPath() |
|
1397 | - */ |
|
1398 | - public static function isValidFileName($file) { |
|
1399 | - $trimmed = trim($file); |
|
1400 | - if ($trimmed === '') { |
|
1401 | - return false; |
|
1402 | - } |
|
1403 | - if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) { |
|
1404 | - return false; |
|
1405 | - } |
|
1406 | - |
|
1407 | - // detect part files |
|
1408 | - if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) { |
|
1409 | - return false; |
|
1410 | - } |
|
1411 | - |
|
1412 | - foreach (str_split($trimmed) as $char) { |
|
1413 | - if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) { |
|
1414 | - return false; |
|
1415 | - } |
|
1416 | - } |
|
1417 | - return true; |
|
1418 | - } |
|
1419 | - |
|
1420 | - /** |
|
1421 | - * Check whether the instance needs to perform an upgrade, |
|
1422 | - * either when the core version is higher or any app requires |
|
1423 | - * an upgrade. |
|
1424 | - * |
|
1425 | - * @param \OC\SystemConfig $config |
|
1426 | - * @return bool whether the core or any app needs an upgrade |
|
1427 | - * @throws \OCP\HintException When the upgrade from the given version is not allowed |
|
1428 | - */ |
|
1429 | - public static function needUpgrade(\OC\SystemConfig $config) { |
|
1430 | - if ($config->getValue('installed', false)) { |
|
1431 | - $installedVersion = $config->getValue('version', '0.0.0'); |
|
1432 | - $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
1433 | - $versionDiff = version_compare($currentVersion, $installedVersion); |
|
1434 | - if ($versionDiff > 0) { |
|
1435 | - return true; |
|
1436 | - } elseif ($config->getValue('debug', false) && $versionDiff < 0) { |
|
1437 | - // downgrade with debug |
|
1438 | - $installedMajor = explode('.', $installedVersion); |
|
1439 | - $installedMajor = $installedMajor[0] . '.' . $installedMajor[1]; |
|
1440 | - $currentMajor = explode('.', $currentVersion); |
|
1441 | - $currentMajor = $currentMajor[0] . '.' . $currentMajor[1]; |
|
1442 | - if ($installedMajor === $currentMajor) { |
|
1443 | - // Same major, allow downgrade for developers |
|
1444 | - return true; |
|
1445 | - } else { |
|
1446 | - // downgrade attempt, throw exception |
|
1447 | - throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); |
|
1448 | - } |
|
1449 | - } elseif ($versionDiff < 0) { |
|
1450 | - // downgrade attempt, throw exception |
|
1451 | - throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); |
|
1452 | - } |
|
1453 | - |
|
1454 | - // also check for upgrades for apps (independently from the user) |
|
1455 | - $apps = \OC_App::getEnabledApps(false, true); |
|
1456 | - $shouldUpgrade = false; |
|
1457 | - foreach ($apps as $app) { |
|
1458 | - if (\OC_App::shouldUpgrade($app)) { |
|
1459 | - $shouldUpgrade = true; |
|
1460 | - break; |
|
1461 | - } |
|
1462 | - } |
|
1463 | - return $shouldUpgrade; |
|
1464 | - } else { |
|
1465 | - return false; |
|
1466 | - } |
|
1467 | - } |
|
1468 | - |
|
1469 | - /** |
|
1470 | - * is this Internet explorer ? |
|
1471 | - * |
|
1472 | - * @return boolean |
|
1473 | - */ |
|
1474 | - public static function isIe() { |
|
1475 | - if (!isset($_SERVER['HTTP_USER_AGENT'])) { |
|
1476 | - return false; |
|
1477 | - } |
|
1478 | - |
|
1479 | - return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1; |
|
1480 | - } |
|
1275 | + return $content !== $testContent && $fallbackContent !== $testContent; |
|
1276 | + } |
|
1277 | + |
|
1278 | + /** |
|
1279 | + * Check if the setlocal call does not work. This can happen if the right |
|
1280 | + * local packages are not available on the server. |
|
1281 | + * |
|
1282 | + * @return bool |
|
1283 | + */ |
|
1284 | + public static function isSetLocaleWorking() { |
|
1285 | + if ('' === basename('§')) { |
|
1286 | + // Borrowed from \Patchwork\Utf8\Bootup::initLocale |
|
1287 | + setlocale(LC_ALL, 'C.UTF-8', 'C'); |
|
1288 | + setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0'); |
|
1289 | + } |
|
1290 | + |
|
1291 | + // Check again |
|
1292 | + if ('' === basename('§')) { |
|
1293 | + return false; |
|
1294 | + } |
|
1295 | + return true; |
|
1296 | + } |
|
1297 | + |
|
1298 | + /** |
|
1299 | + * Check if it's possible to get the inline annotations |
|
1300 | + * |
|
1301 | + * @return bool |
|
1302 | + */ |
|
1303 | + public static function isAnnotationsWorking() { |
|
1304 | + $reflection = new \ReflectionMethod(__METHOD__); |
|
1305 | + $docs = $reflection->getDocComment(); |
|
1306 | + |
|
1307 | + return (is_string($docs) && strlen($docs) > 50); |
|
1308 | + } |
|
1309 | + |
|
1310 | + /** |
|
1311 | + * Check if the PHP module fileinfo is loaded. |
|
1312 | + * |
|
1313 | + * @return bool |
|
1314 | + */ |
|
1315 | + public static function fileInfoLoaded() { |
|
1316 | + return function_exists('finfo_open'); |
|
1317 | + } |
|
1318 | + |
|
1319 | + /** |
|
1320 | + * clear all levels of output buffering |
|
1321 | + * |
|
1322 | + * @return void |
|
1323 | + */ |
|
1324 | + public static function obEnd() { |
|
1325 | + while (ob_get_level()) { |
|
1326 | + ob_end_clean(); |
|
1327 | + } |
|
1328 | + } |
|
1329 | + |
|
1330 | + /** |
|
1331 | + * Checks whether the server is running on Mac OS X |
|
1332 | + * |
|
1333 | + * @return bool true if running on Mac OS X, false otherwise |
|
1334 | + */ |
|
1335 | + public static function runningOnMac() { |
|
1336 | + return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN'); |
|
1337 | + } |
|
1338 | + |
|
1339 | + /** |
|
1340 | + * Handles the case that there may not be a theme, then check if a "default" |
|
1341 | + * theme exists and take that one |
|
1342 | + * |
|
1343 | + * @return string the theme |
|
1344 | + */ |
|
1345 | + public static function getTheme() { |
|
1346 | + $theme = \OC::$server->getSystemConfig()->getValue("theme", ''); |
|
1347 | + |
|
1348 | + if ($theme === '') { |
|
1349 | + if (is_dir(OC::$SERVERROOT . '/themes/default')) { |
|
1350 | + $theme = 'default'; |
|
1351 | + } |
|
1352 | + } |
|
1353 | + |
|
1354 | + return $theme; |
|
1355 | + } |
|
1356 | + |
|
1357 | + /** |
|
1358 | + * Normalize a unicode string |
|
1359 | + * |
|
1360 | + * @param string $value a not normalized string |
|
1361 | + * @return bool|string |
|
1362 | + */ |
|
1363 | + public static function normalizeUnicode($value) { |
|
1364 | + if (Normalizer::isNormalized($value)) { |
|
1365 | + return $value; |
|
1366 | + } |
|
1367 | + |
|
1368 | + $normalizedValue = Normalizer::normalize($value); |
|
1369 | + if ($normalizedValue === null || $normalizedValue === false) { |
|
1370 | + \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']); |
|
1371 | + return $value; |
|
1372 | + } |
|
1373 | + |
|
1374 | + return $normalizedValue; |
|
1375 | + } |
|
1376 | + |
|
1377 | + /** |
|
1378 | + * A human readable string is generated based on version and build number |
|
1379 | + * |
|
1380 | + * @return string |
|
1381 | + */ |
|
1382 | + public static function getHumanVersion() { |
|
1383 | + $version = OC_Util::getVersionString(); |
|
1384 | + $build = OC_Util::getBuild(); |
|
1385 | + if (!empty($build) and OC_Util::getChannel() === 'daily') { |
|
1386 | + $version .= ' Build:' . $build; |
|
1387 | + } |
|
1388 | + return $version; |
|
1389 | + } |
|
1390 | + |
|
1391 | + /** |
|
1392 | + * Returns whether the given file name is valid |
|
1393 | + * |
|
1394 | + * @param string $file file name to check |
|
1395 | + * @return bool true if the file name is valid, false otherwise |
|
1396 | + * @deprecated use \OC\Files\View::verifyPath() |
|
1397 | + */ |
|
1398 | + public static function isValidFileName($file) { |
|
1399 | + $trimmed = trim($file); |
|
1400 | + if ($trimmed === '') { |
|
1401 | + return false; |
|
1402 | + } |
|
1403 | + if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) { |
|
1404 | + return false; |
|
1405 | + } |
|
1406 | + |
|
1407 | + // detect part files |
|
1408 | + if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) { |
|
1409 | + return false; |
|
1410 | + } |
|
1411 | + |
|
1412 | + foreach (str_split($trimmed) as $char) { |
|
1413 | + if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) { |
|
1414 | + return false; |
|
1415 | + } |
|
1416 | + } |
|
1417 | + return true; |
|
1418 | + } |
|
1419 | + |
|
1420 | + /** |
|
1421 | + * Check whether the instance needs to perform an upgrade, |
|
1422 | + * either when the core version is higher or any app requires |
|
1423 | + * an upgrade. |
|
1424 | + * |
|
1425 | + * @param \OC\SystemConfig $config |
|
1426 | + * @return bool whether the core or any app needs an upgrade |
|
1427 | + * @throws \OCP\HintException When the upgrade from the given version is not allowed |
|
1428 | + */ |
|
1429 | + public static function needUpgrade(\OC\SystemConfig $config) { |
|
1430 | + if ($config->getValue('installed', false)) { |
|
1431 | + $installedVersion = $config->getValue('version', '0.0.0'); |
|
1432 | + $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
1433 | + $versionDiff = version_compare($currentVersion, $installedVersion); |
|
1434 | + if ($versionDiff > 0) { |
|
1435 | + return true; |
|
1436 | + } elseif ($config->getValue('debug', false) && $versionDiff < 0) { |
|
1437 | + // downgrade with debug |
|
1438 | + $installedMajor = explode('.', $installedVersion); |
|
1439 | + $installedMajor = $installedMajor[0] . '.' . $installedMajor[1]; |
|
1440 | + $currentMajor = explode('.', $currentVersion); |
|
1441 | + $currentMajor = $currentMajor[0] . '.' . $currentMajor[1]; |
|
1442 | + if ($installedMajor === $currentMajor) { |
|
1443 | + // Same major, allow downgrade for developers |
|
1444 | + return true; |
|
1445 | + } else { |
|
1446 | + // downgrade attempt, throw exception |
|
1447 | + throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); |
|
1448 | + } |
|
1449 | + } elseif ($versionDiff < 0) { |
|
1450 | + // downgrade attempt, throw exception |
|
1451 | + throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')'); |
|
1452 | + } |
|
1453 | + |
|
1454 | + // also check for upgrades for apps (independently from the user) |
|
1455 | + $apps = \OC_App::getEnabledApps(false, true); |
|
1456 | + $shouldUpgrade = false; |
|
1457 | + foreach ($apps as $app) { |
|
1458 | + if (\OC_App::shouldUpgrade($app)) { |
|
1459 | + $shouldUpgrade = true; |
|
1460 | + break; |
|
1461 | + } |
|
1462 | + } |
|
1463 | + return $shouldUpgrade; |
|
1464 | + } else { |
|
1465 | + return false; |
|
1466 | + } |
|
1467 | + } |
|
1468 | + |
|
1469 | + /** |
|
1470 | + * is this Internet explorer ? |
|
1471 | + * |
|
1472 | + * @return boolean |
|
1473 | + */ |
|
1474 | + public static function isIe() { |
|
1475 | + if (!isset($_SERVER['HTTP_USER_AGENT'])) { |
|
1476 | + return false; |
|
1477 | + } |
|
1478 | + |
|
1479 | + return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1; |
|
1480 | + } |
|
1481 | 1481 | } |
@@ -29,118 +29,118 @@ |
||
29 | 29 | * |
30 | 30 | */ |
31 | 31 | class OC_Hook { |
32 | - public static $thrownExceptions = []; |
|
32 | + public static $thrownExceptions = []; |
|
33 | 33 | |
34 | - private static $registered = []; |
|
34 | + private static $registered = []; |
|
35 | 35 | |
36 | - /** |
|
37 | - * connects a function to a hook |
|
38 | - * |
|
39 | - * @param string $signalClass class name of emitter |
|
40 | - * @param string $signalName name of signal |
|
41 | - * @param string|object $slotClass class name of slot |
|
42 | - * @param string $slotName name of slot |
|
43 | - * @return bool |
|
44 | - * |
|
45 | - * This function makes it very easy to connect to use hooks. |
|
46 | - * |
|
47 | - * TODO: write example |
|
48 | - */ |
|
49 | - public static function connect($signalClass, $signalName, $slotClass, $slotName) { |
|
50 | - // If we're trying to connect to an emitting class that isn't |
|
51 | - // yet registered, register it |
|
52 | - if (!array_key_exists($signalClass, self::$registered)) { |
|
53 | - self::$registered[$signalClass] = []; |
|
54 | - } |
|
55 | - // If we're trying to connect to an emitting method that isn't |
|
56 | - // yet registered, register it with the emitting class |
|
57 | - if (!array_key_exists($signalName, self::$registered[$signalClass])) { |
|
58 | - self::$registered[$signalClass][$signalName] = []; |
|
59 | - } |
|
36 | + /** |
|
37 | + * connects a function to a hook |
|
38 | + * |
|
39 | + * @param string $signalClass class name of emitter |
|
40 | + * @param string $signalName name of signal |
|
41 | + * @param string|object $slotClass class name of slot |
|
42 | + * @param string $slotName name of slot |
|
43 | + * @return bool |
|
44 | + * |
|
45 | + * This function makes it very easy to connect to use hooks. |
|
46 | + * |
|
47 | + * TODO: write example |
|
48 | + */ |
|
49 | + public static function connect($signalClass, $signalName, $slotClass, $slotName) { |
|
50 | + // If we're trying to connect to an emitting class that isn't |
|
51 | + // yet registered, register it |
|
52 | + if (!array_key_exists($signalClass, self::$registered)) { |
|
53 | + self::$registered[$signalClass] = []; |
|
54 | + } |
|
55 | + // If we're trying to connect to an emitting method that isn't |
|
56 | + // yet registered, register it with the emitting class |
|
57 | + if (!array_key_exists($signalName, self::$registered[$signalClass])) { |
|
58 | + self::$registered[$signalClass][$signalName] = []; |
|
59 | + } |
|
60 | 60 | |
61 | - // don't connect hooks twice |
|
62 | - foreach (self::$registered[$signalClass][$signalName] as $hook) { |
|
63 | - if ($hook['class'] === $slotClass and $hook['name'] === $slotName) { |
|
64 | - return false; |
|
65 | - } |
|
66 | - } |
|
67 | - // Connect the hook handler to the requested emitter |
|
68 | - self::$registered[$signalClass][$signalName][] = [ |
|
69 | - "class" => $slotClass, |
|
70 | - "name" => $slotName |
|
71 | - ]; |
|
61 | + // don't connect hooks twice |
|
62 | + foreach (self::$registered[$signalClass][$signalName] as $hook) { |
|
63 | + if ($hook['class'] === $slotClass and $hook['name'] === $slotName) { |
|
64 | + return false; |
|
65 | + } |
|
66 | + } |
|
67 | + // Connect the hook handler to the requested emitter |
|
68 | + self::$registered[$signalClass][$signalName][] = [ |
|
69 | + "class" => $slotClass, |
|
70 | + "name" => $slotName |
|
71 | + ]; |
|
72 | 72 | |
73 | - // No chance for failure ;-) |
|
74 | - return true; |
|
75 | - } |
|
73 | + // No chance for failure ;-) |
|
74 | + return true; |
|
75 | + } |
|
76 | 76 | |
77 | - /** |
|
78 | - * emits a signal |
|
79 | - * |
|
80 | - * @param string $signalClass class name of emitter |
|
81 | - * @param string $signalName name of signal |
|
82 | - * @param mixed $params default: array() array with additional data |
|
83 | - * @return bool true if slots exists or false if not |
|
84 | - * @throws \OCP\HintException |
|
85 | - * @throws \OC\ServerNotAvailableException Emits a signal. To get data from the slot use references! |
|
86 | - * |
|
87 | - * TODO: write example |
|
88 | - */ |
|
89 | - public static function emit($signalClass, $signalName, $params = []) { |
|
77 | + /** |
|
78 | + * emits a signal |
|
79 | + * |
|
80 | + * @param string $signalClass class name of emitter |
|
81 | + * @param string $signalName name of signal |
|
82 | + * @param mixed $params default: array() array with additional data |
|
83 | + * @return bool true if slots exists or false if not |
|
84 | + * @throws \OCP\HintException |
|
85 | + * @throws \OC\ServerNotAvailableException Emits a signal. To get data from the slot use references! |
|
86 | + * |
|
87 | + * TODO: write example |
|
88 | + */ |
|
89 | + public static function emit($signalClass, $signalName, $params = []) { |
|
90 | 90 | |
91 | - // Return false if no hook handlers are listening to this |
|
92 | - // emitting class |
|
93 | - if (!array_key_exists($signalClass, self::$registered)) { |
|
94 | - return false; |
|
95 | - } |
|
91 | + // Return false if no hook handlers are listening to this |
|
92 | + // emitting class |
|
93 | + if (!array_key_exists($signalClass, self::$registered)) { |
|
94 | + return false; |
|
95 | + } |
|
96 | 96 | |
97 | - // Return false if no hook handlers are listening to this |
|
98 | - // emitting method |
|
99 | - if (!array_key_exists($signalName, self::$registered[$signalClass])) { |
|
100 | - return false; |
|
101 | - } |
|
97 | + // Return false if no hook handlers are listening to this |
|
98 | + // emitting method |
|
99 | + if (!array_key_exists($signalName, self::$registered[$signalClass])) { |
|
100 | + return false; |
|
101 | + } |
|
102 | 102 | |
103 | - // Call all slots |
|
104 | - foreach (self::$registered[$signalClass][$signalName] as $i) { |
|
105 | - try { |
|
106 | - call_user_func([ $i["class"], $i["name"] ], $params); |
|
107 | - } catch (Exception $e) { |
|
108 | - self::$thrownExceptions[] = $e; |
|
109 | - \OC::$server->getLogger()->logException($e); |
|
110 | - if ($e instanceof \OCP\HintException) { |
|
111 | - throw $e; |
|
112 | - } |
|
113 | - if ($e instanceof \OC\ServerNotAvailableException) { |
|
114 | - throw $e; |
|
115 | - } |
|
116 | - } |
|
117 | - } |
|
103 | + // Call all slots |
|
104 | + foreach (self::$registered[$signalClass][$signalName] as $i) { |
|
105 | + try { |
|
106 | + call_user_func([ $i["class"], $i["name"] ], $params); |
|
107 | + } catch (Exception $e) { |
|
108 | + self::$thrownExceptions[] = $e; |
|
109 | + \OC::$server->getLogger()->logException($e); |
|
110 | + if ($e instanceof \OCP\HintException) { |
|
111 | + throw $e; |
|
112 | + } |
|
113 | + if ($e instanceof \OC\ServerNotAvailableException) { |
|
114 | + throw $e; |
|
115 | + } |
|
116 | + } |
|
117 | + } |
|
118 | 118 | |
119 | - return true; |
|
120 | - } |
|
119 | + return true; |
|
120 | + } |
|
121 | 121 | |
122 | - /** |
|
123 | - * clear hooks |
|
124 | - * @param string $signalClass |
|
125 | - * @param string $signalName |
|
126 | - */ |
|
127 | - public static function clear($signalClass = '', $signalName = '') { |
|
128 | - if ($signalClass) { |
|
129 | - if ($signalName) { |
|
130 | - self::$registered[$signalClass][$signalName] = []; |
|
131 | - } else { |
|
132 | - self::$registered[$signalClass] = []; |
|
133 | - } |
|
134 | - } else { |
|
135 | - self::$registered = []; |
|
136 | - } |
|
137 | - } |
|
122 | + /** |
|
123 | + * clear hooks |
|
124 | + * @param string $signalClass |
|
125 | + * @param string $signalName |
|
126 | + */ |
|
127 | + public static function clear($signalClass = '', $signalName = '') { |
|
128 | + if ($signalClass) { |
|
129 | + if ($signalName) { |
|
130 | + self::$registered[$signalClass][$signalName] = []; |
|
131 | + } else { |
|
132 | + self::$registered[$signalClass] = []; |
|
133 | + } |
|
134 | + } else { |
|
135 | + self::$registered = []; |
|
136 | + } |
|
137 | + } |
|
138 | 138 | |
139 | - /** |
|
140 | - * DO NOT USE! |
|
141 | - * For unit tests ONLY! |
|
142 | - */ |
|
143 | - public static function getHooks() { |
|
144 | - return self::$registered; |
|
145 | - } |
|
139 | + /** |
|
140 | + * DO NOT USE! |
|
141 | + * For unit tests ONLY! |
|
142 | + */ |
|
143 | + public static function getHooks() { |
|
144 | + return self::$registered; |
|
145 | + } |
|
146 | 146 | } |
@@ -37,128 +37,128 @@ |
||
37 | 37 | use OCP\IMemcache; |
38 | 38 | |
39 | 39 | class Factory implements ICacheFactory { |
40 | - public const NULL_CACHE = NullCache::class; |
|
41 | - |
|
42 | - /** |
|
43 | - * @var string $globalPrefix |
|
44 | - */ |
|
45 | - private $globalPrefix; |
|
46 | - |
|
47 | - /** |
|
48 | - * @var ILogger $logger |
|
49 | - */ |
|
50 | - private $logger; |
|
51 | - |
|
52 | - /** |
|
53 | - * @var string $localCacheClass |
|
54 | - */ |
|
55 | - private $localCacheClass; |
|
56 | - |
|
57 | - /** |
|
58 | - * @var string $distributedCacheClass |
|
59 | - */ |
|
60 | - private $distributedCacheClass; |
|
61 | - |
|
62 | - /** |
|
63 | - * @var string $lockingCacheClass |
|
64 | - */ |
|
65 | - private $lockingCacheClass; |
|
66 | - |
|
67 | - /** |
|
68 | - * @param string $globalPrefix |
|
69 | - * @param ILogger $logger |
|
70 | - * @param string|null $localCacheClass |
|
71 | - * @param string|null $distributedCacheClass |
|
72 | - * @param string|null $lockingCacheClass |
|
73 | - */ |
|
74 | - public function __construct(string $globalPrefix, ILogger $logger, |
|
75 | - $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null) { |
|
76 | - $this->logger = $logger; |
|
77 | - $this->globalPrefix = $globalPrefix; |
|
78 | - |
|
79 | - if (!$localCacheClass) { |
|
80 | - $localCacheClass = self::NULL_CACHE; |
|
81 | - } |
|
82 | - if (!$distributedCacheClass) { |
|
83 | - $distributedCacheClass = $localCacheClass; |
|
84 | - } |
|
85 | - |
|
86 | - $missingCacheMessage = 'Memcache {class} not available for {use} cache'; |
|
87 | - $missingCacheHint = 'Is the matching PHP module installed and enabled?'; |
|
88 | - if (!class_exists($localCacheClass) || !$localCacheClass::isAvailable()) { |
|
89 | - throw new \OCP\HintException(strtr($missingCacheMessage, [ |
|
90 | - '{class}' => $localCacheClass, '{use}' => 'local' |
|
91 | - ]), $missingCacheHint); |
|
92 | - } |
|
93 | - if (!class_exists($distributedCacheClass) || !$distributedCacheClass::isAvailable()) { |
|
94 | - throw new \OCP\HintException(strtr($missingCacheMessage, [ |
|
95 | - '{class}' => $distributedCacheClass, '{use}' => 'distributed' |
|
96 | - ]), $missingCacheHint); |
|
97 | - } |
|
98 | - if (!($lockingCacheClass && class_exists($distributedCacheClass) && $lockingCacheClass::isAvailable())) { |
|
99 | - // don't fallback since the fallback might not be suitable for storing lock |
|
100 | - $lockingCacheClass = self::NULL_CACHE; |
|
101 | - } |
|
102 | - |
|
103 | - $this->localCacheClass = $localCacheClass; |
|
104 | - $this->distributedCacheClass = $distributedCacheClass; |
|
105 | - $this->lockingCacheClass = $lockingCacheClass; |
|
106 | - } |
|
107 | - |
|
108 | - /** |
|
109 | - * create a cache instance for storing locks |
|
110 | - * |
|
111 | - * @param string $prefix |
|
112 | - * @return IMemcache |
|
113 | - */ |
|
114 | - public function createLocking(string $prefix = ''): IMemcache { |
|
115 | - return new $this->lockingCacheClass($this->globalPrefix . '/' . $prefix); |
|
116 | - } |
|
117 | - |
|
118 | - /** |
|
119 | - * create a distributed cache instance |
|
120 | - * |
|
121 | - * @param string $prefix |
|
122 | - * @return ICache |
|
123 | - */ |
|
124 | - public function createDistributed(string $prefix = ''): ICache { |
|
125 | - return new $this->distributedCacheClass($this->globalPrefix . '/' . $prefix); |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * create a local cache instance |
|
130 | - * |
|
131 | - * @param string $prefix |
|
132 | - * @return ICache |
|
133 | - */ |
|
134 | - public function createLocal(string $prefix = ''): ICache { |
|
135 | - return new $this->localCacheClass($this->globalPrefix . '/' . $prefix); |
|
136 | - } |
|
137 | - |
|
138 | - /** |
|
139 | - * check memcache availability |
|
140 | - * |
|
141 | - * @return bool |
|
142 | - */ |
|
143 | - public function isAvailable(): bool { |
|
144 | - return ($this->distributedCacheClass !== self::NULL_CACHE); |
|
145 | - } |
|
146 | - |
|
147 | - /** |
|
148 | - * @see \OC\Memcache\Factory::createLocal() |
|
149 | - * @param string $prefix |
|
150 | - * @return ICache |
|
151 | - */ |
|
152 | - public function createLowLatency(string $prefix = ''): ICache { |
|
153 | - return $this->createLocal($prefix); |
|
154 | - } |
|
155 | - |
|
156 | - /** |
|
157 | - * Check if a local memory cache backend is available |
|
158 | - * |
|
159 | - * @return bool |
|
160 | - */ |
|
161 | - public function isLocalCacheAvailable(): bool { |
|
162 | - return ($this->localCacheClass !== self::NULL_CACHE); |
|
163 | - } |
|
40 | + public const NULL_CACHE = NullCache::class; |
|
41 | + |
|
42 | + /** |
|
43 | + * @var string $globalPrefix |
|
44 | + */ |
|
45 | + private $globalPrefix; |
|
46 | + |
|
47 | + /** |
|
48 | + * @var ILogger $logger |
|
49 | + */ |
|
50 | + private $logger; |
|
51 | + |
|
52 | + /** |
|
53 | + * @var string $localCacheClass |
|
54 | + */ |
|
55 | + private $localCacheClass; |
|
56 | + |
|
57 | + /** |
|
58 | + * @var string $distributedCacheClass |
|
59 | + */ |
|
60 | + private $distributedCacheClass; |
|
61 | + |
|
62 | + /** |
|
63 | + * @var string $lockingCacheClass |
|
64 | + */ |
|
65 | + private $lockingCacheClass; |
|
66 | + |
|
67 | + /** |
|
68 | + * @param string $globalPrefix |
|
69 | + * @param ILogger $logger |
|
70 | + * @param string|null $localCacheClass |
|
71 | + * @param string|null $distributedCacheClass |
|
72 | + * @param string|null $lockingCacheClass |
|
73 | + */ |
|
74 | + public function __construct(string $globalPrefix, ILogger $logger, |
|
75 | + $localCacheClass = null, $distributedCacheClass = null, $lockingCacheClass = null) { |
|
76 | + $this->logger = $logger; |
|
77 | + $this->globalPrefix = $globalPrefix; |
|
78 | + |
|
79 | + if (!$localCacheClass) { |
|
80 | + $localCacheClass = self::NULL_CACHE; |
|
81 | + } |
|
82 | + if (!$distributedCacheClass) { |
|
83 | + $distributedCacheClass = $localCacheClass; |
|
84 | + } |
|
85 | + |
|
86 | + $missingCacheMessage = 'Memcache {class} not available for {use} cache'; |
|
87 | + $missingCacheHint = 'Is the matching PHP module installed and enabled?'; |
|
88 | + if (!class_exists($localCacheClass) || !$localCacheClass::isAvailable()) { |
|
89 | + throw new \OCP\HintException(strtr($missingCacheMessage, [ |
|
90 | + '{class}' => $localCacheClass, '{use}' => 'local' |
|
91 | + ]), $missingCacheHint); |
|
92 | + } |
|
93 | + if (!class_exists($distributedCacheClass) || !$distributedCacheClass::isAvailable()) { |
|
94 | + throw new \OCP\HintException(strtr($missingCacheMessage, [ |
|
95 | + '{class}' => $distributedCacheClass, '{use}' => 'distributed' |
|
96 | + ]), $missingCacheHint); |
|
97 | + } |
|
98 | + if (!($lockingCacheClass && class_exists($distributedCacheClass) && $lockingCacheClass::isAvailable())) { |
|
99 | + // don't fallback since the fallback might not be suitable for storing lock |
|
100 | + $lockingCacheClass = self::NULL_CACHE; |
|
101 | + } |
|
102 | + |
|
103 | + $this->localCacheClass = $localCacheClass; |
|
104 | + $this->distributedCacheClass = $distributedCacheClass; |
|
105 | + $this->lockingCacheClass = $lockingCacheClass; |
|
106 | + } |
|
107 | + |
|
108 | + /** |
|
109 | + * create a cache instance for storing locks |
|
110 | + * |
|
111 | + * @param string $prefix |
|
112 | + * @return IMemcache |
|
113 | + */ |
|
114 | + public function createLocking(string $prefix = ''): IMemcache { |
|
115 | + return new $this->lockingCacheClass($this->globalPrefix . '/' . $prefix); |
|
116 | + } |
|
117 | + |
|
118 | + /** |
|
119 | + * create a distributed cache instance |
|
120 | + * |
|
121 | + * @param string $prefix |
|
122 | + * @return ICache |
|
123 | + */ |
|
124 | + public function createDistributed(string $prefix = ''): ICache { |
|
125 | + return new $this->distributedCacheClass($this->globalPrefix . '/' . $prefix); |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * create a local cache instance |
|
130 | + * |
|
131 | + * @param string $prefix |
|
132 | + * @return ICache |
|
133 | + */ |
|
134 | + public function createLocal(string $prefix = ''): ICache { |
|
135 | + return new $this->localCacheClass($this->globalPrefix . '/' . $prefix); |
|
136 | + } |
|
137 | + |
|
138 | + /** |
|
139 | + * check memcache availability |
|
140 | + * |
|
141 | + * @return bool |
|
142 | + */ |
|
143 | + public function isAvailable(): bool { |
|
144 | + return ($this->distributedCacheClass !== self::NULL_CACHE); |
|
145 | + } |
|
146 | + |
|
147 | + /** |
|
148 | + * @see \OC\Memcache\Factory::createLocal() |
|
149 | + * @param string $prefix |
|
150 | + * @return ICache |
|
151 | + */ |
|
152 | + public function createLowLatency(string $prefix = ''): ICache { |
|
153 | + return $this->createLocal($prefix); |
|
154 | + } |
|
155 | + |
|
156 | + /** |
|
157 | + * Check if a local memory cache backend is available |
|
158 | + * |
|
159 | + * @return bool |
|
160 | + */ |
|
161 | + public function isLocalCacheAvailable(): bool { |
|
162 | + return ($this->localCacheClass !== self::NULL_CACHE); |
|
163 | + } |
|
164 | 164 | } |
@@ -78,1006 +78,1006 @@ |
||
78 | 78 | * OC_autoload! |
79 | 79 | */ |
80 | 80 | class OC { |
81 | - /** |
|
82 | - * Associative array for autoloading. classname => filename |
|
83 | - */ |
|
84 | - public static $CLASSPATH = []; |
|
85 | - /** |
|
86 | - * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
87 | - */ |
|
88 | - public static $SERVERROOT = ''; |
|
89 | - /** |
|
90 | - * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
91 | - */ |
|
92 | - private static $SUBURI = ''; |
|
93 | - /** |
|
94 | - * the Nextcloud root path for http requests (e.g. nextcloud/) |
|
95 | - */ |
|
96 | - public static $WEBROOT = ''; |
|
97 | - /** |
|
98 | - * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
99 | - * web path in 'url' |
|
100 | - */ |
|
101 | - public static $APPSROOTS = []; |
|
102 | - |
|
103 | - /** |
|
104 | - * @var string |
|
105 | - */ |
|
106 | - public static $configDir; |
|
107 | - |
|
108 | - /** |
|
109 | - * requested app |
|
110 | - */ |
|
111 | - public static $REQUESTEDAPP = ''; |
|
112 | - |
|
113 | - /** |
|
114 | - * check if Nextcloud runs in cli mode |
|
115 | - */ |
|
116 | - public static $CLI = false; |
|
117 | - |
|
118 | - /** |
|
119 | - * @var \OC\Autoloader $loader |
|
120 | - */ |
|
121 | - public static $loader = null; |
|
122 | - |
|
123 | - /** @var \Composer\Autoload\ClassLoader $composerAutoloader */ |
|
124 | - public static $composerAutoloader = null; |
|
125 | - |
|
126 | - /** |
|
127 | - * @var \OC\Server |
|
128 | - */ |
|
129 | - public static $server = null; |
|
130 | - |
|
131 | - /** |
|
132 | - * @var \OC\Config |
|
133 | - */ |
|
134 | - private static $config = null; |
|
135 | - |
|
136 | - /** |
|
137 | - * @throws \RuntimeException when the 3rdparty directory is missing or |
|
138 | - * the app path list is empty or contains an invalid path |
|
139 | - */ |
|
140 | - public static function initPaths() { |
|
141 | - if (defined('PHPUNIT_CONFIG_DIR')) { |
|
142 | - self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
143 | - } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
144 | - self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
145 | - } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
146 | - self::$configDir = rtrim($dir, '/') . '/'; |
|
147 | - } else { |
|
148 | - self::$configDir = OC::$SERVERROOT . '/config/'; |
|
149 | - } |
|
150 | - self::$config = new \OC\Config(self::$configDir); |
|
151 | - |
|
152 | - OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT))); |
|
153 | - /** |
|
154 | - * FIXME: The following lines are required because we can't yet instantiate |
|
155 | - * \OC::$server->getRequest() since \OC::$server does not yet exist. |
|
156 | - */ |
|
157 | - $params = [ |
|
158 | - 'server' => [ |
|
159 | - 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'], |
|
160 | - 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'], |
|
161 | - ], |
|
162 | - ]; |
|
163 | - $fakeRequest = new \OC\AppFramework\Http\Request($params, new \OC\Security\SecureRandom(), new \OC\AllConfig(new \OC\SystemConfig(self::$config))); |
|
164 | - $scriptName = $fakeRequest->getScriptName(); |
|
165 | - if (substr($scriptName, -1) == '/') { |
|
166 | - $scriptName .= 'index.php'; |
|
167 | - //make sure suburi follows the same rules as scriptName |
|
168 | - if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
169 | - if (substr(OC::$SUBURI, -1) != '/') { |
|
170 | - OC::$SUBURI = OC::$SUBURI . '/'; |
|
171 | - } |
|
172 | - OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
173 | - } |
|
174 | - } |
|
175 | - |
|
176 | - |
|
177 | - if (OC::$CLI) { |
|
178 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
179 | - } else { |
|
180 | - if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
181 | - OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
182 | - |
|
183 | - if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
184 | - OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
185 | - } |
|
186 | - } else { |
|
187 | - // The scriptName is not ending with OC::$SUBURI |
|
188 | - // This most likely means that we are calling from CLI. |
|
189 | - // However some cron jobs still need to generate |
|
190 | - // a web URL, so we use overwritewebroot as a fallback. |
|
191 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
192 | - } |
|
193 | - |
|
194 | - // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
195 | - // slash which is required by URL generation. |
|
196 | - if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
|
197 | - substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
198 | - header('Location: '.\OC::$WEBROOT.'/'); |
|
199 | - exit(); |
|
200 | - } |
|
201 | - } |
|
202 | - |
|
203 | - // search the apps folder |
|
204 | - $config_paths = self::$config->getValue('apps_paths', []); |
|
205 | - if (!empty($config_paths)) { |
|
206 | - foreach ($config_paths as $paths) { |
|
207 | - if (isset($paths['url']) && isset($paths['path'])) { |
|
208 | - $paths['url'] = rtrim($paths['url'], '/'); |
|
209 | - $paths['path'] = rtrim($paths['path'], '/'); |
|
210 | - OC::$APPSROOTS[] = $paths; |
|
211 | - } |
|
212 | - } |
|
213 | - } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
214 | - OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
215 | - } |
|
216 | - |
|
217 | - if (empty(OC::$APPSROOTS)) { |
|
218 | - throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
219 | - . '. You can also configure the location in the config.php file.'); |
|
220 | - } |
|
221 | - $paths = []; |
|
222 | - foreach (OC::$APPSROOTS as $path) { |
|
223 | - $paths[] = $path['path']; |
|
224 | - if (!is_dir($path['path'])) { |
|
225 | - throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
226 | - . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
227 | - } |
|
228 | - } |
|
229 | - |
|
230 | - // set the right include path |
|
231 | - set_include_path( |
|
232 | - implode(PATH_SEPARATOR, $paths) |
|
233 | - ); |
|
234 | - } |
|
235 | - |
|
236 | - public static function checkConfig() { |
|
237 | - $l = \OC::$server->getL10N('lib'); |
|
238 | - |
|
239 | - // Create config if it does not already exist |
|
240 | - $configFilePath = self::$configDir .'/config.php'; |
|
241 | - if (!file_exists($configFilePath)) { |
|
242 | - @touch($configFilePath); |
|
243 | - } |
|
244 | - |
|
245 | - // Check if config is writable |
|
246 | - $configFileWritable = is_writable($configFilePath); |
|
247 | - if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
|
248 | - || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
249 | - $urlGenerator = \OC::$server->getURLGenerator(); |
|
250 | - |
|
251 | - if (self::$CLI) { |
|
252 | - echo $l->t('Cannot write into "config" directory!')."\n"; |
|
253 | - echo $l->t('This can usually be fixed by giving the webserver write access to the config directory.')."\n"; |
|
254 | - echo "\n"; |
|
255 | - echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n"; |
|
256 | - echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n"; |
|
257 | - exit; |
|
258 | - } else { |
|
259 | - OC_Template::printErrorPage( |
|
260 | - $l->t('Cannot write into "config" directory!'), |
|
261 | - $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . ' ' |
|
262 | - . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
263 | - . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
264 | - 503 |
|
265 | - ); |
|
266 | - } |
|
267 | - } |
|
268 | - } |
|
269 | - |
|
270 | - public static function checkInstalled(\OC\SystemConfig $systemConfig) { |
|
271 | - if (defined('OC_CONSOLE')) { |
|
272 | - return; |
|
273 | - } |
|
274 | - // Redirect to installer if not installed |
|
275 | - if (!$systemConfig->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(\OC\SystemConfig $systemConfig) { |
|
287 | - // Allow ajax update script to execute without being stopped |
|
288 | - if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
289 | - // send http status 503 |
|
290 | - http_response_code(503); |
|
291 | - header('Retry-After: 120'); |
|
292 | - |
|
293 | - // render error page |
|
294 | - $template = new OC_Template('', 'update.user', 'guest'); |
|
295 | - OC_Util::addScript('dist/maintenance'); |
|
296 | - OC_Util::addStyle('core', 'guest'); |
|
297 | - $template->printPage(); |
|
298 | - die(); |
|
299 | - } |
|
300 | - } |
|
301 | - |
|
302 | - /** |
|
303 | - * Prints the upgrade page |
|
304 | - * |
|
305 | - * @param \OC\SystemConfig $systemConfig |
|
306 | - */ |
|
307 | - private static function printUpgradePage(\OC\SystemConfig $systemConfig) { |
|
308 | - $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
309 | - $tooBig = false; |
|
310 | - if (!$disableWebUpdater) { |
|
311 | - $apps = \OC::$server->getAppManager(); |
|
312 | - if ($apps->isInstalled('user_ldap')) { |
|
313 | - $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
314 | - |
|
315 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
316 | - ->from('ldap_user_mapping') |
|
317 | - ->execute(); |
|
318 | - $row = $result->fetch(); |
|
319 | - $result->closeCursor(); |
|
320 | - |
|
321 | - $tooBig = ($row['user_count'] > 50); |
|
322 | - } |
|
323 | - if (!$tooBig && $apps->isInstalled('user_saml')) { |
|
324 | - $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
325 | - |
|
326 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
327 | - ->from('user_saml_users') |
|
328 | - ->execute(); |
|
329 | - $row = $result->fetch(); |
|
330 | - $result->closeCursor(); |
|
331 | - |
|
332 | - $tooBig = ($row['user_count'] > 50); |
|
333 | - } |
|
334 | - if (!$tooBig) { |
|
335 | - // count users |
|
336 | - $stats = \OC::$server->getUserManager()->countUsers(); |
|
337 | - $totalUsers = array_sum($stats); |
|
338 | - $tooBig = ($totalUsers > 50); |
|
339 | - } |
|
340 | - } |
|
341 | - $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) && |
|
342 | - $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
343 | - |
|
344 | - if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
345 | - // send http status 503 |
|
346 | - http_response_code(503); |
|
347 | - header('Retry-After: 120'); |
|
348 | - |
|
349 | - // render error page |
|
350 | - $template = new OC_Template('', 'update.use-cli', 'guest'); |
|
351 | - $template->assign('productName', 'nextcloud'); // for now |
|
352 | - $template->assign('version', OC_Util::getVersionString()); |
|
353 | - $template->assign('tooBig', $tooBig); |
|
354 | - |
|
355 | - $template->printPage(); |
|
356 | - die(); |
|
357 | - } |
|
358 | - |
|
359 | - // check whether this is a core update or apps update |
|
360 | - $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
361 | - $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
362 | - |
|
363 | - // if not a core upgrade, then it's apps upgrade |
|
364 | - $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
365 | - |
|
366 | - $oldTheme = $systemConfig->getValue('theme'); |
|
367 | - $systemConfig->setValue('theme', ''); |
|
368 | - OC_Util::addScript('update'); |
|
369 | - |
|
370 | - /** @var \OC\App\AppManager $appManager */ |
|
371 | - $appManager = \OC::$server->getAppManager(); |
|
372 | - |
|
373 | - $tmpl = new OC_Template('', 'update.admin', 'guest'); |
|
374 | - $tmpl->assign('version', OC_Util::getVersionString()); |
|
375 | - $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
376 | - |
|
377 | - // get third party apps |
|
378 | - $ocVersion = \OCP\Util::getVersion(); |
|
379 | - $ocVersion = implode('.', $ocVersion); |
|
380 | - $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
381 | - $incompatibleShippedApps = []; |
|
382 | - foreach ($incompatibleApps as $appInfo) { |
|
383 | - if ($appManager->isShipped($appInfo['id'])) { |
|
384 | - $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
385 | - } |
|
386 | - } |
|
387 | - |
|
388 | - if (!empty($incompatibleShippedApps)) { |
|
389 | - $l = \OC::$server->getL10N('core'); |
|
390 | - $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]); |
|
391 | - throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint); |
|
392 | - } |
|
393 | - |
|
394 | - $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
395 | - $tmpl->assign('incompatibleAppsList', $incompatibleApps); |
|
396 | - try { |
|
397 | - $defaults = new \OC_Defaults(); |
|
398 | - $tmpl->assign('productName', $defaults->getName()); |
|
399 | - } catch (Throwable $error) { |
|
400 | - $tmpl->assign('productName', 'Nextcloud'); |
|
401 | - } |
|
402 | - $tmpl->assign('oldTheme', $oldTheme); |
|
403 | - $tmpl->printPage(); |
|
404 | - } |
|
405 | - |
|
406 | - public static function initSession() { |
|
407 | - if (self::$server->getRequest()->getServerProtocol() === 'https') { |
|
408 | - ini_set('session.cookie_secure', 'true'); |
|
409 | - } |
|
410 | - |
|
411 | - // prevents javascript from accessing php session cookies |
|
412 | - ini_set('session.cookie_httponly', 'true'); |
|
413 | - |
|
414 | - // set the cookie path to the Nextcloud directory |
|
415 | - $cookie_path = OC::$WEBROOT ? : '/'; |
|
416 | - ini_set('session.cookie_path', $cookie_path); |
|
417 | - |
|
418 | - // Let the session name be changed in the initSession Hook |
|
419 | - $sessionName = OC_Util::getInstanceId(); |
|
420 | - |
|
421 | - try { |
|
422 | - // set the session name to the instance id - which is unique |
|
423 | - $session = new \OC\Session\Internal($sessionName); |
|
424 | - |
|
425 | - $cryptoWrapper = \OC::$server->getSessionCryptoWrapper(); |
|
426 | - $session = $cryptoWrapper->wrapSession($session); |
|
427 | - self::$server->setSession($session); |
|
428 | - |
|
429 | - // if session can't be started break with http 500 error |
|
430 | - } catch (Exception $e) { |
|
431 | - \OC::$server->getLogger()->logException($e, ['app' => 'base']); |
|
432 | - //show the user a detailed error page |
|
433 | - OC_Template::printExceptionErrorPage($e, 500); |
|
434 | - die(); |
|
435 | - } |
|
436 | - |
|
437 | - $sessionLifeTime = self::getSessionLifeTime(); |
|
438 | - |
|
439 | - // session timeout |
|
440 | - if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
441 | - if (isset($_COOKIE[session_name()])) { |
|
442 | - setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
443 | - } |
|
444 | - \OC::$server->getUserSession()->logout(); |
|
445 | - } |
|
446 | - |
|
447 | - $session->set('LAST_ACTIVITY', time()); |
|
448 | - } |
|
449 | - |
|
450 | - /** |
|
451 | - * @return string |
|
452 | - */ |
|
453 | - private static function getSessionLifeTime() { |
|
454 | - return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24); |
|
455 | - } |
|
456 | - |
|
457 | - /** |
|
458 | - * Try to set some values to the required Nextcloud default |
|
459 | - */ |
|
460 | - public static function setRequiredIniValues() { |
|
461 | - @ini_set('default_charset', 'UTF-8'); |
|
462 | - @ini_set('gd.jpeg_ignore_warning', '1'); |
|
463 | - } |
|
464 | - |
|
465 | - /** |
|
466 | - * Send the same site cookies |
|
467 | - */ |
|
468 | - private static function sendSameSiteCookies() { |
|
469 | - $cookieParams = session_get_cookie_params(); |
|
470 | - $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
471 | - $policies = [ |
|
472 | - 'lax', |
|
473 | - 'strict', |
|
474 | - ]; |
|
475 | - |
|
476 | - // Append __Host to the cookie if it meets the requirements |
|
477 | - $cookiePrefix = ''; |
|
478 | - if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
479 | - $cookiePrefix = '__Host-'; |
|
480 | - } |
|
481 | - |
|
482 | - foreach ($policies as $policy) { |
|
483 | - header( |
|
484 | - sprintf( |
|
485 | - 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
486 | - $cookiePrefix, |
|
487 | - $policy, |
|
488 | - $cookieParams['path'], |
|
489 | - $policy |
|
490 | - ), |
|
491 | - false |
|
492 | - ); |
|
493 | - } |
|
494 | - } |
|
495 | - |
|
496 | - /** |
|
497 | - * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
498 | - * be set in every request if cookies are sent to add a second level of |
|
499 | - * defense against CSRF. |
|
500 | - * |
|
501 | - * If the cookie is not sent this will set the cookie and reload the page. |
|
502 | - * We use an additional cookie since we want to protect logout CSRF and |
|
503 | - * also we can't directly interfere with PHP's session mechanism. |
|
504 | - */ |
|
505 | - private static function performSameSiteCookieProtection(\OCP\IConfig $config) { |
|
506 | - $request = \OC::$server->getRequest(); |
|
507 | - |
|
508 | - // Some user agents are notorious and don't really properly follow HTTP |
|
509 | - // specifications. For those, have an automated opt-out. Since the protection |
|
510 | - // for remote.php is applied in base.php as starting point we need to opt out |
|
511 | - // here. |
|
512 | - $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
513 | - |
|
514 | - // Fallback, if csrf.optout is unset |
|
515 | - if (!is_array($incompatibleUserAgents)) { |
|
516 | - $incompatibleUserAgents = [ |
|
517 | - // OS X Finder |
|
518 | - '/^WebDAVFS/', |
|
519 | - // Windows webdav drive |
|
520 | - '/^Microsoft-WebDAV-MiniRedir/', |
|
521 | - ]; |
|
522 | - } |
|
523 | - |
|
524 | - if ($request->isUserAgent($incompatibleUserAgents)) { |
|
525 | - return; |
|
526 | - } |
|
527 | - |
|
528 | - if (count($_COOKIE) > 0) { |
|
529 | - $requestUri = $request->getScriptName(); |
|
530 | - $processingScript = explode('/', $requestUri); |
|
531 | - $processingScript = $processingScript[count($processingScript) - 1]; |
|
532 | - |
|
533 | - // index.php routes are handled in the middleware |
|
534 | - if ($processingScript === 'index.php') { |
|
535 | - return; |
|
536 | - } |
|
537 | - |
|
538 | - // All other endpoints require the lax and the strict cookie |
|
539 | - if (!$request->passesStrictCookieCheck()) { |
|
540 | - self::sendSameSiteCookies(); |
|
541 | - // Debug mode gets access to the resources without strict cookie |
|
542 | - // due to the fact that the SabreDAV browser also lives there. |
|
543 | - if (!$config->getSystemValue('debug', false)) { |
|
544 | - http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); |
|
545 | - exit(); |
|
546 | - } |
|
547 | - } |
|
548 | - } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
549 | - self::sendSameSiteCookies(); |
|
550 | - } |
|
551 | - } |
|
552 | - |
|
553 | - public static function init() { |
|
554 | - // calculate the root directories |
|
555 | - OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); |
|
556 | - |
|
557 | - // register autoloader |
|
558 | - $loaderStart = microtime(true); |
|
559 | - require_once __DIR__ . '/autoloader.php'; |
|
560 | - self::$loader = new \OC\Autoloader([ |
|
561 | - OC::$SERVERROOT . '/lib/private/legacy', |
|
562 | - ]); |
|
563 | - if (defined('PHPUNIT_RUN')) { |
|
564 | - self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
|
565 | - } |
|
566 | - spl_autoload_register([self::$loader, 'load']); |
|
567 | - $loaderEnd = microtime(true); |
|
568 | - |
|
569 | - self::$CLI = (php_sapi_name() == 'cli'); |
|
570 | - |
|
571 | - // Add default composer PSR-4 autoloader |
|
572 | - self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
573 | - |
|
574 | - try { |
|
575 | - self::initPaths(); |
|
576 | - // setup 3rdparty autoloader |
|
577 | - $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php'; |
|
578 | - if (!file_exists($vendorAutoLoad)) { |
|
579 | - 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".'); |
|
580 | - } |
|
581 | - require_once $vendorAutoLoad; |
|
582 | - } catch (\RuntimeException $e) { |
|
583 | - if (!self::$CLI) { |
|
584 | - http_response_code(503); |
|
585 | - } |
|
586 | - // we can't use the template error page here, because this needs the |
|
587 | - // DI container which isn't available yet |
|
588 | - print($e->getMessage()); |
|
589 | - exit(); |
|
590 | - } |
|
591 | - |
|
592 | - // setup the basic server |
|
593 | - self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
594 | - self::$server->boot(); |
|
595 | - $eventLogger = \OC::$server->getEventLogger(); |
|
596 | - $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
597 | - $eventLogger->start('boot', 'Initialize'); |
|
598 | - |
|
599 | - // Override php.ini and log everything if we're troubleshooting |
|
600 | - if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
601 | - error_reporting(E_ALL); |
|
602 | - } |
|
603 | - |
|
604 | - // Don't display errors and log them |
|
605 | - @ini_set('display_errors', '0'); |
|
606 | - @ini_set('log_errors', '1'); |
|
607 | - |
|
608 | - if (!date_default_timezone_set('UTC')) { |
|
609 | - throw new \RuntimeException('Could not set timezone to UTC'); |
|
610 | - } |
|
611 | - |
|
612 | - //try to configure php to enable big file uploads. |
|
613 | - //this doesn´t work always depending on the webserver and php configuration. |
|
614 | - //Let´s try to overwrite some defaults anyway |
|
615 | - |
|
616 | - //try to set the maximum execution time to 60min |
|
617 | - if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
618 | - @set_time_limit(3600); |
|
619 | - } |
|
620 | - @ini_set('max_execution_time', '3600'); |
|
621 | - @ini_set('max_input_time', '3600'); |
|
622 | - |
|
623 | - self::setRequiredIniValues(); |
|
624 | - self::handleAuthHeaders(); |
|
625 | - $systemConfig = \OC::$server->get(\OC\SystemConfig::class); |
|
626 | - self::registerAutoloaderCache($systemConfig); |
|
627 | - |
|
628 | - // initialize intl fallback if necessary |
|
629 | - OC_Util::isSetLocaleWorking(); |
|
630 | - |
|
631 | - $config = \OC::$server->get(\OCP\IConfig::class); |
|
632 | - if (!defined('PHPUNIT_RUN')) { |
|
633 | - OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger()); |
|
634 | - $debug = $config->getSystemValue('debug', false); |
|
635 | - OC\Log\ErrorHandler::register($debug); |
|
636 | - } |
|
637 | - |
|
638 | - /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
639 | - $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
640 | - $bootstrapCoordinator->runInitialRegistration(); |
|
641 | - |
|
642 | - $eventLogger->start('init_session', 'Initialize session'); |
|
643 | - OC_App::loadApps(['session']); |
|
644 | - if (!self::$CLI) { |
|
645 | - self::initSession(); |
|
646 | - } |
|
647 | - $eventLogger->end('init_session'); |
|
648 | - self::checkConfig(); |
|
649 | - self::checkInstalled($systemConfig); |
|
650 | - |
|
651 | - OC_Response::addSecurityHeaders(); |
|
652 | - |
|
653 | - self::performSameSiteCookieProtection($config); |
|
654 | - |
|
655 | - if (!defined('OC_CONSOLE')) { |
|
656 | - $errors = OC_Util::checkServer($systemConfig); |
|
657 | - if (count($errors) > 0) { |
|
658 | - if (!self::$CLI) { |
|
659 | - http_response_code(503); |
|
660 | - OC_Util::addStyle('guest'); |
|
661 | - try { |
|
662 | - OC_Template::printGuestPage('', 'error', ['errors' => $errors]); |
|
663 | - exit; |
|
664 | - } catch (\Exception $e) { |
|
665 | - // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
666 | - // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
667 | - } |
|
668 | - } |
|
669 | - |
|
670 | - // Convert l10n string into regular string for usage in database |
|
671 | - $staticErrors = []; |
|
672 | - foreach ($errors as $error) { |
|
673 | - echo $error['error'] . "\n"; |
|
674 | - echo $error['hint'] . "\n\n"; |
|
675 | - $staticErrors[] = [ |
|
676 | - 'error' => (string)$error['error'], |
|
677 | - 'hint' => (string)$error['hint'], |
|
678 | - ]; |
|
679 | - } |
|
680 | - |
|
681 | - try { |
|
682 | - $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
683 | - } catch (\Exception $e) { |
|
684 | - echo('Writing to database failed'); |
|
685 | - } |
|
686 | - exit(1); |
|
687 | - } elseif (self::$CLI && $config->getSystemValue('installed', false)) { |
|
688 | - $config->deleteAppValue('core', 'cronErrors'); |
|
689 | - } |
|
690 | - } |
|
691 | - //try to set the session lifetime |
|
692 | - $sessionLifeTime = self::getSessionLifeTime(); |
|
693 | - @ini_set('gc_maxlifetime', (string)$sessionLifeTime); |
|
694 | - |
|
695 | - // User and Groups |
|
696 | - if (!$systemConfig->getValue("installed", false)) { |
|
697 | - self::$server->getSession()->set('user_id', ''); |
|
698 | - } |
|
699 | - |
|
700 | - OC_User::useBackend(new \OC\User\Database()); |
|
701 | - \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database()); |
|
702 | - |
|
703 | - // Subscribe to the hook |
|
704 | - \OCP\Util::connectHook( |
|
705 | - '\OCA\Files_Sharing\API\Server2Server', |
|
706 | - 'preLoginNameUsedAsUserName', |
|
707 | - '\OC\User\Database', |
|
708 | - 'preLoginNameUsedAsUserName' |
|
709 | - ); |
|
710 | - |
|
711 | - //setup extra user backends |
|
712 | - if (!\OCP\Util::needUpgrade()) { |
|
713 | - OC_User::setupBackends(); |
|
714 | - } else { |
|
715 | - // Run upgrades in incognito mode |
|
716 | - OC_User::setIncognitoMode(true); |
|
717 | - } |
|
718 | - |
|
719 | - self::registerCleanupHooks($systemConfig); |
|
720 | - self::registerFilesystemHooks(); |
|
721 | - self::registerShareHooks($systemConfig); |
|
722 | - self::registerEncryptionWrapperAndHooks(); |
|
723 | - self::registerAccountHooks(); |
|
724 | - self::registerResourceCollectionHooks(); |
|
725 | - self::registerAppRestrictionsHooks(); |
|
726 | - |
|
727 | - // Make sure that the application class is not loaded before the database is setup |
|
728 | - if ($systemConfig->getValue("installed", false)) { |
|
729 | - OC_App::loadApp('settings'); |
|
730 | - } |
|
731 | - |
|
732 | - //make sure temporary files are cleaned up |
|
733 | - $tmpManager = \OC::$server->getTempManager(); |
|
734 | - register_shutdown_function([$tmpManager, 'clean']); |
|
735 | - $lockProvider = \OC::$server->getLockingProvider(); |
|
736 | - register_shutdown_function([$lockProvider, 'releaseAll']); |
|
737 | - |
|
738 | - // Check whether the sample configuration has been copied |
|
739 | - if ($systemConfig->getValue('copied_sample_config', false)) { |
|
740 | - $l = \OC::$server->getL10N('lib'); |
|
741 | - OC_Template::printErrorPage( |
|
742 | - $l->t('Sample configuration detected'), |
|
743 | - $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'), |
|
744 | - 503 |
|
745 | - ); |
|
746 | - return; |
|
747 | - } |
|
748 | - |
|
749 | - $request = \OC::$server->getRequest(); |
|
750 | - $host = $request->getInsecureServerHost(); |
|
751 | - /** |
|
752 | - * if the host passed in headers isn't trusted |
|
753 | - * FIXME: Should not be in here at all :see_no_evil: |
|
754 | - */ |
|
755 | - if (!OC::$CLI |
|
756 | - && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host) |
|
757 | - && $config->getSystemValue('installed', false) |
|
758 | - ) { |
|
759 | - // Allow access to CSS resources |
|
760 | - $isScssRequest = false; |
|
761 | - if (strpos($request->getPathInfo(), '/css/') === 0) { |
|
762 | - $isScssRequest = true; |
|
763 | - } |
|
764 | - |
|
765 | - if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
766 | - http_response_code(400); |
|
767 | - header('Content-Type: application/json'); |
|
768 | - echo '{"error": "Trusted domain error.", "code": 15}'; |
|
769 | - exit(); |
|
770 | - } |
|
771 | - |
|
772 | - if (!$isScssRequest) { |
|
773 | - http_response_code(400); |
|
774 | - |
|
775 | - \OC::$server->getLogger()->info( |
|
776 | - 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
777 | - [ |
|
778 | - 'app' => 'core', |
|
779 | - 'remoteAddress' => $request->getRemoteAddress(), |
|
780 | - 'host' => $host, |
|
781 | - ] |
|
782 | - ); |
|
783 | - |
|
784 | - $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); |
|
785 | - $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains')); |
|
786 | - $tmpl->printPage(); |
|
787 | - |
|
788 | - exit(); |
|
789 | - } |
|
790 | - } |
|
791 | - $eventLogger->end('boot'); |
|
792 | - } |
|
793 | - |
|
794 | - /** |
|
795 | - * register hooks for the cleanup of cache and bruteforce protection |
|
796 | - */ |
|
797 | - public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) { |
|
798 | - //don't try to do this before we are properly setup |
|
799 | - if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
800 | - |
|
801 | - // NOTE: This will be replaced to use OCP |
|
802 | - $userSession = self::$server->getUserSession(); |
|
803 | - $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
804 | - if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
805 | - // reset brute force delay for this IP address and username |
|
806 | - $uid = \OC::$server->getUserSession()->getUser()->getUID(); |
|
807 | - $request = \OC::$server->getRequest(); |
|
808 | - $throttler = \OC::$server->getBruteForceThrottler(); |
|
809 | - $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
810 | - } |
|
811 | - |
|
812 | - try { |
|
813 | - $cache = new \OC\Cache\File(); |
|
814 | - $cache->gc(); |
|
815 | - } catch (\OC\ServerNotAvailableException $e) { |
|
816 | - // not a GC exception, pass it on |
|
817 | - throw $e; |
|
818 | - } catch (\OC\ForbiddenException $e) { |
|
819 | - // filesystem blocked for this request, ignore |
|
820 | - } catch (\Exception $e) { |
|
821 | - // a GC exception should not prevent users from using OC, |
|
822 | - // so log the exception |
|
823 | - \OC::$server->getLogger()->logException($e, [ |
|
824 | - 'message' => 'Exception when running cache gc.', |
|
825 | - 'level' => ILogger::WARN, |
|
826 | - 'app' => 'core', |
|
827 | - ]); |
|
828 | - } |
|
829 | - }); |
|
830 | - } |
|
831 | - } |
|
832 | - |
|
833 | - private static function registerEncryptionWrapperAndHooks() { |
|
834 | - $manager = self::$server->getEncryptionManager(); |
|
835 | - \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); |
|
836 | - |
|
837 | - $enabled = $manager->isEnabled(); |
|
838 | - if ($enabled) { |
|
839 | - \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared'); |
|
840 | - \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared'); |
|
841 | - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename'); |
|
842 | - \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore'); |
|
843 | - } |
|
844 | - } |
|
845 | - |
|
846 | - private static function registerAccountHooks() { |
|
847 | - /** @var IEventDispatcher $dispatcher */ |
|
848 | - $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
849 | - $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
850 | - } |
|
851 | - |
|
852 | - private static function registerAppRestrictionsHooks() { |
|
853 | - /** @var \OC\Group\Manager $groupManager */ |
|
854 | - $groupManager = self::$server->query(\OCP\IGroupManager::class); |
|
855 | - $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
856 | - $appManager = self::$server->getAppManager(); |
|
857 | - $apps = $appManager->getEnabledAppsForGroup($group); |
|
858 | - foreach ($apps as $appId) { |
|
859 | - $restrictions = $appManager->getAppRestriction($appId); |
|
860 | - if (empty($restrictions)) { |
|
861 | - continue; |
|
862 | - } |
|
863 | - $key = array_search($group->getGID(), $restrictions); |
|
864 | - unset($restrictions[$key]); |
|
865 | - $restrictions = array_values($restrictions); |
|
866 | - if (empty($restrictions)) { |
|
867 | - $appManager->disableApp($appId); |
|
868 | - } else { |
|
869 | - $appManager->enableAppForGroups($appId, $restrictions); |
|
870 | - } |
|
871 | - } |
|
872 | - }); |
|
873 | - } |
|
874 | - |
|
875 | - private static function registerResourceCollectionHooks() { |
|
876 | - \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher()); |
|
877 | - } |
|
878 | - |
|
879 | - /** |
|
880 | - * register hooks for the filesystem |
|
881 | - */ |
|
882 | - public static function registerFilesystemHooks() { |
|
883 | - // Check for blacklisted files |
|
884 | - OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted'); |
|
885 | - OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted'); |
|
886 | - } |
|
887 | - |
|
888 | - /** |
|
889 | - * register hooks for sharing |
|
890 | - */ |
|
891 | - public static function registerShareHooks(\OC\SystemConfig $systemConfig) { |
|
892 | - if ($systemConfig->getValue('installed')) { |
|
893 | - OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser'); |
|
894 | - OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup'); |
|
895 | - |
|
896 | - /** @var IEventDispatcher $dispatcher */ |
|
897 | - $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
898 | - $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class); |
|
899 | - } |
|
900 | - } |
|
901 | - |
|
902 | - protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) { |
|
903 | - // The class loader takes an optional low-latency cache, which MUST be |
|
904 | - // namespaced. The instanceid is used for namespacing, but might be |
|
905 | - // unavailable at this point. Furthermore, it might not be possible to |
|
906 | - // generate an instanceid via \OC_Util::getInstanceId() because the |
|
907 | - // config file may not be writable. As such, we only register a class |
|
908 | - // loader cache if instanceid is available without trying to create one. |
|
909 | - $instanceId = $systemConfig->getValue('instanceid', null); |
|
910 | - if ($instanceId) { |
|
911 | - try { |
|
912 | - $memcacheFactory = \OC::$server->getMemCacheFactory(); |
|
913 | - self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); |
|
914 | - } catch (\Exception $ex) { |
|
915 | - } |
|
916 | - } |
|
917 | - } |
|
918 | - |
|
919 | - /** |
|
920 | - * Handle the request |
|
921 | - */ |
|
922 | - public static function handleRequest() { |
|
923 | - \OC::$server->getEventLogger()->start('handle_request', 'Handle request'); |
|
924 | - $systemConfig = \OC::$server->getSystemConfig(); |
|
925 | - |
|
926 | - // Check if Nextcloud is installed or in maintenance (update) mode |
|
927 | - if (!$systemConfig->getValue('installed', false)) { |
|
928 | - \OC::$server->getSession()->clear(); |
|
929 | - $setupHelper = new OC\Setup( |
|
930 | - $systemConfig, |
|
931 | - \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class), |
|
932 | - \OC::$server->getL10N('lib'), |
|
933 | - \OC::$server->query(\OCP\Defaults::class), |
|
934 | - \OC::$server->get(\Psr\Log\LoggerInterface::class), |
|
935 | - \OC::$server->getSecureRandom(), |
|
936 | - \OC::$server->query(\OC\Installer::class) |
|
937 | - ); |
|
938 | - $controller = new OC\Core\Controller\SetupController($setupHelper); |
|
939 | - $controller->run($_POST); |
|
940 | - exit(); |
|
941 | - } |
|
942 | - |
|
943 | - $request = \OC::$server->getRequest(); |
|
944 | - $requestPath = $request->getRawPathInfo(); |
|
945 | - if ($requestPath === '/heartbeat') { |
|
946 | - return; |
|
947 | - } |
|
948 | - if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
949 | - self::checkMaintenanceMode($systemConfig); |
|
950 | - |
|
951 | - if (\OCP\Util::needUpgrade()) { |
|
952 | - if (function_exists('opcache_reset')) { |
|
953 | - opcache_reset(); |
|
954 | - } |
|
955 | - if (!((bool) $systemConfig->getValue('maintenance', false))) { |
|
956 | - self::printUpgradePage($systemConfig); |
|
957 | - exit(); |
|
958 | - } |
|
959 | - } |
|
960 | - } |
|
961 | - |
|
962 | - // emergency app disabling |
|
963 | - if ($requestPath === '/disableapp' |
|
964 | - && $request->getMethod() === 'POST' |
|
965 | - && ((array)$request->getParam('appid')) !== '' |
|
966 | - ) { |
|
967 | - \OC_JSON::callCheck(); |
|
968 | - \OC_JSON::checkAdminUser(); |
|
969 | - $appIds = (array)$request->getParam('appid'); |
|
970 | - foreach ($appIds as $appId) { |
|
971 | - $appId = \OC_App::cleanAppId($appId); |
|
972 | - \OC::$server->getAppManager()->disableApp($appId); |
|
973 | - } |
|
974 | - \OC_JSON::success(); |
|
975 | - exit(); |
|
976 | - } |
|
977 | - |
|
978 | - // Always load authentication apps |
|
979 | - OC_App::loadApps(['authentication']); |
|
980 | - |
|
981 | - // Load minimum set of apps |
|
982 | - if (!\OCP\Util::needUpgrade() |
|
983 | - && !((bool) $systemConfig->getValue('maintenance', false))) { |
|
984 | - // For logged-in users: Load everything |
|
985 | - if (\OC::$server->getUserSession()->isLoggedIn()) { |
|
986 | - OC_App::loadApps(); |
|
987 | - } else { |
|
988 | - // For guests: Load only filesystem and logging |
|
989 | - OC_App::loadApps(['filesystem', 'logging']); |
|
990 | - self::handleLogin($request); |
|
991 | - } |
|
992 | - } |
|
993 | - |
|
994 | - if (!self::$CLI) { |
|
995 | - try { |
|
996 | - if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) { |
|
997 | - OC_App::loadApps(['filesystem', 'logging']); |
|
998 | - OC_App::loadApps(); |
|
999 | - } |
|
1000 | - OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1001 | - return; |
|
1002 | - } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1003 | - //header('HTTP/1.0 404 Not Found'); |
|
1004 | - } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1005 | - http_response_code(405); |
|
1006 | - return; |
|
1007 | - } |
|
1008 | - } |
|
1009 | - |
|
1010 | - // Handle WebDAV |
|
1011 | - if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1012 | - // not allowed any more to prevent people |
|
1013 | - // mounting this root directly. |
|
1014 | - // Users need to mount remote.php/webdav instead. |
|
1015 | - http_response_code(405); |
|
1016 | - return; |
|
1017 | - } |
|
1018 | - |
|
1019 | - // Someone is logged in |
|
1020 | - if (\OC::$server->getUserSession()->isLoggedIn()) { |
|
1021 | - OC_App::loadApps(); |
|
1022 | - OC_User::setupBackends(); |
|
1023 | - OC_Util::setupFS(); |
|
1024 | - // FIXME |
|
1025 | - // Redirect to default application |
|
1026 | - OC_Util::redirectToDefaultPage(); |
|
1027 | - } else { |
|
1028 | - // Not handled and not logged in |
|
1029 | - header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1030 | - } |
|
1031 | - } |
|
1032 | - |
|
1033 | - /** |
|
1034 | - * Check login: apache auth, auth token, basic auth |
|
1035 | - * |
|
1036 | - * @param OCP\IRequest $request |
|
1037 | - * @return boolean |
|
1038 | - */ |
|
1039 | - public static function handleLogin(OCP\IRequest $request) { |
|
1040 | - $userSession = self::$server->getUserSession(); |
|
1041 | - if (OC_User::handleApacheAuth()) { |
|
1042 | - return true; |
|
1043 | - } |
|
1044 | - if ($userSession->tryTokenLogin($request)) { |
|
1045 | - return true; |
|
1046 | - } |
|
1047 | - if (isset($_COOKIE['nc_username']) |
|
1048 | - && isset($_COOKIE['nc_token']) |
|
1049 | - && isset($_COOKIE['nc_session_id']) |
|
1050 | - && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1051 | - return true; |
|
1052 | - } |
|
1053 | - if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) { |
|
1054 | - return true; |
|
1055 | - } |
|
1056 | - return false; |
|
1057 | - } |
|
1058 | - |
|
1059 | - protected static function handleAuthHeaders() { |
|
1060 | - //copy http auth headers for apache+php-fcgid work around |
|
1061 | - if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1062 | - $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1063 | - } |
|
1064 | - |
|
1065 | - // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1066 | - $vars = [ |
|
1067 | - 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1068 | - 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1069 | - ]; |
|
1070 | - foreach ($vars as $var) { |
|
1071 | - if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1072 | - $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1073 | - if (count($credentials) === 2) { |
|
1074 | - $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1075 | - $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1076 | - break; |
|
1077 | - } |
|
1078 | - } |
|
1079 | - } |
|
1080 | - } |
|
81 | + /** |
|
82 | + * Associative array for autoloading. classname => filename |
|
83 | + */ |
|
84 | + public static $CLASSPATH = []; |
|
85 | + /** |
|
86 | + * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
87 | + */ |
|
88 | + public static $SERVERROOT = ''; |
|
89 | + /** |
|
90 | + * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
91 | + */ |
|
92 | + private static $SUBURI = ''; |
|
93 | + /** |
|
94 | + * the Nextcloud root path for http requests (e.g. nextcloud/) |
|
95 | + */ |
|
96 | + public static $WEBROOT = ''; |
|
97 | + /** |
|
98 | + * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
99 | + * web path in 'url' |
|
100 | + */ |
|
101 | + public static $APPSROOTS = []; |
|
102 | + |
|
103 | + /** |
|
104 | + * @var string |
|
105 | + */ |
|
106 | + public static $configDir; |
|
107 | + |
|
108 | + /** |
|
109 | + * requested app |
|
110 | + */ |
|
111 | + public static $REQUESTEDAPP = ''; |
|
112 | + |
|
113 | + /** |
|
114 | + * check if Nextcloud runs in cli mode |
|
115 | + */ |
|
116 | + public static $CLI = false; |
|
117 | + |
|
118 | + /** |
|
119 | + * @var \OC\Autoloader $loader |
|
120 | + */ |
|
121 | + public static $loader = null; |
|
122 | + |
|
123 | + /** @var \Composer\Autoload\ClassLoader $composerAutoloader */ |
|
124 | + public static $composerAutoloader = null; |
|
125 | + |
|
126 | + /** |
|
127 | + * @var \OC\Server |
|
128 | + */ |
|
129 | + public static $server = null; |
|
130 | + |
|
131 | + /** |
|
132 | + * @var \OC\Config |
|
133 | + */ |
|
134 | + private static $config = null; |
|
135 | + |
|
136 | + /** |
|
137 | + * @throws \RuntimeException when the 3rdparty directory is missing or |
|
138 | + * the app path list is empty or contains an invalid path |
|
139 | + */ |
|
140 | + public static function initPaths() { |
|
141 | + if (defined('PHPUNIT_CONFIG_DIR')) { |
|
142 | + self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
143 | + } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
144 | + self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
145 | + } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
146 | + self::$configDir = rtrim($dir, '/') . '/'; |
|
147 | + } else { |
|
148 | + self::$configDir = OC::$SERVERROOT . '/config/'; |
|
149 | + } |
|
150 | + self::$config = new \OC\Config(self::$configDir); |
|
151 | + |
|
152 | + OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT))); |
|
153 | + /** |
|
154 | + * FIXME: The following lines are required because we can't yet instantiate |
|
155 | + * \OC::$server->getRequest() since \OC::$server does not yet exist. |
|
156 | + */ |
|
157 | + $params = [ |
|
158 | + 'server' => [ |
|
159 | + 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'], |
|
160 | + 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'], |
|
161 | + ], |
|
162 | + ]; |
|
163 | + $fakeRequest = new \OC\AppFramework\Http\Request($params, new \OC\Security\SecureRandom(), new \OC\AllConfig(new \OC\SystemConfig(self::$config))); |
|
164 | + $scriptName = $fakeRequest->getScriptName(); |
|
165 | + if (substr($scriptName, -1) == '/') { |
|
166 | + $scriptName .= 'index.php'; |
|
167 | + //make sure suburi follows the same rules as scriptName |
|
168 | + if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
169 | + if (substr(OC::$SUBURI, -1) != '/') { |
|
170 | + OC::$SUBURI = OC::$SUBURI . '/'; |
|
171 | + } |
|
172 | + OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
173 | + } |
|
174 | + } |
|
175 | + |
|
176 | + |
|
177 | + if (OC::$CLI) { |
|
178 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
179 | + } else { |
|
180 | + if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
181 | + OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
182 | + |
|
183 | + if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
184 | + OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
185 | + } |
|
186 | + } else { |
|
187 | + // The scriptName is not ending with OC::$SUBURI |
|
188 | + // This most likely means that we are calling from CLI. |
|
189 | + // However some cron jobs still need to generate |
|
190 | + // a web URL, so we use overwritewebroot as a fallback. |
|
191 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
192 | + } |
|
193 | + |
|
194 | + // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
195 | + // slash which is required by URL generation. |
|
196 | + if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
|
197 | + substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
198 | + header('Location: '.\OC::$WEBROOT.'/'); |
|
199 | + exit(); |
|
200 | + } |
|
201 | + } |
|
202 | + |
|
203 | + // search the apps folder |
|
204 | + $config_paths = self::$config->getValue('apps_paths', []); |
|
205 | + if (!empty($config_paths)) { |
|
206 | + foreach ($config_paths as $paths) { |
|
207 | + if (isset($paths['url']) && isset($paths['path'])) { |
|
208 | + $paths['url'] = rtrim($paths['url'], '/'); |
|
209 | + $paths['path'] = rtrim($paths['path'], '/'); |
|
210 | + OC::$APPSROOTS[] = $paths; |
|
211 | + } |
|
212 | + } |
|
213 | + } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
214 | + OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
215 | + } |
|
216 | + |
|
217 | + if (empty(OC::$APPSROOTS)) { |
|
218 | + throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
219 | + . '. You can also configure the location in the config.php file.'); |
|
220 | + } |
|
221 | + $paths = []; |
|
222 | + foreach (OC::$APPSROOTS as $path) { |
|
223 | + $paths[] = $path['path']; |
|
224 | + if (!is_dir($path['path'])) { |
|
225 | + throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
226 | + . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
227 | + } |
|
228 | + } |
|
229 | + |
|
230 | + // set the right include path |
|
231 | + set_include_path( |
|
232 | + implode(PATH_SEPARATOR, $paths) |
|
233 | + ); |
|
234 | + } |
|
235 | + |
|
236 | + public static function checkConfig() { |
|
237 | + $l = \OC::$server->getL10N('lib'); |
|
238 | + |
|
239 | + // Create config if it does not already exist |
|
240 | + $configFilePath = self::$configDir .'/config.php'; |
|
241 | + if (!file_exists($configFilePath)) { |
|
242 | + @touch($configFilePath); |
|
243 | + } |
|
244 | + |
|
245 | + // Check if config is writable |
|
246 | + $configFileWritable = is_writable($configFilePath); |
|
247 | + if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
|
248 | + || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
249 | + $urlGenerator = \OC::$server->getURLGenerator(); |
|
250 | + |
|
251 | + if (self::$CLI) { |
|
252 | + echo $l->t('Cannot write into "config" directory!')."\n"; |
|
253 | + echo $l->t('This can usually be fixed by giving the webserver write access to the config directory.')."\n"; |
|
254 | + echo "\n"; |
|
255 | + echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n"; |
|
256 | + echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n"; |
|
257 | + exit; |
|
258 | + } else { |
|
259 | + OC_Template::printErrorPage( |
|
260 | + $l->t('Cannot write into "config" directory!'), |
|
261 | + $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . ' ' |
|
262 | + . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
263 | + . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
264 | + 503 |
|
265 | + ); |
|
266 | + } |
|
267 | + } |
|
268 | + } |
|
269 | + |
|
270 | + public static function checkInstalled(\OC\SystemConfig $systemConfig) { |
|
271 | + if (defined('OC_CONSOLE')) { |
|
272 | + return; |
|
273 | + } |
|
274 | + // Redirect to installer if not installed |
|
275 | + if (!$systemConfig->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(\OC\SystemConfig $systemConfig) { |
|
287 | + // Allow ajax update script to execute without being stopped |
|
288 | + if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
289 | + // send http status 503 |
|
290 | + http_response_code(503); |
|
291 | + header('Retry-After: 120'); |
|
292 | + |
|
293 | + // render error page |
|
294 | + $template = new OC_Template('', 'update.user', 'guest'); |
|
295 | + OC_Util::addScript('dist/maintenance'); |
|
296 | + OC_Util::addStyle('core', 'guest'); |
|
297 | + $template->printPage(); |
|
298 | + die(); |
|
299 | + } |
|
300 | + } |
|
301 | + |
|
302 | + /** |
|
303 | + * Prints the upgrade page |
|
304 | + * |
|
305 | + * @param \OC\SystemConfig $systemConfig |
|
306 | + */ |
|
307 | + private static function printUpgradePage(\OC\SystemConfig $systemConfig) { |
|
308 | + $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
309 | + $tooBig = false; |
|
310 | + if (!$disableWebUpdater) { |
|
311 | + $apps = \OC::$server->getAppManager(); |
|
312 | + if ($apps->isInstalled('user_ldap')) { |
|
313 | + $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
314 | + |
|
315 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
316 | + ->from('ldap_user_mapping') |
|
317 | + ->execute(); |
|
318 | + $row = $result->fetch(); |
|
319 | + $result->closeCursor(); |
|
320 | + |
|
321 | + $tooBig = ($row['user_count'] > 50); |
|
322 | + } |
|
323 | + if (!$tooBig && $apps->isInstalled('user_saml')) { |
|
324 | + $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
325 | + |
|
326 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
327 | + ->from('user_saml_users') |
|
328 | + ->execute(); |
|
329 | + $row = $result->fetch(); |
|
330 | + $result->closeCursor(); |
|
331 | + |
|
332 | + $tooBig = ($row['user_count'] > 50); |
|
333 | + } |
|
334 | + if (!$tooBig) { |
|
335 | + // count users |
|
336 | + $stats = \OC::$server->getUserManager()->countUsers(); |
|
337 | + $totalUsers = array_sum($stats); |
|
338 | + $tooBig = ($totalUsers > 50); |
|
339 | + } |
|
340 | + } |
|
341 | + $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) && |
|
342 | + $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
343 | + |
|
344 | + if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
345 | + // send http status 503 |
|
346 | + http_response_code(503); |
|
347 | + header('Retry-After: 120'); |
|
348 | + |
|
349 | + // render error page |
|
350 | + $template = new OC_Template('', 'update.use-cli', 'guest'); |
|
351 | + $template->assign('productName', 'nextcloud'); // for now |
|
352 | + $template->assign('version', OC_Util::getVersionString()); |
|
353 | + $template->assign('tooBig', $tooBig); |
|
354 | + |
|
355 | + $template->printPage(); |
|
356 | + die(); |
|
357 | + } |
|
358 | + |
|
359 | + // check whether this is a core update or apps update |
|
360 | + $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
361 | + $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
362 | + |
|
363 | + // if not a core upgrade, then it's apps upgrade |
|
364 | + $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
365 | + |
|
366 | + $oldTheme = $systemConfig->getValue('theme'); |
|
367 | + $systemConfig->setValue('theme', ''); |
|
368 | + OC_Util::addScript('update'); |
|
369 | + |
|
370 | + /** @var \OC\App\AppManager $appManager */ |
|
371 | + $appManager = \OC::$server->getAppManager(); |
|
372 | + |
|
373 | + $tmpl = new OC_Template('', 'update.admin', 'guest'); |
|
374 | + $tmpl->assign('version', OC_Util::getVersionString()); |
|
375 | + $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
376 | + |
|
377 | + // get third party apps |
|
378 | + $ocVersion = \OCP\Util::getVersion(); |
|
379 | + $ocVersion = implode('.', $ocVersion); |
|
380 | + $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
381 | + $incompatibleShippedApps = []; |
|
382 | + foreach ($incompatibleApps as $appInfo) { |
|
383 | + if ($appManager->isShipped($appInfo['id'])) { |
|
384 | + $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
385 | + } |
|
386 | + } |
|
387 | + |
|
388 | + if (!empty($incompatibleShippedApps)) { |
|
389 | + $l = \OC::$server->getL10N('core'); |
|
390 | + $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]); |
|
391 | + throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint); |
|
392 | + } |
|
393 | + |
|
394 | + $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
395 | + $tmpl->assign('incompatibleAppsList', $incompatibleApps); |
|
396 | + try { |
|
397 | + $defaults = new \OC_Defaults(); |
|
398 | + $tmpl->assign('productName', $defaults->getName()); |
|
399 | + } catch (Throwable $error) { |
|
400 | + $tmpl->assign('productName', 'Nextcloud'); |
|
401 | + } |
|
402 | + $tmpl->assign('oldTheme', $oldTheme); |
|
403 | + $tmpl->printPage(); |
|
404 | + } |
|
405 | + |
|
406 | + public static function initSession() { |
|
407 | + if (self::$server->getRequest()->getServerProtocol() === 'https') { |
|
408 | + ini_set('session.cookie_secure', 'true'); |
|
409 | + } |
|
410 | + |
|
411 | + // prevents javascript from accessing php session cookies |
|
412 | + ini_set('session.cookie_httponly', 'true'); |
|
413 | + |
|
414 | + // set the cookie path to the Nextcloud directory |
|
415 | + $cookie_path = OC::$WEBROOT ? : '/'; |
|
416 | + ini_set('session.cookie_path', $cookie_path); |
|
417 | + |
|
418 | + // Let the session name be changed in the initSession Hook |
|
419 | + $sessionName = OC_Util::getInstanceId(); |
|
420 | + |
|
421 | + try { |
|
422 | + // set the session name to the instance id - which is unique |
|
423 | + $session = new \OC\Session\Internal($sessionName); |
|
424 | + |
|
425 | + $cryptoWrapper = \OC::$server->getSessionCryptoWrapper(); |
|
426 | + $session = $cryptoWrapper->wrapSession($session); |
|
427 | + self::$server->setSession($session); |
|
428 | + |
|
429 | + // if session can't be started break with http 500 error |
|
430 | + } catch (Exception $e) { |
|
431 | + \OC::$server->getLogger()->logException($e, ['app' => 'base']); |
|
432 | + //show the user a detailed error page |
|
433 | + OC_Template::printExceptionErrorPage($e, 500); |
|
434 | + die(); |
|
435 | + } |
|
436 | + |
|
437 | + $sessionLifeTime = self::getSessionLifeTime(); |
|
438 | + |
|
439 | + // session timeout |
|
440 | + if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
441 | + if (isset($_COOKIE[session_name()])) { |
|
442 | + setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
443 | + } |
|
444 | + \OC::$server->getUserSession()->logout(); |
|
445 | + } |
|
446 | + |
|
447 | + $session->set('LAST_ACTIVITY', time()); |
|
448 | + } |
|
449 | + |
|
450 | + /** |
|
451 | + * @return string |
|
452 | + */ |
|
453 | + private static function getSessionLifeTime() { |
|
454 | + return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24); |
|
455 | + } |
|
456 | + |
|
457 | + /** |
|
458 | + * Try to set some values to the required Nextcloud default |
|
459 | + */ |
|
460 | + public static function setRequiredIniValues() { |
|
461 | + @ini_set('default_charset', 'UTF-8'); |
|
462 | + @ini_set('gd.jpeg_ignore_warning', '1'); |
|
463 | + } |
|
464 | + |
|
465 | + /** |
|
466 | + * Send the same site cookies |
|
467 | + */ |
|
468 | + private static function sendSameSiteCookies() { |
|
469 | + $cookieParams = session_get_cookie_params(); |
|
470 | + $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
471 | + $policies = [ |
|
472 | + 'lax', |
|
473 | + 'strict', |
|
474 | + ]; |
|
475 | + |
|
476 | + // Append __Host to the cookie if it meets the requirements |
|
477 | + $cookiePrefix = ''; |
|
478 | + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
479 | + $cookiePrefix = '__Host-'; |
|
480 | + } |
|
481 | + |
|
482 | + foreach ($policies as $policy) { |
|
483 | + header( |
|
484 | + sprintf( |
|
485 | + 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
486 | + $cookiePrefix, |
|
487 | + $policy, |
|
488 | + $cookieParams['path'], |
|
489 | + $policy |
|
490 | + ), |
|
491 | + false |
|
492 | + ); |
|
493 | + } |
|
494 | + } |
|
495 | + |
|
496 | + /** |
|
497 | + * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
498 | + * be set in every request if cookies are sent to add a second level of |
|
499 | + * defense against CSRF. |
|
500 | + * |
|
501 | + * If the cookie is not sent this will set the cookie and reload the page. |
|
502 | + * We use an additional cookie since we want to protect logout CSRF and |
|
503 | + * also we can't directly interfere with PHP's session mechanism. |
|
504 | + */ |
|
505 | + private static function performSameSiteCookieProtection(\OCP\IConfig $config) { |
|
506 | + $request = \OC::$server->getRequest(); |
|
507 | + |
|
508 | + // Some user agents are notorious and don't really properly follow HTTP |
|
509 | + // specifications. For those, have an automated opt-out. Since the protection |
|
510 | + // for remote.php is applied in base.php as starting point we need to opt out |
|
511 | + // here. |
|
512 | + $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
513 | + |
|
514 | + // Fallback, if csrf.optout is unset |
|
515 | + if (!is_array($incompatibleUserAgents)) { |
|
516 | + $incompatibleUserAgents = [ |
|
517 | + // OS X Finder |
|
518 | + '/^WebDAVFS/', |
|
519 | + // Windows webdav drive |
|
520 | + '/^Microsoft-WebDAV-MiniRedir/', |
|
521 | + ]; |
|
522 | + } |
|
523 | + |
|
524 | + if ($request->isUserAgent($incompatibleUserAgents)) { |
|
525 | + return; |
|
526 | + } |
|
527 | + |
|
528 | + if (count($_COOKIE) > 0) { |
|
529 | + $requestUri = $request->getScriptName(); |
|
530 | + $processingScript = explode('/', $requestUri); |
|
531 | + $processingScript = $processingScript[count($processingScript) - 1]; |
|
532 | + |
|
533 | + // index.php routes are handled in the middleware |
|
534 | + if ($processingScript === 'index.php') { |
|
535 | + return; |
|
536 | + } |
|
537 | + |
|
538 | + // All other endpoints require the lax and the strict cookie |
|
539 | + if (!$request->passesStrictCookieCheck()) { |
|
540 | + self::sendSameSiteCookies(); |
|
541 | + // Debug mode gets access to the resources without strict cookie |
|
542 | + // due to the fact that the SabreDAV browser also lives there. |
|
543 | + if (!$config->getSystemValue('debug', false)) { |
|
544 | + http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); |
|
545 | + exit(); |
|
546 | + } |
|
547 | + } |
|
548 | + } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
549 | + self::sendSameSiteCookies(); |
|
550 | + } |
|
551 | + } |
|
552 | + |
|
553 | + public static function init() { |
|
554 | + // calculate the root directories |
|
555 | + OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); |
|
556 | + |
|
557 | + // register autoloader |
|
558 | + $loaderStart = microtime(true); |
|
559 | + require_once __DIR__ . '/autoloader.php'; |
|
560 | + self::$loader = new \OC\Autoloader([ |
|
561 | + OC::$SERVERROOT . '/lib/private/legacy', |
|
562 | + ]); |
|
563 | + if (defined('PHPUNIT_RUN')) { |
|
564 | + self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
|
565 | + } |
|
566 | + spl_autoload_register([self::$loader, 'load']); |
|
567 | + $loaderEnd = microtime(true); |
|
568 | + |
|
569 | + self::$CLI = (php_sapi_name() == 'cli'); |
|
570 | + |
|
571 | + // Add default composer PSR-4 autoloader |
|
572 | + self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
573 | + |
|
574 | + try { |
|
575 | + self::initPaths(); |
|
576 | + // setup 3rdparty autoloader |
|
577 | + $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php'; |
|
578 | + if (!file_exists($vendorAutoLoad)) { |
|
579 | + 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".'); |
|
580 | + } |
|
581 | + require_once $vendorAutoLoad; |
|
582 | + } catch (\RuntimeException $e) { |
|
583 | + if (!self::$CLI) { |
|
584 | + http_response_code(503); |
|
585 | + } |
|
586 | + // we can't use the template error page here, because this needs the |
|
587 | + // DI container which isn't available yet |
|
588 | + print($e->getMessage()); |
|
589 | + exit(); |
|
590 | + } |
|
591 | + |
|
592 | + // setup the basic server |
|
593 | + self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
594 | + self::$server->boot(); |
|
595 | + $eventLogger = \OC::$server->getEventLogger(); |
|
596 | + $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
597 | + $eventLogger->start('boot', 'Initialize'); |
|
598 | + |
|
599 | + // Override php.ini and log everything if we're troubleshooting |
|
600 | + if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
601 | + error_reporting(E_ALL); |
|
602 | + } |
|
603 | + |
|
604 | + // Don't display errors and log them |
|
605 | + @ini_set('display_errors', '0'); |
|
606 | + @ini_set('log_errors', '1'); |
|
607 | + |
|
608 | + if (!date_default_timezone_set('UTC')) { |
|
609 | + throw new \RuntimeException('Could not set timezone to UTC'); |
|
610 | + } |
|
611 | + |
|
612 | + //try to configure php to enable big file uploads. |
|
613 | + //this doesn´t work always depending on the webserver and php configuration. |
|
614 | + //Let´s try to overwrite some defaults anyway |
|
615 | + |
|
616 | + //try to set the maximum execution time to 60min |
|
617 | + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
618 | + @set_time_limit(3600); |
|
619 | + } |
|
620 | + @ini_set('max_execution_time', '3600'); |
|
621 | + @ini_set('max_input_time', '3600'); |
|
622 | + |
|
623 | + self::setRequiredIniValues(); |
|
624 | + self::handleAuthHeaders(); |
|
625 | + $systemConfig = \OC::$server->get(\OC\SystemConfig::class); |
|
626 | + self::registerAutoloaderCache($systemConfig); |
|
627 | + |
|
628 | + // initialize intl fallback if necessary |
|
629 | + OC_Util::isSetLocaleWorking(); |
|
630 | + |
|
631 | + $config = \OC::$server->get(\OCP\IConfig::class); |
|
632 | + if (!defined('PHPUNIT_RUN')) { |
|
633 | + OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger()); |
|
634 | + $debug = $config->getSystemValue('debug', false); |
|
635 | + OC\Log\ErrorHandler::register($debug); |
|
636 | + } |
|
637 | + |
|
638 | + /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
639 | + $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
640 | + $bootstrapCoordinator->runInitialRegistration(); |
|
641 | + |
|
642 | + $eventLogger->start('init_session', 'Initialize session'); |
|
643 | + OC_App::loadApps(['session']); |
|
644 | + if (!self::$CLI) { |
|
645 | + self::initSession(); |
|
646 | + } |
|
647 | + $eventLogger->end('init_session'); |
|
648 | + self::checkConfig(); |
|
649 | + self::checkInstalled($systemConfig); |
|
650 | + |
|
651 | + OC_Response::addSecurityHeaders(); |
|
652 | + |
|
653 | + self::performSameSiteCookieProtection($config); |
|
654 | + |
|
655 | + if (!defined('OC_CONSOLE')) { |
|
656 | + $errors = OC_Util::checkServer($systemConfig); |
|
657 | + if (count($errors) > 0) { |
|
658 | + if (!self::$CLI) { |
|
659 | + http_response_code(503); |
|
660 | + OC_Util::addStyle('guest'); |
|
661 | + try { |
|
662 | + OC_Template::printGuestPage('', 'error', ['errors' => $errors]); |
|
663 | + exit; |
|
664 | + } catch (\Exception $e) { |
|
665 | + // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
666 | + // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
667 | + } |
|
668 | + } |
|
669 | + |
|
670 | + // Convert l10n string into regular string for usage in database |
|
671 | + $staticErrors = []; |
|
672 | + foreach ($errors as $error) { |
|
673 | + echo $error['error'] . "\n"; |
|
674 | + echo $error['hint'] . "\n\n"; |
|
675 | + $staticErrors[] = [ |
|
676 | + 'error' => (string)$error['error'], |
|
677 | + 'hint' => (string)$error['hint'], |
|
678 | + ]; |
|
679 | + } |
|
680 | + |
|
681 | + try { |
|
682 | + $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
683 | + } catch (\Exception $e) { |
|
684 | + echo('Writing to database failed'); |
|
685 | + } |
|
686 | + exit(1); |
|
687 | + } elseif (self::$CLI && $config->getSystemValue('installed', false)) { |
|
688 | + $config->deleteAppValue('core', 'cronErrors'); |
|
689 | + } |
|
690 | + } |
|
691 | + //try to set the session lifetime |
|
692 | + $sessionLifeTime = self::getSessionLifeTime(); |
|
693 | + @ini_set('gc_maxlifetime', (string)$sessionLifeTime); |
|
694 | + |
|
695 | + // User and Groups |
|
696 | + if (!$systemConfig->getValue("installed", false)) { |
|
697 | + self::$server->getSession()->set('user_id', ''); |
|
698 | + } |
|
699 | + |
|
700 | + OC_User::useBackend(new \OC\User\Database()); |
|
701 | + \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database()); |
|
702 | + |
|
703 | + // Subscribe to the hook |
|
704 | + \OCP\Util::connectHook( |
|
705 | + '\OCA\Files_Sharing\API\Server2Server', |
|
706 | + 'preLoginNameUsedAsUserName', |
|
707 | + '\OC\User\Database', |
|
708 | + 'preLoginNameUsedAsUserName' |
|
709 | + ); |
|
710 | + |
|
711 | + //setup extra user backends |
|
712 | + if (!\OCP\Util::needUpgrade()) { |
|
713 | + OC_User::setupBackends(); |
|
714 | + } else { |
|
715 | + // Run upgrades in incognito mode |
|
716 | + OC_User::setIncognitoMode(true); |
|
717 | + } |
|
718 | + |
|
719 | + self::registerCleanupHooks($systemConfig); |
|
720 | + self::registerFilesystemHooks(); |
|
721 | + self::registerShareHooks($systemConfig); |
|
722 | + self::registerEncryptionWrapperAndHooks(); |
|
723 | + self::registerAccountHooks(); |
|
724 | + self::registerResourceCollectionHooks(); |
|
725 | + self::registerAppRestrictionsHooks(); |
|
726 | + |
|
727 | + // Make sure that the application class is not loaded before the database is setup |
|
728 | + if ($systemConfig->getValue("installed", false)) { |
|
729 | + OC_App::loadApp('settings'); |
|
730 | + } |
|
731 | + |
|
732 | + //make sure temporary files are cleaned up |
|
733 | + $tmpManager = \OC::$server->getTempManager(); |
|
734 | + register_shutdown_function([$tmpManager, 'clean']); |
|
735 | + $lockProvider = \OC::$server->getLockingProvider(); |
|
736 | + register_shutdown_function([$lockProvider, 'releaseAll']); |
|
737 | + |
|
738 | + // Check whether the sample configuration has been copied |
|
739 | + if ($systemConfig->getValue('copied_sample_config', false)) { |
|
740 | + $l = \OC::$server->getL10N('lib'); |
|
741 | + OC_Template::printErrorPage( |
|
742 | + $l->t('Sample configuration detected'), |
|
743 | + $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'), |
|
744 | + 503 |
|
745 | + ); |
|
746 | + return; |
|
747 | + } |
|
748 | + |
|
749 | + $request = \OC::$server->getRequest(); |
|
750 | + $host = $request->getInsecureServerHost(); |
|
751 | + /** |
|
752 | + * if the host passed in headers isn't trusted |
|
753 | + * FIXME: Should not be in here at all :see_no_evil: |
|
754 | + */ |
|
755 | + if (!OC::$CLI |
|
756 | + && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host) |
|
757 | + && $config->getSystemValue('installed', false) |
|
758 | + ) { |
|
759 | + // Allow access to CSS resources |
|
760 | + $isScssRequest = false; |
|
761 | + if (strpos($request->getPathInfo(), '/css/') === 0) { |
|
762 | + $isScssRequest = true; |
|
763 | + } |
|
764 | + |
|
765 | + if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
766 | + http_response_code(400); |
|
767 | + header('Content-Type: application/json'); |
|
768 | + echo '{"error": "Trusted domain error.", "code": 15}'; |
|
769 | + exit(); |
|
770 | + } |
|
771 | + |
|
772 | + if (!$isScssRequest) { |
|
773 | + http_response_code(400); |
|
774 | + |
|
775 | + \OC::$server->getLogger()->info( |
|
776 | + 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
777 | + [ |
|
778 | + 'app' => 'core', |
|
779 | + 'remoteAddress' => $request->getRemoteAddress(), |
|
780 | + 'host' => $host, |
|
781 | + ] |
|
782 | + ); |
|
783 | + |
|
784 | + $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); |
|
785 | + $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains')); |
|
786 | + $tmpl->printPage(); |
|
787 | + |
|
788 | + exit(); |
|
789 | + } |
|
790 | + } |
|
791 | + $eventLogger->end('boot'); |
|
792 | + } |
|
793 | + |
|
794 | + /** |
|
795 | + * register hooks for the cleanup of cache and bruteforce protection |
|
796 | + */ |
|
797 | + public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) { |
|
798 | + //don't try to do this before we are properly setup |
|
799 | + if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
800 | + |
|
801 | + // NOTE: This will be replaced to use OCP |
|
802 | + $userSession = self::$server->getUserSession(); |
|
803 | + $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
804 | + if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
805 | + // reset brute force delay for this IP address and username |
|
806 | + $uid = \OC::$server->getUserSession()->getUser()->getUID(); |
|
807 | + $request = \OC::$server->getRequest(); |
|
808 | + $throttler = \OC::$server->getBruteForceThrottler(); |
|
809 | + $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
810 | + } |
|
811 | + |
|
812 | + try { |
|
813 | + $cache = new \OC\Cache\File(); |
|
814 | + $cache->gc(); |
|
815 | + } catch (\OC\ServerNotAvailableException $e) { |
|
816 | + // not a GC exception, pass it on |
|
817 | + throw $e; |
|
818 | + } catch (\OC\ForbiddenException $e) { |
|
819 | + // filesystem blocked for this request, ignore |
|
820 | + } catch (\Exception $e) { |
|
821 | + // a GC exception should not prevent users from using OC, |
|
822 | + // so log the exception |
|
823 | + \OC::$server->getLogger()->logException($e, [ |
|
824 | + 'message' => 'Exception when running cache gc.', |
|
825 | + 'level' => ILogger::WARN, |
|
826 | + 'app' => 'core', |
|
827 | + ]); |
|
828 | + } |
|
829 | + }); |
|
830 | + } |
|
831 | + } |
|
832 | + |
|
833 | + private static function registerEncryptionWrapperAndHooks() { |
|
834 | + $manager = self::$server->getEncryptionManager(); |
|
835 | + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); |
|
836 | + |
|
837 | + $enabled = $manager->isEnabled(); |
|
838 | + if ($enabled) { |
|
839 | + \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared'); |
|
840 | + \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared'); |
|
841 | + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename'); |
|
842 | + \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore'); |
|
843 | + } |
|
844 | + } |
|
845 | + |
|
846 | + private static function registerAccountHooks() { |
|
847 | + /** @var IEventDispatcher $dispatcher */ |
|
848 | + $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
849 | + $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
850 | + } |
|
851 | + |
|
852 | + private static function registerAppRestrictionsHooks() { |
|
853 | + /** @var \OC\Group\Manager $groupManager */ |
|
854 | + $groupManager = self::$server->query(\OCP\IGroupManager::class); |
|
855 | + $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
856 | + $appManager = self::$server->getAppManager(); |
|
857 | + $apps = $appManager->getEnabledAppsForGroup($group); |
|
858 | + foreach ($apps as $appId) { |
|
859 | + $restrictions = $appManager->getAppRestriction($appId); |
|
860 | + if (empty($restrictions)) { |
|
861 | + continue; |
|
862 | + } |
|
863 | + $key = array_search($group->getGID(), $restrictions); |
|
864 | + unset($restrictions[$key]); |
|
865 | + $restrictions = array_values($restrictions); |
|
866 | + if (empty($restrictions)) { |
|
867 | + $appManager->disableApp($appId); |
|
868 | + } else { |
|
869 | + $appManager->enableAppForGroups($appId, $restrictions); |
|
870 | + } |
|
871 | + } |
|
872 | + }); |
|
873 | + } |
|
874 | + |
|
875 | + private static function registerResourceCollectionHooks() { |
|
876 | + \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher()); |
|
877 | + } |
|
878 | + |
|
879 | + /** |
|
880 | + * register hooks for the filesystem |
|
881 | + */ |
|
882 | + public static function registerFilesystemHooks() { |
|
883 | + // Check for blacklisted files |
|
884 | + OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted'); |
|
885 | + OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted'); |
|
886 | + } |
|
887 | + |
|
888 | + /** |
|
889 | + * register hooks for sharing |
|
890 | + */ |
|
891 | + public static function registerShareHooks(\OC\SystemConfig $systemConfig) { |
|
892 | + if ($systemConfig->getValue('installed')) { |
|
893 | + OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser'); |
|
894 | + OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup'); |
|
895 | + |
|
896 | + /** @var IEventDispatcher $dispatcher */ |
|
897 | + $dispatcher = \OC::$server->get(IEventDispatcher::class); |
|
898 | + $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class); |
|
899 | + } |
|
900 | + } |
|
901 | + |
|
902 | + protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) { |
|
903 | + // The class loader takes an optional low-latency cache, which MUST be |
|
904 | + // namespaced. The instanceid is used for namespacing, but might be |
|
905 | + // unavailable at this point. Furthermore, it might not be possible to |
|
906 | + // generate an instanceid via \OC_Util::getInstanceId() because the |
|
907 | + // config file may not be writable. As such, we only register a class |
|
908 | + // loader cache if instanceid is available without trying to create one. |
|
909 | + $instanceId = $systemConfig->getValue('instanceid', null); |
|
910 | + if ($instanceId) { |
|
911 | + try { |
|
912 | + $memcacheFactory = \OC::$server->getMemCacheFactory(); |
|
913 | + self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); |
|
914 | + } catch (\Exception $ex) { |
|
915 | + } |
|
916 | + } |
|
917 | + } |
|
918 | + |
|
919 | + /** |
|
920 | + * Handle the request |
|
921 | + */ |
|
922 | + public static function handleRequest() { |
|
923 | + \OC::$server->getEventLogger()->start('handle_request', 'Handle request'); |
|
924 | + $systemConfig = \OC::$server->getSystemConfig(); |
|
925 | + |
|
926 | + // Check if Nextcloud is installed or in maintenance (update) mode |
|
927 | + if (!$systemConfig->getValue('installed', false)) { |
|
928 | + \OC::$server->getSession()->clear(); |
|
929 | + $setupHelper = new OC\Setup( |
|
930 | + $systemConfig, |
|
931 | + \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class), |
|
932 | + \OC::$server->getL10N('lib'), |
|
933 | + \OC::$server->query(\OCP\Defaults::class), |
|
934 | + \OC::$server->get(\Psr\Log\LoggerInterface::class), |
|
935 | + \OC::$server->getSecureRandom(), |
|
936 | + \OC::$server->query(\OC\Installer::class) |
|
937 | + ); |
|
938 | + $controller = new OC\Core\Controller\SetupController($setupHelper); |
|
939 | + $controller->run($_POST); |
|
940 | + exit(); |
|
941 | + } |
|
942 | + |
|
943 | + $request = \OC::$server->getRequest(); |
|
944 | + $requestPath = $request->getRawPathInfo(); |
|
945 | + if ($requestPath === '/heartbeat') { |
|
946 | + return; |
|
947 | + } |
|
948 | + if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
949 | + self::checkMaintenanceMode($systemConfig); |
|
950 | + |
|
951 | + if (\OCP\Util::needUpgrade()) { |
|
952 | + if (function_exists('opcache_reset')) { |
|
953 | + opcache_reset(); |
|
954 | + } |
|
955 | + if (!((bool) $systemConfig->getValue('maintenance', false))) { |
|
956 | + self::printUpgradePage($systemConfig); |
|
957 | + exit(); |
|
958 | + } |
|
959 | + } |
|
960 | + } |
|
961 | + |
|
962 | + // emergency app disabling |
|
963 | + if ($requestPath === '/disableapp' |
|
964 | + && $request->getMethod() === 'POST' |
|
965 | + && ((array)$request->getParam('appid')) !== '' |
|
966 | + ) { |
|
967 | + \OC_JSON::callCheck(); |
|
968 | + \OC_JSON::checkAdminUser(); |
|
969 | + $appIds = (array)$request->getParam('appid'); |
|
970 | + foreach ($appIds as $appId) { |
|
971 | + $appId = \OC_App::cleanAppId($appId); |
|
972 | + \OC::$server->getAppManager()->disableApp($appId); |
|
973 | + } |
|
974 | + \OC_JSON::success(); |
|
975 | + exit(); |
|
976 | + } |
|
977 | + |
|
978 | + // Always load authentication apps |
|
979 | + OC_App::loadApps(['authentication']); |
|
980 | + |
|
981 | + // Load minimum set of apps |
|
982 | + if (!\OCP\Util::needUpgrade() |
|
983 | + && !((bool) $systemConfig->getValue('maintenance', false))) { |
|
984 | + // For logged-in users: Load everything |
|
985 | + if (\OC::$server->getUserSession()->isLoggedIn()) { |
|
986 | + OC_App::loadApps(); |
|
987 | + } else { |
|
988 | + // For guests: Load only filesystem and logging |
|
989 | + OC_App::loadApps(['filesystem', 'logging']); |
|
990 | + self::handleLogin($request); |
|
991 | + } |
|
992 | + } |
|
993 | + |
|
994 | + if (!self::$CLI) { |
|
995 | + try { |
|
996 | + if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) { |
|
997 | + OC_App::loadApps(['filesystem', 'logging']); |
|
998 | + OC_App::loadApps(); |
|
999 | + } |
|
1000 | + OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1001 | + return; |
|
1002 | + } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1003 | + //header('HTTP/1.0 404 Not Found'); |
|
1004 | + } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1005 | + http_response_code(405); |
|
1006 | + return; |
|
1007 | + } |
|
1008 | + } |
|
1009 | + |
|
1010 | + // Handle WebDAV |
|
1011 | + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1012 | + // not allowed any more to prevent people |
|
1013 | + // mounting this root directly. |
|
1014 | + // Users need to mount remote.php/webdav instead. |
|
1015 | + http_response_code(405); |
|
1016 | + return; |
|
1017 | + } |
|
1018 | + |
|
1019 | + // Someone is logged in |
|
1020 | + if (\OC::$server->getUserSession()->isLoggedIn()) { |
|
1021 | + OC_App::loadApps(); |
|
1022 | + OC_User::setupBackends(); |
|
1023 | + OC_Util::setupFS(); |
|
1024 | + // FIXME |
|
1025 | + // Redirect to default application |
|
1026 | + OC_Util::redirectToDefaultPage(); |
|
1027 | + } else { |
|
1028 | + // Not handled and not logged in |
|
1029 | + header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1030 | + } |
|
1031 | + } |
|
1032 | + |
|
1033 | + /** |
|
1034 | + * Check login: apache auth, auth token, basic auth |
|
1035 | + * |
|
1036 | + * @param OCP\IRequest $request |
|
1037 | + * @return boolean |
|
1038 | + */ |
|
1039 | + public static function handleLogin(OCP\IRequest $request) { |
|
1040 | + $userSession = self::$server->getUserSession(); |
|
1041 | + if (OC_User::handleApacheAuth()) { |
|
1042 | + return true; |
|
1043 | + } |
|
1044 | + if ($userSession->tryTokenLogin($request)) { |
|
1045 | + return true; |
|
1046 | + } |
|
1047 | + if (isset($_COOKIE['nc_username']) |
|
1048 | + && isset($_COOKIE['nc_token']) |
|
1049 | + && isset($_COOKIE['nc_session_id']) |
|
1050 | + && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1051 | + return true; |
|
1052 | + } |
|
1053 | + if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) { |
|
1054 | + return true; |
|
1055 | + } |
|
1056 | + return false; |
|
1057 | + } |
|
1058 | + |
|
1059 | + protected static function handleAuthHeaders() { |
|
1060 | + //copy http auth headers for apache+php-fcgid work around |
|
1061 | + if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1062 | + $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1063 | + } |
|
1064 | + |
|
1065 | + // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1066 | + $vars = [ |
|
1067 | + 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1068 | + 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1069 | + ]; |
|
1070 | + foreach ($vars as $var) { |
|
1071 | + if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1072 | + $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1073 | + if (count($credentials) === 2) { |
|
1074 | + $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1075 | + $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1076 | + break; |
|
1077 | + } |
|
1078 | + } |
|
1079 | + } |
|
1080 | + } |
|
1081 | 1081 | } |
1082 | 1082 | |
1083 | 1083 | OC::init(); |