base.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Adam Williamson <awilliam@redhat.com>
  7. * @author Andreas Fischer <bantu@owncloud.com>
  8. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  9. * @author Bart Visscher <bartv@thisnet.nl>
  10. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  11. * @author Bjoern Schiessle <bjoern@schiessle.org>
  12. * @author Björn Schießle <bjoern@schiessle.org>
  13. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  14. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  15. * @author Damjan Georgievski <gdamjan@gmail.com>
  16. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  17. * @author davidgumberg <davidnoizgumberg@gmail.com>
  18. * @author Eric Masseran <rico.masseran@gmail.com>
  19. * @author Florin Peter <github@florin-peter.de>
  20. * @author Greta Doci <gretadoci@gmail.com>
  21. * @author J0WI <J0WI@users.noreply.github.com>
  22. * @author Jakob Sack <mail@jakobsack.de>
  23. * @author jaltek <jaltek@mailbox.org>
  24. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  25. * @author Joachim Sokolowski <github@sokolowski.org>
  26. * @author Joas Schilling <coding@schilljs.com>
  27. * @author John Molakvoæ <skjnldsv@protonmail.com>
  28. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  29. * @author Jose Quinteiro <github@quinteiro.org>
  30. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  31. * @author Julius Härtl <jus@bitgrid.net>
  32. * @author Ko- <k.stoffelen@cs.ru.nl>
  33. * @author Lukas Reschke <lukas@statuscode.ch>
  34. * @author MartB <mart.b@outlook.de>
  35. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  36. * @author Morris Jobke <hey@morrisjobke.de>
  37. * @author Owen Winkler <a_github@midnightcircus.com>
  38. * @author Phil Davis <phil.davis@inf.org>
  39. * @author Ramiro Aparicio <rapariciog@gmail.com>
  40. * @author Robin Appelman <robin@icewind.nl>
  41. * @author Robin McCorkell <robin@mccorkell.me.uk>
  42. * @author Roeland Jago Douma <roeland@famdouma.nl>
  43. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  44. * @author Stefan Weil <sw@weilnetz.de>
  45. * @author Thomas Müller <thomas.mueller@tmit.eu>
  46. * @author Thomas Tanghus <thomas@tanghus.net>
  47. * @author Tobia De Koninck <tobia@ledfan.be>
  48. * @author Vincent Petry <vincent@nextcloud.com>
  49. * @author Volkan Gezer <volkangezer@gmail.com>
  50. *
  51. * @license AGPL-3.0
  52. *
  53. * This code is free software: you can redistribute it and/or modify
  54. * it under the terms of the GNU Affero General Public License, version 3,
  55. * as published by the Free Software Foundation.
  56. *
  57. * This program is distributed in the hope that it will be useful,
  58. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  59. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  60. * GNU Affero General Public License for more details.
  61. *
  62. * You should have received a copy of the GNU Affero General Public License, version 3,
  63. * along with this program. If not, see <http://www.gnu.org/licenses/>
  64. *
  65. */
  66. use OC\Encryption\HookManager;
  67. use OC\EventDispatcher\SymfonyAdapter;
  68. use OC\Files\Filesystem;
  69. use OC\Share20\Hooks;
  70. use OCP\EventDispatcher\IEventDispatcher;
  71. use OCP\Group\Events\UserRemovedEvent;
  72. use OCP\ILogger;
  73. use OCP\IRequest;
  74. use OCP\IURLGenerator;
  75. use OCP\IUserSession;
  76. use OCP\Server;
  77. use OCP\Share;
  78. use OCP\User\Events\UserChangedEvent;
  79. use Psr\Log\LoggerInterface;
  80. use function OCP\Log\logger;
  81. require_once 'public/Constants.php';
  82. /**
  83. * Class that is a namespace for all global OC variables
  84. * No, we can not put this class in its own file because it is used by
  85. * OC_autoload!
  86. */
  87. class OC {
  88. /**
  89. * Associative array for autoloading. classname => filename
  90. */
  91. public static array $CLASSPATH = [];
  92. /**
  93. * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
  94. */
  95. public static string $SERVERROOT = '';
  96. /**
  97. * the current request path relative to the Nextcloud root (e.g. files/index.php)
  98. */
  99. private static string $SUBURI = '';
  100. /**
  101. * the Nextcloud root path for http requests (e.g. nextcloud/)
  102. */
  103. public static string $WEBROOT = '';
  104. /**
  105. * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
  106. * web path in 'url'
  107. */
  108. public static array $APPSROOTS = [];
  109. public static string $configDir;
  110. /**
  111. * requested app
  112. */
  113. public static string $REQUESTEDAPP = '';
  114. /**
  115. * check if Nextcloud runs in cli mode
  116. */
  117. public static bool $CLI = false;
  118. public static \OC\Autoloader $loader;
  119. public static \Composer\Autoload\ClassLoader $composerAutoloader;
  120. public static \OC\Server $server;
  121. private static \OC\Config $config;
  122. /**
  123. * @throws \RuntimeException when the 3rdparty directory is missing or
  124. * the app path list is empty or contains an invalid path
  125. */
  126. public static function initPaths(): void {
  127. if (defined('PHPUNIT_CONFIG_DIR')) {
  128. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  129. } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  130. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  131. } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
  132. self::$configDir = rtrim($dir, '/') . '/';
  133. } else {
  134. self::$configDir = OC::$SERVERROOT . '/config/';
  135. }
  136. self::$config = new \OC\Config(self::$configDir);
  137. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"] ?? ''), strlen(OC::$SERVERROOT)));
  138. /**
  139. * FIXME: The following lines are required because we can't yet instantiate
  140. * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
  141. */
  142. $params = [
  143. 'server' => [
  144. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
  145. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
  146. ],
  147. ];
  148. $fakeRequest = new \OC\AppFramework\Http\Request(
  149. $params,
  150. new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
  151. new \OC\AllConfig(new \OC\SystemConfig(self::$config))
  152. );
  153. $scriptName = $fakeRequest->getScriptName();
  154. if (substr($scriptName, -1) == '/') {
  155. $scriptName .= 'index.php';
  156. //make sure suburi follows the same rules as scriptName
  157. if (substr(OC::$SUBURI, -9) != 'index.php') {
  158. if (substr(OC::$SUBURI, -1) != '/') {
  159. OC::$SUBURI = OC::$SUBURI . '/';
  160. }
  161. OC::$SUBURI = OC::$SUBURI . 'index.php';
  162. }
  163. }
  164. if (OC::$CLI) {
  165. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  166. } else {
  167. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  168. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  169. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  170. OC::$WEBROOT = '/' . OC::$WEBROOT;
  171. }
  172. } else {
  173. // The scriptName is not ending with OC::$SUBURI
  174. // This most likely means that we are calling from CLI.
  175. // However some cron jobs still need to generate
  176. // a web URL, so we use overwritewebroot as a fallback.
  177. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  178. }
  179. // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
  180. // slash which is required by URL generation.
  181. if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  182. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  183. header('Location: '.\OC::$WEBROOT.'/');
  184. exit();
  185. }
  186. }
  187. // search the apps folder
  188. $config_paths = self::$config->getValue('apps_paths', []);
  189. if (!empty($config_paths)) {
  190. foreach ($config_paths as $paths) {
  191. if (isset($paths['url']) && isset($paths['path'])) {
  192. $paths['url'] = rtrim($paths['url'], '/');
  193. $paths['path'] = rtrim($paths['path'], '/');
  194. OC::$APPSROOTS[] = $paths;
  195. }
  196. }
  197. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  198. OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
  199. }
  200. if (empty(OC::$APPSROOTS)) {
  201. throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
  202. . '. You can also configure the location in the config.php file.');
  203. }
  204. $paths = [];
  205. foreach (OC::$APPSROOTS as $path) {
  206. $paths[] = $path['path'];
  207. if (!is_dir($path['path'])) {
  208. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
  209. . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
  210. }
  211. }
  212. // set the right include path
  213. set_include_path(
  214. implode(PATH_SEPARATOR, $paths)
  215. );
  216. }
  217. public static function checkConfig(): void {
  218. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  219. // Create config if it does not already exist
  220. $configFilePath = self::$configDir .'/config.php';
  221. if (!file_exists($configFilePath)) {
  222. @touch($configFilePath);
  223. }
  224. // Check if config is writable
  225. $configFileWritable = is_writable($configFilePath);
  226. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  227. || !$configFileWritable && \OCP\Util::needUpgrade()) {
  228. $urlGenerator = Server::get(IURLGenerator::class);
  229. if (self::$CLI) {
  230. echo $l->t('Cannot write into "config" directory!')."\n";
  231. echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
  232. echo "\n";
  233. 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";
  234. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
  235. exit;
  236. } else {
  237. OC_Template::printErrorPage(
  238. $l->t('Cannot write into "config" directory!'),
  239. $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
  240. . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
  241. . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
  242. 503
  243. );
  244. }
  245. }
  246. }
  247. public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
  248. if (defined('OC_CONSOLE')) {
  249. return;
  250. }
  251. // Redirect to installer if not installed
  252. if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
  253. if (OC::$CLI) {
  254. throw new Exception('Not installed');
  255. } else {
  256. $url = OC::$WEBROOT . '/index.php';
  257. header('Location: ' . $url);
  258. }
  259. exit();
  260. }
  261. }
  262. public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
  263. // Allow ajax update script to execute without being stopped
  264. if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
  265. // send http status 503
  266. http_response_code(503);
  267. header('X-Nextcloud-Maintenance-Mode: 1');
  268. header('Retry-After: 120');
  269. // render error page
  270. $template = new OC_Template('', 'update.user', 'guest');
  271. \OCP\Util::addScript('core', 'maintenance');
  272. \OCP\Util::addStyle('core', 'guest');
  273. $template->printPage();
  274. die();
  275. }
  276. }
  277. /**
  278. * Prints the upgrade page
  279. */
  280. private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
  281. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  282. $tooBig = false;
  283. if (!$disableWebUpdater) {
  284. $apps = Server::get(\OCP\App\IAppManager::class);
  285. if ($apps->isInstalled('user_ldap')) {
  286. $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
  287. $result = $qb->select($qb->func()->count('*', 'user_count'))
  288. ->from('ldap_user_mapping')
  289. ->executeQuery();
  290. $row = $result->fetch();
  291. $result->closeCursor();
  292. $tooBig = ($row['user_count'] > 50);
  293. }
  294. if (!$tooBig && $apps->isInstalled('user_saml')) {
  295. $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
  296. $result = $qb->select($qb->func()->count('*', 'user_count'))
  297. ->from('user_saml_users')
  298. ->executeQuery();
  299. $row = $result->fetch();
  300. $result->closeCursor();
  301. $tooBig = ($row['user_count'] > 50);
  302. }
  303. if (!$tooBig) {
  304. // count users
  305. $stats = Server::get(\OCP\IUserManager::class)->countUsers();
  306. $totalUsers = array_sum($stats);
  307. $tooBig = ($totalUsers > 50);
  308. }
  309. }
  310. $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
  311. $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
  312. if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
  313. // send http status 503
  314. http_response_code(503);
  315. header('Retry-After: 120');
  316. // render error page
  317. $template = new OC_Template('', 'update.use-cli', 'guest');
  318. $template->assign('productName', 'nextcloud'); // for now
  319. $template->assign('version', OC_Util::getVersionString());
  320. $template->assign('tooBig', $tooBig);
  321. $template->printPage();
  322. die();
  323. }
  324. // check whether this is a core update or apps update
  325. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  326. $currentVersion = implode('.', \OCP\Util::getVersion());
  327. // if not a core upgrade, then it's apps upgrade
  328. $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
  329. $oldTheme = $systemConfig->getValue('theme');
  330. $systemConfig->setValue('theme', '');
  331. \OCP\Util::addScript('core', 'common');
  332. \OCP\Util::addScript('core', 'main');
  333. \OCP\Util::addTranslations('core');
  334. \OCP\Util::addScript('core', 'update');
  335. /** @var \OC\App\AppManager $appManager */
  336. $appManager = Server::get(\OCP\App\IAppManager::class);
  337. $tmpl = new OC_Template('', 'update.admin', 'guest');
  338. $tmpl->assign('version', OC_Util::getVersionString());
  339. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  340. // get third party apps
  341. $ocVersion = \OCP\Util::getVersion();
  342. $ocVersion = implode('.', $ocVersion);
  343. $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
  344. $incompatibleShippedApps = [];
  345. foreach ($incompatibleApps as $appInfo) {
  346. if ($appManager->isShipped($appInfo['id'])) {
  347. $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
  348. }
  349. }
  350. if (!empty($incompatibleShippedApps)) {
  351. $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
  352. $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)]);
  353. 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);
  354. }
  355. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  356. $tmpl->assign('incompatibleAppsList', $incompatibleApps);
  357. try {
  358. $defaults = new \OC_Defaults();
  359. $tmpl->assign('productName', $defaults->getName());
  360. } catch (Throwable $error) {
  361. $tmpl->assign('productName', 'Nextcloud');
  362. }
  363. $tmpl->assign('oldTheme', $oldTheme);
  364. $tmpl->printPage();
  365. }
  366. public static function initSession(): void {
  367. $request = Server::get(IRequest::class);
  368. $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
  369. if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest) {
  370. setcookie('cookie_test', 'test', time() + 3600);
  371. // Do not initialize the session if a request is authenticated directly
  372. // unless there is a session cookie already sent along
  373. return;
  374. }
  375. if ($request->getServerProtocol() === 'https') {
  376. ini_set('session.cookie_secure', 'true');
  377. }
  378. // prevents javascript from accessing php session cookies
  379. ini_set('session.cookie_httponly', 'true');
  380. // set the cookie path to the Nextcloud directory
  381. $cookie_path = OC::$WEBROOT ? : '/';
  382. ini_set('session.cookie_path', $cookie_path);
  383. // Let the session name be changed in the initSession Hook
  384. $sessionName = OC_Util::getInstanceId();
  385. try {
  386. // set the session name to the instance id - which is unique
  387. $session = new \OC\Session\Internal($sessionName);
  388. $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
  389. $session = $cryptoWrapper->wrapSession($session);
  390. self::$server->setSession($session);
  391. // if session can't be started break with http 500 error
  392. } catch (Exception $e) {
  393. Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
  394. //show the user a detailed error page
  395. OC_Template::printExceptionErrorPage($e, 500);
  396. die();
  397. }
  398. //try to set the session lifetime
  399. $sessionLifeTime = self::getSessionLifeTime();
  400. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  401. // session timeout
  402. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  403. if (isset($_COOKIE[session_name()])) {
  404. setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
  405. }
  406. Server::get(IUserSession::class)->logout();
  407. }
  408. if (!self::hasSessionRelaxedExpiry()) {
  409. $session->set('LAST_ACTIVITY', time());
  410. }
  411. $session->close();
  412. }
  413. private static function getSessionLifeTime(): int {
  414. return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
  415. }
  416. /**
  417. * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
  418. */
  419. public static function hasSessionRelaxedExpiry(): bool {
  420. return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
  421. }
  422. /**
  423. * Try to set some values to the required Nextcloud default
  424. */
  425. public static function setRequiredIniValues(): void {
  426. @ini_set('default_charset', 'UTF-8');
  427. @ini_set('gd.jpeg_ignore_warning', '1');
  428. }
  429. /**
  430. * Send the same site cookies
  431. */
  432. private static function sendSameSiteCookies(): void {
  433. $cookieParams = session_get_cookie_params();
  434. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  435. $policies = [
  436. 'lax',
  437. 'strict',
  438. ];
  439. // Append __Host to the cookie if it meets the requirements
  440. $cookiePrefix = '';
  441. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  442. $cookiePrefix = '__Host-';
  443. }
  444. foreach ($policies as $policy) {
  445. header(
  446. sprintf(
  447. 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  448. $cookiePrefix,
  449. $policy,
  450. $cookieParams['path'],
  451. $policy
  452. ),
  453. false
  454. );
  455. }
  456. }
  457. /**
  458. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  459. * be set in every request if cookies are sent to add a second level of
  460. * defense against CSRF.
  461. *
  462. * If the cookie is not sent this will set the cookie and reload the page.
  463. * We use an additional cookie since we want to protect logout CSRF and
  464. * also we can't directly interfere with PHP's session mechanism.
  465. */
  466. private static function performSameSiteCookieProtection(\OCP\IConfig $config): void {
  467. $request = Server::get(IRequest::class);
  468. // Some user agents are notorious and don't really properly follow HTTP
  469. // specifications. For those, have an automated opt-out. Since the protection
  470. // for remote.php is applied in base.php as starting point we need to opt out
  471. // here.
  472. $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
  473. // Fallback, if csrf.optout is unset
  474. if (!is_array($incompatibleUserAgents)) {
  475. $incompatibleUserAgents = [
  476. // OS X Finder
  477. '/^WebDAVFS/',
  478. // Windows webdav drive
  479. '/^Microsoft-WebDAV-MiniRedir/',
  480. ];
  481. }
  482. if ($request->isUserAgent($incompatibleUserAgents)) {
  483. return;
  484. }
  485. if (count($_COOKIE) > 0) {
  486. $requestUri = $request->getScriptName();
  487. $processingScript = explode('/', $requestUri);
  488. $processingScript = $processingScript[count($processingScript) - 1];
  489. // index.php routes are handled in the middleware
  490. if ($processingScript === 'index.php') {
  491. return;
  492. }
  493. // All other endpoints require the lax and the strict cookie
  494. if (!$request->passesStrictCookieCheck()) {
  495. self::sendSameSiteCookies();
  496. // Debug mode gets access to the resources without strict cookie
  497. // due to the fact that the SabreDAV browser also lives there.
  498. if (!$config->getSystemValue('debug', false)) {
  499. http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
  500. exit();
  501. }
  502. }
  503. } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  504. self::sendSameSiteCookies();
  505. }
  506. }
  507. public static function init(): void {
  508. // calculate the root directories
  509. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  510. // register autoloader
  511. $loaderStart = microtime(true);
  512. require_once __DIR__ . '/autoloader.php';
  513. self::$loader = new \OC\Autoloader([
  514. OC::$SERVERROOT . '/lib/private/legacy',
  515. ]);
  516. if (defined('PHPUNIT_RUN')) {
  517. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  518. }
  519. spl_autoload_register([self::$loader, 'load']);
  520. $loaderEnd = microtime(true);
  521. self::$CLI = (php_sapi_name() == 'cli');
  522. // Add default composer PSR-4 autoloader
  523. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  524. self::$composerAutoloader->setApcuPrefix('composer_autoload');
  525. try {
  526. self::initPaths();
  527. // setup 3rdparty autoloader
  528. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  529. if (!file_exists($vendorAutoLoad)) {
  530. 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".');
  531. }
  532. require_once $vendorAutoLoad;
  533. } catch (\RuntimeException $e) {
  534. if (!self::$CLI) {
  535. http_response_code(503);
  536. }
  537. // we can't use the template error page here, because this needs the
  538. // DI container which isn't available yet
  539. print($e->getMessage());
  540. exit();
  541. }
  542. // setup the basic server
  543. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  544. self::$server->boot();
  545. $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
  546. $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  547. $eventLogger->start('boot', 'Initialize');
  548. // Override php.ini and log everything if we're troubleshooting
  549. if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
  550. error_reporting(E_ALL);
  551. }
  552. // Don't display errors and log them
  553. @ini_set('display_errors', '0');
  554. @ini_set('log_errors', '1');
  555. if (!date_default_timezone_set('UTC')) {
  556. throw new \RuntimeException('Could not set timezone to UTC');
  557. }
  558. //try to configure php to enable big file uploads.
  559. //this doesn´t work always depending on the webserver and php configuration.
  560. //Let´s try to overwrite some defaults if they are smaller than 1 hour
  561. if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
  562. @ini_set('max_execution_time', strval(3600));
  563. }
  564. if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
  565. @ini_set('max_input_time', strval(3600));
  566. }
  567. //try to set the maximum execution time to the largest time limit we have
  568. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  569. @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
  570. }
  571. self::setRequiredIniValues();
  572. self::handleAuthHeaders();
  573. $systemConfig = Server::get(\OC\SystemConfig::class);
  574. self::registerAutoloaderCache($systemConfig);
  575. // initialize intl fallback if necessary
  576. OC_Util::isSetLocaleWorking();
  577. $config = Server::get(\OCP\IConfig::class);
  578. if (!defined('PHPUNIT_RUN')) {
  579. $errorHandler = new OC\Log\ErrorHandler(
  580. \OCP\Server::get(\Psr\Log\LoggerInterface::class),
  581. );
  582. $exceptionHandler = [$errorHandler, 'onException'];
  583. if ($config->getSystemValue('debug', false)) {
  584. set_error_handler([$errorHandler, 'onAll'], E_ALL);
  585. if (\OC::$CLI) {
  586. $exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
  587. }
  588. } else {
  589. set_error_handler([$errorHandler, 'onError']);
  590. }
  591. register_shutdown_function([$errorHandler, 'onShutdown']);
  592. set_exception_handler($exceptionHandler);
  593. }
  594. /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
  595. $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
  596. $bootstrapCoordinator->runInitialRegistration();
  597. $eventLogger->start('init_session', 'Initialize session');
  598. OC_App::loadApps(['session']);
  599. if (!self::$CLI) {
  600. self::initSession();
  601. }
  602. $eventLogger->end('init_session');
  603. self::checkConfig();
  604. self::checkInstalled($systemConfig);
  605. OC_Response::addSecurityHeaders();
  606. self::performSameSiteCookieProtection($config);
  607. if (!defined('OC_CONSOLE')) {
  608. $errors = OC_Util::checkServer($systemConfig);
  609. if (count($errors) > 0) {
  610. if (!self::$CLI) {
  611. http_response_code(503);
  612. OC_Util::addStyle('guest');
  613. try {
  614. OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
  615. exit;
  616. } catch (\Exception $e) {
  617. // In case any error happens when showing the error page, we simply fall back to posting the text.
  618. // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
  619. }
  620. }
  621. // Convert l10n string into regular string for usage in database
  622. $staticErrors = [];
  623. foreach ($errors as $error) {
  624. echo $error['error'] . "\n";
  625. echo $error['hint'] . "\n\n";
  626. $staticErrors[] = [
  627. 'error' => (string)$error['error'],
  628. 'hint' => (string)$error['hint'],
  629. ];
  630. }
  631. try {
  632. $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  633. } catch (\Exception $e) {
  634. echo('Writing to database failed');
  635. }
  636. exit(1);
  637. } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
  638. $config->deleteAppValue('core', 'cronErrors');
  639. }
  640. }
  641. // User and Groups
  642. if (!$systemConfig->getValue("installed", false)) {
  643. self::$server->getSession()->set('user_id', '');
  644. }
  645. OC_User::useBackend(new \OC\User\Database());
  646. Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
  647. // Subscribe to the hook
  648. \OCP\Util::connectHook(
  649. '\OCA\Files_Sharing\API\Server2Server',
  650. 'preLoginNameUsedAsUserName',
  651. '\OC\User\Database',
  652. 'preLoginNameUsedAsUserName'
  653. );
  654. //setup extra user backends
  655. if (!\OCP\Util::needUpgrade()) {
  656. OC_User::setupBackends();
  657. } else {
  658. // Run upgrades in incognito mode
  659. OC_User::setIncognitoMode(true);
  660. }
  661. self::registerCleanupHooks($systemConfig);
  662. self::registerShareHooks($systemConfig);
  663. self::registerEncryptionWrapperAndHooks();
  664. self::registerAccountHooks();
  665. self::registerResourceCollectionHooks();
  666. self::registerFileReferenceEventListener();
  667. self::registerAppRestrictionsHooks();
  668. // Make sure that the application class is not loaded before the database is setup
  669. if ($systemConfig->getValue("installed", false)) {
  670. OC_App::loadApp('settings');
  671. /* Build core application to make sure that listeners are registered */
  672. Server::get(\OC\Core\Application::class);
  673. }
  674. //make sure temporary files are cleaned up
  675. $tmpManager = Server::get(\OCP\ITempManager::class);
  676. register_shutdown_function([$tmpManager, 'clean']);
  677. $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
  678. register_shutdown_function([$lockProvider, 'releaseAll']);
  679. // Check whether the sample configuration has been copied
  680. if ($systemConfig->getValue('copied_sample_config', false)) {
  681. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  682. OC_Template::printErrorPage(
  683. $l->t('Sample configuration detected'),
  684. $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'),
  685. 503
  686. );
  687. return;
  688. }
  689. $request = Server::get(IRequest::class);
  690. $host = $request->getInsecureServerHost();
  691. /**
  692. * if the host passed in headers isn't trusted
  693. * FIXME: Should not be in here at all :see_no_evil:
  694. */
  695. if (!OC::$CLI
  696. && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
  697. && $config->getSystemValue('installed', false)
  698. ) {
  699. // Allow access to CSS resources
  700. $isScssRequest = false;
  701. if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
  702. $isScssRequest = true;
  703. }
  704. if (substr($request->getRequestUri(), -11) === '/status.php') {
  705. http_response_code(400);
  706. header('Content-Type: application/json');
  707. echo '{"error": "Trusted domain error.", "code": 15}';
  708. exit();
  709. }
  710. if (!$isScssRequest) {
  711. http_response_code(400);
  712. Server::get(LoggerInterface::class)->info(
  713. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  714. [
  715. 'app' => 'core',
  716. 'remoteAddress' => $request->getRemoteAddress(),
  717. 'host' => $host,
  718. ]
  719. );
  720. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  721. $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
  722. $tmpl->printPage();
  723. exit();
  724. }
  725. }
  726. $eventLogger->end('boot');
  727. $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
  728. $eventLogger->start('runtime', 'Runtime');
  729. $eventLogger->start('request', 'Full request after boot');
  730. register_shutdown_function(function () use ($eventLogger) {
  731. $eventLogger->end('request');
  732. });
  733. }
  734. /**
  735. * register hooks for the cleanup of cache and bruteforce protection
  736. */
  737. public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
  738. //don't try to do this before we are properly setup
  739. if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
  740. // NOTE: This will be replaced to use OCP
  741. $userSession = Server::get(\OC\User\Session::class);
  742. $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
  743. if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
  744. // reset brute force delay for this IP address and username
  745. $uid = $userSession->getUser()->getUID();
  746. $request = Server::get(IRequest::class);
  747. $throttler = Server::get(\OC\Security\Bruteforce\Throttler::class);
  748. $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
  749. }
  750. try {
  751. $cache = new \OC\Cache\File();
  752. $cache->gc();
  753. } catch (\OC\ServerNotAvailableException $e) {
  754. // not a GC exception, pass it on
  755. throw $e;
  756. } catch (\OC\ForbiddenException $e) {
  757. // filesystem blocked for this request, ignore
  758. } catch (\Exception $e) {
  759. // a GC exception should not prevent users from using OC,
  760. // so log the exception
  761. Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
  762. 'app' => 'core',
  763. 'exception' => $e,
  764. ]);
  765. }
  766. });
  767. }
  768. }
  769. private static function registerEncryptionWrapperAndHooks(): void {
  770. $manager = Server::get(\OCP\Encryption\IManager::class);
  771. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  772. $enabled = $manager->isEnabled();
  773. if ($enabled) {
  774. \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
  775. \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
  776. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
  777. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
  778. }
  779. }
  780. private static function registerAccountHooks(): void {
  781. /** @var IEventDispatcher $dispatcher */
  782. $dispatcher = Server::get(IEventDispatcher::class);
  783. $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
  784. }
  785. private static function registerAppRestrictionsHooks(): void {
  786. /** @var \OC\Group\Manager $groupManager */
  787. $groupManager = Server::get(\OCP\IGroupManager::class);
  788. $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
  789. $appManager = Server::get(\OCP\App\IAppManager::class);
  790. $apps = $appManager->getEnabledAppsForGroup($group);
  791. foreach ($apps as $appId) {
  792. $restrictions = $appManager->getAppRestriction($appId);
  793. if (empty($restrictions)) {
  794. continue;
  795. }
  796. $key = array_search($group->getGID(), $restrictions);
  797. unset($restrictions[$key]);
  798. $restrictions = array_values($restrictions);
  799. if (empty($restrictions)) {
  800. $appManager->disableApp($appId);
  801. } else {
  802. $appManager->enableAppForGroups($appId, $restrictions);
  803. }
  804. }
  805. });
  806. }
  807. private static function registerResourceCollectionHooks(): void {
  808. \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
  809. }
  810. private static function registerFileReferenceEventListener(): void {
  811. \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
  812. }
  813. /**
  814. * register hooks for sharing
  815. */
  816. public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
  817. if ($systemConfig->getValue('installed')) {
  818. OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
  819. OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
  820. /** @var IEventDispatcher $dispatcher */
  821. $dispatcher = Server::get(IEventDispatcher::class);
  822. $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
  823. }
  824. }
  825. protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
  826. // The class loader takes an optional low-latency cache, which MUST be
  827. // namespaced. The instanceid is used for namespacing, but might be
  828. // unavailable at this point. Furthermore, it might not be possible to
  829. // generate an instanceid via \OC_Util::getInstanceId() because the
  830. // config file may not be writable. As such, we only register a class
  831. // loader cache if instanceid is available without trying to create one.
  832. $instanceId = $systemConfig->getValue('instanceid', null);
  833. if ($instanceId) {
  834. try {
  835. $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
  836. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  837. } catch (\Exception $ex) {
  838. }
  839. }
  840. }
  841. /**
  842. * Handle the request
  843. */
  844. public static function handleRequest(): void {
  845. Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
  846. $systemConfig = Server::get(\OC\SystemConfig::class);
  847. // Check if Nextcloud is installed or in maintenance (update) mode
  848. if (!$systemConfig->getValue('installed', false)) {
  849. \OC::$server->getSession()->clear();
  850. $setupHelper = new OC\Setup(
  851. $systemConfig,
  852. Server::get(\bantu\IniGetWrapper\IniGetWrapper::class),
  853. Server::get(\OCP\L10N\IFactory::class)->get('lib'),
  854. Server::get(\OCP\Defaults::class),
  855. Server::get(\Psr\Log\LoggerInterface::class),
  856. Server::get(\OCP\Security\ISecureRandom::class),
  857. Server::get(\OC\Installer::class)
  858. );
  859. $controller = new OC\Core\Controller\SetupController($setupHelper);
  860. $controller->run($_POST);
  861. exit();
  862. }
  863. $request = Server::get(IRequest::class);
  864. $requestPath = $request->getRawPathInfo();
  865. if ($requestPath === '/heartbeat') {
  866. return;
  867. }
  868. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  869. self::checkMaintenanceMode($systemConfig);
  870. if (\OCP\Util::needUpgrade()) {
  871. if (function_exists('opcache_reset')) {
  872. opcache_reset();
  873. }
  874. if (!((bool) $systemConfig->getValue('maintenance', false))) {
  875. self::printUpgradePage($systemConfig);
  876. exit();
  877. }
  878. }
  879. }
  880. // emergency app disabling
  881. if ($requestPath === '/disableapp'
  882. && $request->getMethod() === 'POST'
  883. ) {
  884. \OC_JSON::callCheck();
  885. \OC_JSON::checkAdminUser();
  886. $appIds = (array)$request->getParam('appid');
  887. foreach ($appIds as $appId) {
  888. $appId = \OC_App::cleanAppId($appId);
  889. Server::get(\OCP\App\IAppManager::class)->disableApp($appId);
  890. }
  891. \OC_JSON::success();
  892. exit();
  893. }
  894. // Always load authentication apps
  895. OC_App::loadApps(['authentication']);
  896. // Load minimum set of apps
  897. if (!\OCP\Util::needUpgrade()
  898. && !((bool) $systemConfig->getValue('maintenance', false))) {
  899. // For logged-in users: Load everything
  900. if (Server::get(IUserSession::class)->isLoggedIn()) {
  901. OC_App::loadApps();
  902. } else {
  903. // For guests: Load only filesystem and logging
  904. OC_App::loadApps(['filesystem', 'logging']);
  905. // Don't try to login when a client is trying to get a OAuth token.
  906. // OAuth needs to support basic auth too, so the login is not valid
  907. // inside Nextcloud and the Login exception would ruin it.
  908. if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
  909. self::handleLogin($request);
  910. }
  911. }
  912. }
  913. if (!self::$CLI) {
  914. try {
  915. if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
  916. OC_App::loadApps(['filesystem', 'logging']);
  917. OC_App::loadApps();
  918. }
  919. Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
  920. return;
  921. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  922. //header('HTTP/1.0 404 Not Found');
  923. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  924. http_response_code(405);
  925. return;
  926. }
  927. }
  928. // Handle WebDAV
  929. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  930. // not allowed any more to prevent people
  931. // mounting this root directly.
  932. // Users need to mount remote.php/webdav instead.
  933. http_response_code(405);
  934. return;
  935. }
  936. // Handle requests for JSON or XML
  937. $acceptHeader = $request->getHeader('Accept');
  938. if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
  939. http_response_code(404);
  940. return;
  941. }
  942. // Handle resources that can't be found
  943. // This prevents browsers from redirecting to the default page and then
  944. // attempting to parse HTML as CSS and similar.
  945. $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
  946. if (in_array($destinationHeader, ['font', 'script', 'style'])) {
  947. http_response_code(404);
  948. return;
  949. }
  950. // Redirect to the default app or login only as an entry point
  951. if ($requestPath === '') {
  952. // Someone is logged in
  953. if (Server::get(IUserSession::class)->isLoggedIn()) {
  954. header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
  955. } else {
  956. // Not handled and not logged in
  957. header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
  958. }
  959. return;
  960. }
  961. try {
  962. Server::get(\OC\Route\Router::class)->match('/error/404');
  963. } catch (\Exception $e) {
  964. logger('core')->emergency($e->getMessage(), ['exception' => $e]);
  965. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  966. OC_Template::printErrorPage(
  967. $l->t('404'),
  968. $l->t('The page could not be found on the server.'),
  969. 404
  970. );
  971. }
  972. }
  973. /**
  974. * Check login: apache auth, auth token, basic auth
  975. */
  976. public static function handleLogin(OCP\IRequest $request): bool {
  977. $userSession = Server::get(\OC\User\Session::class);
  978. if (OC_User::handleApacheAuth()) {
  979. return true;
  980. }
  981. if ($userSession->tryTokenLogin($request)) {
  982. return true;
  983. }
  984. if (isset($_COOKIE['nc_username'])
  985. && isset($_COOKIE['nc_token'])
  986. && isset($_COOKIE['nc_session_id'])
  987. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  988. return true;
  989. }
  990. if ($userSession->tryBasicAuthLogin($request, Server::get(\OC\Security\Bruteforce\Throttler::class))) {
  991. return true;
  992. }
  993. return false;
  994. }
  995. protected static function handleAuthHeaders(): void {
  996. //copy http auth headers for apache+php-fcgid work around
  997. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  998. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  999. }
  1000. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  1001. $vars = [
  1002. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  1003. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  1004. ];
  1005. foreach ($vars as $var) {
  1006. if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  1007. $credentials = explode(':', base64_decode($matches[1]), 2);
  1008. if (count($credentials) === 2) {
  1009. $_SERVER['PHP_AUTH_USER'] = $credentials[0];
  1010. $_SERVER['PHP_AUTH_PW'] = $credentials[1];
  1011. break;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. OC::init();