You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.php 36KB

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