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

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