base.php 39 KB

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