您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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