base.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. <?php
  2. /**
  3. * @author Adam Williamson <awilliam@redhat.com>
  4. * @author Andreas Fischer <bantu@owncloud.com>
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Christoph Wurst <christoph@owncloud.com>
  10. * @author davidgumberg <davidnoizgumberg@gmail.com>
  11. * @author Florin Peter <github@florin-peter.de>
  12. * @author Georg Ehrke <georg@owncloud.com>
  13. * @author Hugo Gonzalez Labrador <hglavra@gmail.com>
  14. * @author Individual IT Services <info@individual-it.net>
  15. * @author Jakob Sack <mail@jakobsack.de>
  16. * @author Joachim Bauch <bauch@struktur.de>
  17. * @author Joas Schilling <nickvergessen@owncloud.com>
  18. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  19. * @author Lukas Reschke <lukas@statuscode.ch>
  20. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  21. * @author Morris Jobke <hey@morrisjobke.de>
  22. * @author Owen Winkler <a_github@midnightcircus.com>
  23. * @author Phil Davis <phil.davis@inf.org>
  24. * @author Ramiro Aparicio <rapariciog@gmail.com>
  25. * @author Robin Appelman <icewind@owncloud.com>
  26. * @author Robin McCorkell <robin@mccorkell.me.uk>
  27. * @author Roeland Jago Douma <rullzer@owncloud.com>
  28. * @author scolebrook <scolebrook@mac.com>
  29. * @author Stefan Weil <sw@weilnetz.de>
  30. * @author Thomas Müller <thomas.mueller@tmit.eu>
  31. * @author Thomas Tanghus <thomas@tanghus.net>
  32. * @author Vincent Petry <pvince81@owncloud.com>
  33. * @author Volkan Gezer <volkangezer@gmail.com>
  34. *
  35. * @copyright Copyright (c) 2016, ownCloud, Inc.
  36. * @license AGPL-3.0
  37. *
  38. * This code is free software: you can redistribute it and/or modify
  39. * it under the terms of the GNU Affero General Public License, version 3,
  40. * as published by the Free Software Foundation.
  41. *
  42. * This program is distributed in the hope that it will be useful,
  43. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  44. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  45. * GNU Affero General Public License for more details.
  46. *
  47. * You should have received a copy of the GNU Affero General Public License, version 3,
  48. * along with this program. If not, see <http://www.gnu.org/licenses/>
  49. *
  50. */
  51. use OCP\IRequest;
  52. require_once 'public/Constants.php';
  53. /**
  54. * Class that is a namespace for all global OC variables
  55. * No, we can not put this class in its own file because it is used by
  56. * OC_autoload!
  57. */
  58. class OC {
  59. /**
  60. * Associative array for autoloading. classname => filename
  61. */
  62. public static $CLASSPATH = array();
  63. /**
  64. * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
  65. */
  66. public static $SERVERROOT = '';
  67. /**
  68. * the current request path relative to the Nextcloud root (e.g. files/index.php)
  69. */
  70. private static $SUBURI = '';
  71. /**
  72. * the Nextcloud root path for http requests (e.g. nextcloud/)
  73. */
  74. public static $WEBROOT = '';
  75. /**
  76. * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
  77. * web path in 'url'
  78. */
  79. public static $APPSROOTS = array();
  80. /**
  81. * @var string
  82. */
  83. public static $configDir;
  84. /**
  85. * requested app
  86. */
  87. public static $REQUESTEDAPP = '';
  88. /**
  89. * check if Nextcloud runs in cli mode
  90. */
  91. public static $CLI = false;
  92. /**
  93. * @var \OC\Autoloader $loader
  94. */
  95. public static $loader = null;
  96. /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
  97. public static $composerAutoloader = null;
  98. /**
  99. * @var \OC\Server
  100. */
  101. public static $server = null;
  102. /**
  103. * @var \OC\Config
  104. */
  105. private static $config = null;
  106. /**
  107. * @throws \RuntimeException when the 3rdparty directory is missing or
  108. * the app path list is empty or contains an invalid path
  109. */
  110. public static function initPaths() {
  111. if(defined('PHPUNIT_CONFIG_DIR')) {
  112. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  113. } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  114. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  115. } else {
  116. self::$configDir = OC::$SERVERROOT . '/config/';
  117. }
  118. self::$config = new \OC\Config(self::$configDir);
  119. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  120. /**
  121. * FIXME: The following lines are required because we can't yet instantiiate
  122. * \OC::$server->getRequest() since \OC::$server does not yet exist.
  123. */
  124. $params = [
  125. 'server' => [
  126. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
  127. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
  128. ],
  129. ];
  130. $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
  131. $scriptName = $fakeRequest->getScriptName();
  132. if (substr($scriptName, -1) == '/') {
  133. $scriptName .= 'index.php';
  134. //make sure suburi follows the same rules as scriptName
  135. if (substr(OC::$SUBURI, -9) != 'index.php') {
  136. if (substr(OC::$SUBURI, -1) != '/') {
  137. OC::$SUBURI = OC::$SUBURI . '/';
  138. }
  139. OC::$SUBURI = OC::$SUBURI . 'index.php';
  140. }
  141. }
  142. if (OC::$CLI) {
  143. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  144. } else {
  145. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  146. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  147. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  148. OC::$WEBROOT = '/' . OC::$WEBROOT;
  149. }
  150. } else {
  151. // The scriptName is not ending with OC::$SUBURI
  152. // This most likely means that we are calling from CLI.
  153. // However some cron jobs still need to generate
  154. // a web URL, so we use overwritewebroot as a fallback.
  155. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  156. }
  157. // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
  158. // slash which is required by URL generation.
  159. if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  160. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  161. header('Location: '.\OC::$WEBROOT.'/');
  162. exit();
  163. }
  164. }
  165. // search the apps folder
  166. $config_paths = self::$config->getValue('apps_paths', array());
  167. if (!empty($config_paths)) {
  168. foreach ($config_paths as $paths) {
  169. if (isset($paths['url']) && isset($paths['path'])) {
  170. $paths['url'] = rtrim($paths['url'], '/');
  171. $paths['path'] = rtrim($paths['path'], '/');
  172. OC::$APPSROOTS[] = $paths;
  173. }
  174. }
  175. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  176. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  177. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  178. OC::$APPSROOTS[] = array(
  179. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  180. 'url' => '/apps',
  181. 'writable' => true
  182. );
  183. }
  184. if (empty(OC::$APPSROOTS)) {
  185. throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
  186. . ' or the folder above. You can also configure the location in the config.php file.');
  187. }
  188. $paths = array();
  189. foreach (OC::$APPSROOTS as $path) {
  190. $paths[] = $path['path'];
  191. if (!is_dir($path['path'])) {
  192. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
  193. . ' Nextcloud folder or the folder above. You can also configure the location in the'
  194. . ' config.php file.', $path['path']));
  195. }
  196. }
  197. // set the right include path
  198. set_include_path(
  199. OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
  200. OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
  201. OC::$SERVERROOT . '/3rdparty' . PATH_SEPARATOR .
  202. implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
  203. get_include_path() . PATH_SEPARATOR .
  204. OC::$SERVERROOT
  205. );
  206. }
  207. public static function checkConfig() {
  208. $l = \OC::$server->getL10N('lib');
  209. // Create config if it does not already exist
  210. $configFilePath = self::$configDir .'/config.php';
  211. if(!file_exists($configFilePath)) {
  212. @touch($configFilePath);
  213. }
  214. // Check if config is writable
  215. $configFileWritable = is_writable($configFilePath);
  216. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  217. || !$configFileWritable && self::checkUpgrade(false)) {
  218. $urlGenerator = \OC::$server->getURLGenerator();
  219. if (self::$CLI) {
  220. echo $l->t('Cannot write into "config" directory!')."\n";
  221. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  222. echo "\n";
  223. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
  224. exit;
  225. } else {
  226. OC_Template::printErrorPage(
  227. $l->t('Cannot write into "config" directory!'),
  228. $l->t('This can usually be fixed by '
  229. . '%sgiving the webserver write access to the config directory%s.',
  230. array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
  231. );
  232. }
  233. }
  234. }
  235. public static function checkInstalled() {
  236. if (defined('OC_CONSOLE')) {
  237. return;
  238. }
  239. // Redirect to installer if not installed
  240. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
  241. if (OC::$CLI) {
  242. throw new Exception('Not installed');
  243. } else {
  244. $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
  245. header('Location: ' . $url);
  246. }
  247. exit();
  248. }
  249. }
  250. /**
  251. * Limit maintenance mode access
  252. * @param IRequest $request
  253. */
  254. public static function checkMaintenanceMode(IRequest $request) {
  255. // Check if requested URL matches 'index.php/occ'
  256. $isOccControllerRequested = preg_match('|/index\.php$|', $request->getScriptName()) === 1
  257. && strpos($request->getPathInfo(), '/occ/') === 0;
  258. // Allow ajax update script to execute without being stopped
  259. if (
  260. \OC::$server->getSystemConfig()->getValue('maintenance', false)
  261. && OC::$SUBURI != '/core/ajax/update.php'
  262. && !$isOccControllerRequested
  263. ) {
  264. // send http status 503
  265. header('HTTP/1.1 503 Service Temporarily Unavailable');
  266. header('Status: 503 Service Temporarily Unavailable');
  267. header('Retry-After: 120');
  268. // render error page
  269. $template = new OC_Template('', 'update.user', 'guest');
  270. OC_Util::addScript('maintenance-check');
  271. $template->printPage();
  272. die();
  273. }
  274. }
  275. public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
  276. if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
  277. return;
  278. }
  279. $user = OC_User::getUserSession()->getUser();
  280. if ($user) {
  281. $group = \OC::$server->getGroupManager()->get('admin');
  282. if ($group->inGroup($user)) {
  283. return;
  284. }
  285. } else {
  286. if(!$lockIfNoUserLoggedIn) {
  287. return;
  288. }
  289. }
  290. // send http status 503
  291. header('HTTP/1.1 503 Service Temporarily Unavailable');
  292. header('Status: 503 Service Temporarily Unavailable');
  293. header('Retry-After: 120');
  294. // render error page
  295. $template = new OC_Template('', 'singleuser.user', 'guest');
  296. $template->printPage();
  297. die();
  298. }
  299. /**
  300. * Checks if the version requires an update and shows
  301. * @param bool $showTemplate Whether an update screen should get shown
  302. * @return bool|void
  303. */
  304. public static function checkUpgrade($showTemplate = true) {
  305. if (\OCP\Util::needUpgrade()) {
  306. $systemConfig = \OC::$server->getSystemConfig();
  307. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  308. self::printUpgradePage();
  309. exit();
  310. } else {
  311. return true;
  312. }
  313. }
  314. return false;
  315. }
  316. /**
  317. * Prints the upgrade page
  318. */
  319. private static function printUpgradePage() {
  320. $systemConfig = \OC::$server->getSystemConfig();
  321. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  322. $tooBig = false;
  323. if (!$disableWebUpdater) {
  324. $apps = \OC::$server->getAppManager();
  325. $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
  326. if (!$tooBig) {
  327. // count users
  328. $stats = \OC::$server->getUserManager()->countUsers();
  329. $totalUsers = array_sum($stats);
  330. $tooBig = ($totalUsers > 50);
  331. }
  332. }
  333. if ($disableWebUpdater || $tooBig) {
  334. // send http status 503
  335. header('HTTP/1.1 503 Service Temporarily Unavailable');
  336. header('Status: 503 Service Temporarily Unavailable');
  337. header('Retry-After: 120');
  338. // render error page
  339. $template = new OC_Template('', 'update.use-cli', 'guest');
  340. $template->assign('productName', 'owncloud'); // for now
  341. $template->assign('version', OC_Util::getVersionString());
  342. $template->assign('tooBig', $tooBig);
  343. $template->printPage();
  344. die();
  345. }
  346. // check whether this is a core update or apps update
  347. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  348. $currentVersion = implode('.', \OCP\Util::getVersion());
  349. // if not a core upgrade, then it's apps upgrade
  350. $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
  351. $oldTheme = $systemConfig->getValue('theme');
  352. $systemConfig->setValue('theme', '');
  353. \OCP\Util::addScript('config'); // needed for web root
  354. \OCP\Util::addScript('update');
  355. \OCP\Util::addStyle('update');
  356. $appManager = \OC::$server->getAppManager();
  357. $tmpl = new OC_Template('', 'update.admin', 'guest');
  358. $tmpl->assign('version', OC_Util::getVersionString());
  359. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  360. // get third party apps
  361. $ocVersion = \OCP\Util::getVersion();
  362. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  363. $tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
  364. $tmpl->assign('productName', 'ownCloud'); // for now
  365. $tmpl->assign('oldTheme', $oldTheme);
  366. $tmpl->printPage();
  367. }
  368. public static function initSession() {
  369. // prevents javascript from accessing php session cookies
  370. ini_set('session.cookie_httponly', true);
  371. // set the cookie path to the Nextcloud directory
  372. $cookie_path = OC::$WEBROOT ? : '/';
  373. ini_set('session.cookie_path', $cookie_path);
  374. // Let the session name be changed in the initSession Hook
  375. $sessionName = OC_Util::getInstanceId();
  376. try {
  377. // Allow session apps to create a custom session object
  378. $useCustomSession = false;
  379. $session = self::$server->getSession();
  380. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  381. if (!$useCustomSession) {
  382. // set the session name to the instance id - which is unique
  383. $session = new \OC\Session\Internal($sessionName);
  384. }
  385. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  386. $session = $cryptoWrapper->wrapSession($session);
  387. self::$server->setSession($session);
  388. // if session can't be started break with http 500 error
  389. } catch (Exception $e) {
  390. \OCP\Util::logException('base', $e);
  391. //show the user a detailed error page
  392. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  393. OC_Template::printExceptionErrorPage($e);
  394. die();
  395. }
  396. $sessionLifeTime = self::getSessionLifeTime();
  397. // session timeout
  398. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  399. if (isset($_COOKIE[session_name()])) {
  400. setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
  401. }
  402. \OC::$server->getUserSession()->logout();
  403. }
  404. $session->set('LAST_ACTIVITY', time());
  405. }
  406. /**
  407. * @return string
  408. */
  409. private static function getSessionLifeTime() {
  410. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  411. }
  412. public static function loadAppClassPaths() {
  413. foreach (OC_App::getEnabledApps() as $app) {
  414. $appPath = OC_App::getAppPath($app);
  415. if ($appPath === false) {
  416. continue;
  417. }
  418. $file = $appPath . '/appinfo/classpath.php';
  419. if (file_exists($file)) {
  420. require_once $file;
  421. }
  422. }
  423. }
  424. /**
  425. * Try to set some values to the required Nextcloud default
  426. */
  427. public static function setRequiredIniValues() {
  428. @ini_set('default_charset', 'UTF-8');
  429. @ini_set('gd.jpeg_ignore_warning', 1);
  430. }
  431. public static function init() {
  432. // calculate the root directories
  433. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  434. // register autoloader
  435. $loaderStart = microtime(true);
  436. require_once __DIR__ . '/autoloader.php';
  437. self::$loader = new \OC\Autoloader([
  438. OC::$SERVERROOT . '/lib/private/legacy',
  439. ]);
  440. if (defined('PHPUNIT_RUN')) {
  441. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  442. }
  443. spl_autoload_register(array(self::$loader, 'load'));
  444. $loaderEnd = microtime(true);
  445. self::$CLI = (php_sapi_name() == 'cli');
  446. // Add default composer PSR-4 autoloader
  447. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  448. try {
  449. self::initPaths();
  450. // setup 3rdparty autoloader
  451. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  452. if (!file_exists($vendorAutoLoad)) {
  453. 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".');
  454. }
  455. require_once $vendorAutoLoad;
  456. } catch (\RuntimeException $e) {
  457. if (!self::$CLI) {
  458. $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
  459. $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
  460. header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
  461. }
  462. // we can't use the template error page here, because this needs the
  463. // DI container which isn't available yet
  464. print($e->getMessage());
  465. exit();
  466. }
  467. // setup the basic server
  468. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  469. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  470. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  471. // Don't display errors and log them
  472. error_reporting(E_ALL | E_STRICT);
  473. @ini_set('display_errors', 0);
  474. @ini_set('log_errors', 1);
  475. date_default_timezone_set('UTC');
  476. //try to configure php to enable big file uploads.
  477. //this doesn´t work always depending on the webserver and php configuration.
  478. //Let´s try to overwrite some defaults anyway
  479. //try to set the maximum execution time to 60min
  480. @set_time_limit(3600);
  481. @ini_set('max_execution_time', 3600);
  482. @ini_set('max_input_time', 3600);
  483. //try to set the maximum filesize to 10G
  484. @ini_set('upload_max_filesize', '10G');
  485. @ini_set('post_max_size', '10G');
  486. @ini_set('file_uploads', '50');
  487. self::setRequiredIniValues();
  488. self::handleAuthHeaders();
  489. self::registerAutoloaderCache();
  490. // initialize intl fallback is necessary
  491. \Patchwork\Utf8\Bootup::initIntl();
  492. OC_Util::isSetLocaleWorking();
  493. if (!defined('PHPUNIT_RUN')) {
  494. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  495. $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
  496. OC\Log\ErrorHandler::register($debug);
  497. }
  498. // register the stream wrappers
  499. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  500. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  501. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  502. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  503. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  504. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  505. OC_App::loadApps(array('session'));
  506. if (!self::$CLI) {
  507. self::initSession();
  508. }
  509. \OC::$server->getEventLogger()->end('init_session');
  510. self::checkConfig();
  511. self::checkInstalled();
  512. OC_Response::addSecurityHeaders();
  513. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  514. ini_set('session.cookie_secure', true);
  515. }
  516. if (!defined('OC_CONSOLE')) {
  517. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  518. if (count($errors) > 0) {
  519. if (self::$CLI) {
  520. // Convert l10n string into regular string for usage in database
  521. $staticErrors = [];
  522. foreach ($errors as $error) {
  523. echo $error['error'] . "\n";
  524. echo $error['hint'] . "\n\n";
  525. $staticErrors[] = [
  526. 'error' => (string)$error['error'],
  527. 'hint' => (string)$error['hint'],
  528. ];
  529. }
  530. try {
  531. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  532. } catch (\Exception $e) {
  533. echo('Writing to database failed');
  534. }
  535. exit(1);
  536. } else {
  537. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  538. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  539. exit;
  540. }
  541. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  542. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  543. }
  544. }
  545. //try to set the session lifetime
  546. $sessionLifeTime = self::getSessionLifeTime();
  547. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  548. $systemConfig = \OC::$server->getSystemConfig();
  549. // User and Groups
  550. if (!$systemConfig->getValue("installed", false)) {
  551. self::$server->getSession()->set('user_id', '');
  552. }
  553. OC_User::useBackend(new \OC\User\Database());
  554. OC_Group::useBackend(new \OC\Group\Database());
  555. // Subscribe to the hook
  556. \OCP\Util::connectHook(
  557. '\OCA\Files_Sharing\API\Server2Server',
  558. 'preLoginNameUsedAsUserName',
  559. '\OC\User\Database',
  560. 'preLoginNameUsedAsUserName'
  561. );
  562. //setup extra user backends
  563. if (!self::checkUpgrade(false)) {
  564. OC_User::setupBackends();
  565. } else {
  566. // Run upgrades in incognito mode
  567. OC_User::setIncognitoMode(true);
  568. }
  569. self::registerCacheHooks();
  570. self::registerFilesystemHooks();
  571. if ($systemConfig->getValue('enable_previews', true)) {
  572. self::registerPreviewHooks();
  573. }
  574. self::registerShareHooks();
  575. self::registerLogRotate();
  576. self::registerEncryptionWrapper();
  577. self::registerEncryptionHooks();
  578. //make sure temporary files are cleaned up
  579. $tmpManager = \OC::$server->getTempManager();
  580. register_shutdown_function(array($tmpManager, 'clean'));
  581. $lockProvider = \OC::$server->getLockingProvider();
  582. register_shutdown_function(array($lockProvider, 'releaseAll'));
  583. // Check whether the sample configuration has been copied
  584. if($systemConfig->getValue('copied_sample_config', false)) {
  585. $l = \OC::$server->getL10N('lib');
  586. header('HTTP/1.1 503 Service Temporarily Unavailable');
  587. header('Status: 503 Service Temporarily Unavailable');
  588. OC_Template::printErrorPage(
  589. $l->t('Sample configuration detected'),
  590. $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')
  591. );
  592. return;
  593. }
  594. $request = \OC::$server->getRequest();
  595. $host = $request->getInsecureServerHost();
  596. /**
  597. * if the host passed in headers isn't trusted
  598. * FIXME: Should not be in here at all :see_no_evil:
  599. */
  600. if (!OC::$CLI
  601. // overwritehost is always trusted, workaround to not have to make
  602. // \OC\AppFramework\Http\Request::getOverwriteHost public
  603. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  604. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  605. && self::$server->getConfig()->getSystemValue('installed', false)
  606. ) {
  607. header('HTTP/1.1 400 Bad Request');
  608. header('Status: 400 Bad Request');
  609. \OC::$server->getLogger()->warning(
  610. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  611. [
  612. 'app' => 'core',
  613. 'remoteAddress' => $request->getRemoteAddress(),
  614. 'host' => $host,
  615. ]
  616. );
  617. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  618. $tmpl->assign('domain', $host);
  619. $tmpl->printPage();
  620. exit();
  621. }
  622. \OC::$server->getEventLogger()->end('boot');
  623. }
  624. /**
  625. * register hooks for the cache
  626. */
  627. public static function registerCacheHooks() {
  628. //don't try to do this before we are properly setup
  629. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  630. // NOTE: This will be replaced to use OCP
  631. $userSession = self::$server->getUserSession();
  632. $userSession->listen('\OC\User', 'postLogin', function () {
  633. try {
  634. $cache = new \OC\Cache\File();
  635. $cache->gc();
  636. } catch (\OC\ServerNotAvailableException $e) {
  637. // not a GC exception, pass it on
  638. throw $e;
  639. } catch (\Exception $e) {
  640. // a GC exception should not prevent users from using OC,
  641. // so log the exception
  642. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  643. }
  644. });
  645. }
  646. }
  647. private static function registerEncryptionWrapper() {
  648. $manager = self::$server->getEncryptionManager();
  649. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  650. }
  651. private static function registerEncryptionHooks() {
  652. $enabled = self::$server->getEncryptionManager()->isEnabled();
  653. if ($enabled) {
  654. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  655. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  656. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  657. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  658. }
  659. }
  660. /**
  661. * register hooks for the cache
  662. */
  663. public static function registerLogRotate() {
  664. $systemConfig = \OC::$server->getSystemConfig();
  665. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  666. //don't try to do this before we are properly setup
  667. //use custom logfile path if defined, otherwise use default of owncloud.log in data directory
  668. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
  669. }
  670. }
  671. /**
  672. * register hooks for the filesystem
  673. */
  674. public static function registerFilesystemHooks() {
  675. // Check for blacklisted files
  676. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  677. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  678. }
  679. /**
  680. * register hooks for previews
  681. */
  682. public static function registerPreviewHooks() {
  683. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  684. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  685. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  686. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  687. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  688. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
  689. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  690. OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
  691. }
  692. /**
  693. * register hooks for sharing
  694. */
  695. public static function registerShareHooks() {
  696. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  697. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
  698. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
  699. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
  700. }
  701. }
  702. protected static function registerAutoloaderCache() {
  703. // The class loader takes an optional low-latency cache, which MUST be
  704. // namespaced. The instanceid is used for namespacing, but might be
  705. // unavailable at this point. Furthermore, it might not be possible to
  706. // generate an instanceid via \OC_Util::getInstanceId() because the
  707. // config file may not be writable. As such, we only register a class
  708. // loader cache if instanceid is available without trying to create one.
  709. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  710. if ($instanceId) {
  711. try {
  712. $memcacheFactory = \OC::$server->getMemCacheFactory();
  713. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  714. } catch (\Exception $ex) {
  715. }
  716. }
  717. }
  718. /**
  719. * Handle the request
  720. */
  721. public static function handleRequest() {
  722. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  723. $systemConfig = \OC::$server->getSystemConfig();
  724. // load all the classpaths from the enabled apps so they are available
  725. // in the routing files of each app
  726. OC::loadAppClassPaths();
  727. // Check if Nextcloud is installed or in maintenance (update) mode
  728. if (!$systemConfig->getValue('installed', false)) {
  729. \OC::$server->getSession()->clear();
  730. $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
  731. \OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
  732. \OC::$server->getSecureRandom());
  733. $controller = new OC\Core\Controller\SetupController($setupHelper);
  734. $controller->run($_POST);
  735. exit();
  736. }
  737. $request = \OC::$server->getRequest();
  738. $requestPath = $request->getRawPathInfo();
  739. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  740. self::checkMaintenanceMode($request);
  741. self::checkUpgrade();
  742. }
  743. // emergency app disabling
  744. if ($requestPath === '/disableapp'
  745. && $request->getMethod() === 'POST'
  746. && ((string)$request->getParam('appid')) !== ''
  747. ) {
  748. \OCP\JSON::callCheck();
  749. \OCP\JSON::checkAdminUser();
  750. $appId = (string)$request->getParam('appid');
  751. $appId = \OC_App::cleanAppId($appId);
  752. \OC_App::disable($appId);
  753. \OC_JSON::success();
  754. exit();
  755. }
  756. // Always load authentication apps
  757. OC_App::loadApps(['authentication']);
  758. // Load minimum set of apps
  759. if (!self::checkUpgrade(false)
  760. && !$systemConfig->getValue('maintenance', false)) {
  761. // For logged-in users: Load everything
  762. if(OC_User::isLoggedIn()) {
  763. OC_App::loadApps();
  764. } else {
  765. // For guests: Load only filesystem and logging
  766. OC_App::loadApps(array('filesystem', 'logging'));
  767. self::handleLogin($request);
  768. }
  769. }
  770. if (!self::$CLI) {
  771. try {
  772. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  773. OC_App::loadApps(array('filesystem', 'logging'));
  774. OC_App::loadApps();
  775. }
  776. self::checkSingleUserMode();
  777. OC_Util::setupFS();
  778. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  779. return;
  780. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  781. //header('HTTP/1.0 404 Not Found');
  782. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  783. OC_Response::setStatus(405);
  784. return;
  785. }
  786. }
  787. // Handle WebDAV
  788. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  789. // not allowed any more to prevent people
  790. // mounting this root directly.
  791. // Users need to mount remote.php/webdav instead.
  792. header('HTTP/1.1 405 Method Not Allowed');
  793. header('Status: 405 Method Not Allowed');
  794. return;
  795. }
  796. // Someone is logged in
  797. if (OC_User::isLoggedIn()) {
  798. OC_App::loadApps();
  799. OC_User::setupBackends();
  800. OC_Util::setupFS();
  801. // FIXME
  802. // Redirect to default application
  803. OC_Util::redirectToDefaultPage();
  804. } else {
  805. // Not handled and not logged in
  806. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  807. }
  808. }
  809. /**
  810. * Check login: apache auth, auth token, basic auth
  811. *
  812. * @param OCP\IRequest $request
  813. * @return boolean
  814. */
  815. private static function handleLogin(OCP\IRequest $request) {
  816. $userSession = self::$server->getUserSession();
  817. if (OC_User::handleApacheAuth()) {
  818. return true;
  819. }
  820. if ($userSession->tryTokenLogin($request)) {
  821. return true;
  822. }
  823. if ($userSession->tryBasicAuthLogin($request)) {
  824. return true;
  825. }
  826. return false;
  827. }
  828. protected static function handleAuthHeaders() {
  829. //copy http auth headers for apache+php-fcgid work around
  830. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  831. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  832. }
  833. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  834. $vars = array(
  835. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  836. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  837. );
  838. foreach ($vars as $var) {
  839. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  840. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  841. $_SERVER['PHP_AUTH_USER'] = $name;
  842. $_SERVER['PHP_AUTH_PW'] = $password;
  843. break;
  844. }
  845. }
  846. }
  847. }
  848. OC::init();