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 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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 owncloud on the server (e.g. /srv/http/owncloud)
  65. */
  66. public static $SERVERROOT = '';
  67. /**
  68. * the current request path relative to the owncloud root (e.g. files/index.php)
  69. */
  70. private static $SUBURI = '';
  71. /**
  72. * the owncloud root path for http requests (e.g. owncloud/)
  73. */
  74. public static $WEBROOT = '';
  75. /**
  76. * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) '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 ownCloud 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 /owncloud to /owncloud/ 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 ownCloud apps folder in the ownCloud 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 ownCloud apps folder in the'
  193. . ' ownCloud 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 ownCloud 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 ownCloud 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. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  459. }
  460. // we can't use the template error page here, because this needs the
  461. // DI container which isn't available yet
  462. print($e->getMessage());
  463. exit();
  464. }
  465. // setup the basic server
  466. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  467. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  468. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  469. // Don't display errors and log them
  470. error_reporting(E_ALL | E_STRICT);
  471. @ini_set('display_errors', 0);
  472. @ini_set('log_errors', 1);
  473. date_default_timezone_set('UTC');
  474. //try to configure php to enable big file uploads.
  475. //this doesn´t work always depending on the webserver and php configuration.
  476. //Let´s try to overwrite some defaults anyway
  477. //try to set the maximum execution time to 60min
  478. @set_time_limit(3600);
  479. @ini_set('max_execution_time', 3600);
  480. @ini_set('max_input_time', 3600);
  481. //try to set the maximum filesize to 10G
  482. @ini_set('upload_max_filesize', '10G');
  483. @ini_set('post_max_size', '10G');
  484. @ini_set('file_uploads', '50');
  485. self::setRequiredIniValues();
  486. self::handleAuthHeaders();
  487. self::registerAutoloaderCache();
  488. // initialize intl fallback is necessary
  489. \Patchwork\Utf8\Bootup::initIntl();
  490. OC_Util::isSetLocaleWorking();
  491. if (!defined('PHPUNIT_RUN')) {
  492. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  493. $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
  494. OC\Log\ErrorHandler::register($debug);
  495. }
  496. // register the stream wrappers
  497. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  498. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  499. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  500. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  501. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  502. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  503. OC_App::loadApps(array('session'));
  504. if (!self::$CLI) {
  505. self::initSession();
  506. }
  507. \OC::$server->getEventLogger()->end('init_session');
  508. self::checkConfig();
  509. self::checkInstalled();
  510. OC_Response::addSecurityHeaders();
  511. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  512. ini_set('session.cookie_secure', true);
  513. }
  514. if (!defined('OC_CONSOLE')) {
  515. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  516. if (count($errors) > 0) {
  517. if (self::$CLI) {
  518. // Convert l10n string into regular string for usage in database
  519. $staticErrors = [];
  520. foreach ($errors as $error) {
  521. echo $error['error'] . "\n";
  522. echo $error['hint'] . "\n\n";
  523. $staticErrors[] = [
  524. 'error' => (string)$error['error'],
  525. 'hint' => (string)$error['hint'],
  526. ];
  527. }
  528. try {
  529. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  530. } catch (\Exception $e) {
  531. echo('Writing to database failed');
  532. }
  533. exit(1);
  534. } else {
  535. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  536. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  537. exit;
  538. }
  539. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  540. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  541. }
  542. }
  543. //try to set the session lifetime
  544. $sessionLifeTime = self::getSessionLifeTime();
  545. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  546. $systemConfig = \OC::$server->getSystemConfig();
  547. // User and Groups
  548. if (!$systemConfig->getValue("installed", false)) {
  549. self::$server->getSession()->set('user_id', '');
  550. }
  551. OC_User::useBackend(new \OC\User\Database());
  552. OC_Group::useBackend(new \OC\Group\Database());
  553. // Subscribe to the hook
  554. \OCP\Util::connectHook(
  555. '\OCA\Files_Sharing\API\Server2Server',
  556. 'preLoginNameUsedAsUserName',
  557. '\OC\User\Database',
  558. 'preLoginNameUsedAsUserName'
  559. );
  560. //setup extra user backends
  561. if (!self::checkUpgrade(false)) {
  562. OC_User::setupBackends();
  563. } else {
  564. // Run upgrades in incognito mode
  565. OC_User::setIncognitoMode(true);
  566. }
  567. self::registerCacheHooks();
  568. self::registerFilesystemHooks();
  569. if ($systemConfig->getValue('enable_previews', true)) {
  570. self::registerPreviewHooks();
  571. }
  572. self::registerShareHooks();
  573. self::registerLogRotate();
  574. self::registerEncryptionWrapper();
  575. self::registerEncryptionHooks();
  576. //make sure temporary files are cleaned up
  577. $tmpManager = \OC::$server->getTempManager();
  578. register_shutdown_function(array($tmpManager, 'clean'));
  579. $lockProvider = \OC::$server->getLockingProvider();
  580. register_shutdown_function(array($lockProvider, 'releaseAll'));
  581. // Check whether the sample configuration has been copied
  582. if($systemConfig->getValue('copied_sample_config', false)) {
  583. $l = \OC::$server->getL10N('lib');
  584. header('HTTP/1.1 503 Service Temporarily Unavailable');
  585. header('Status: 503 Service Temporarily Unavailable');
  586. OC_Template::printErrorPage(
  587. $l->t('Sample configuration detected'),
  588. $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')
  589. );
  590. return;
  591. }
  592. $request = \OC::$server->getRequest();
  593. $host = $request->getInsecureServerHost();
  594. /**
  595. * if the host passed in headers isn't trusted
  596. * FIXME: Should not be in here at all :see_no_evil:
  597. */
  598. if (!OC::$CLI
  599. // overwritehost is always trusted, workaround to not have to make
  600. // \OC\AppFramework\Http\Request::getOverwriteHost public
  601. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  602. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  603. && self::$server->getConfig()->getSystemValue('installed', false)
  604. ) {
  605. header('HTTP/1.1 400 Bad Request');
  606. header('Status: 400 Bad Request');
  607. \OC::$server->getLogger()->warning(
  608. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  609. [
  610. 'app' => 'core',
  611. 'remoteAddress' => $request->getRemoteAddress(),
  612. 'host' => $host,
  613. ]
  614. );
  615. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  616. $tmpl->assign('domain', $host);
  617. $tmpl->printPage();
  618. exit();
  619. }
  620. \OC::$server->getEventLogger()->end('boot');
  621. }
  622. /**
  623. * register hooks for the cache
  624. */
  625. public static function registerCacheHooks() {
  626. //don't try to do this before we are properly setup
  627. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  628. // NOTE: This will be replaced to use OCP
  629. $userSession = self::$server->getUserSession();
  630. $userSession->listen('\OC\User', 'postLogin', function () {
  631. try {
  632. $cache = new \OC\Cache\File();
  633. $cache->gc();
  634. } catch (\OC\ServerNotAvailableException $e) {
  635. // not a GC exception, pass it on
  636. throw $e;
  637. } catch (\Exception $e) {
  638. // a GC exception should not prevent users from using OC,
  639. // so log the exception
  640. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  641. }
  642. });
  643. }
  644. }
  645. private static function registerEncryptionWrapper() {
  646. $manager = self::$server->getEncryptionManager();
  647. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  648. }
  649. private static function registerEncryptionHooks() {
  650. $enabled = self::$server->getEncryptionManager()->isEnabled();
  651. if ($enabled) {
  652. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  653. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  654. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  655. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  656. }
  657. }
  658. /**
  659. * register hooks for the cache
  660. */
  661. public static function registerLogRotate() {
  662. $systemConfig = \OC::$server->getSystemConfig();
  663. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  664. //don't try to do this before we are properly setup
  665. //use custom logfile path if defined, otherwise use default of owncloud.log in data directory
  666. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
  667. }
  668. }
  669. /**
  670. * register hooks for the filesystem
  671. */
  672. public static function registerFilesystemHooks() {
  673. // Check for blacklisted files
  674. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  675. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  676. }
  677. /**
  678. * register hooks for previews
  679. */
  680. public static function registerPreviewHooks() {
  681. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  682. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  683. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  684. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  685. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  686. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
  687. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  688. OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
  689. }
  690. /**
  691. * register hooks for sharing
  692. */
  693. public static function registerShareHooks() {
  694. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  695. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
  696. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
  697. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
  698. }
  699. }
  700. protected static function registerAutoloaderCache() {
  701. // The class loader takes an optional low-latency cache, which MUST be
  702. // namespaced. The instanceid is used for namespacing, but might be
  703. // unavailable at this point. Furthermore, it might not be possible to
  704. // generate an instanceid via \OC_Util::getInstanceId() because the
  705. // config file may not be writable. As such, we only register a class
  706. // loader cache if instanceid is available without trying to create one.
  707. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  708. if ($instanceId) {
  709. try {
  710. $memcacheFactory = \OC::$server->getMemCacheFactory();
  711. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  712. } catch (\Exception $ex) {
  713. }
  714. }
  715. }
  716. /**
  717. * Handle the request
  718. */
  719. public static function handleRequest() {
  720. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  721. $systemConfig = \OC::$server->getSystemConfig();
  722. // load all the classpaths from the enabled apps so they are available
  723. // in the routing files of each app
  724. OC::loadAppClassPaths();
  725. // Check if ownCloud is installed or in maintenance (update) mode
  726. if (!$systemConfig->getValue('installed', false)) {
  727. \OC::$server->getSession()->clear();
  728. $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
  729. \OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
  730. \OC::$server->getSecureRandom());
  731. $controller = new OC\Core\Controller\SetupController($setupHelper);
  732. $controller->run($_POST);
  733. exit();
  734. }
  735. $request = \OC::$server->getRequest();
  736. $requestPath = $request->getRawPathInfo();
  737. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  738. self::checkMaintenanceMode($request);
  739. self::checkUpgrade();
  740. }
  741. // emergency app disabling
  742. if ($requestPath === '/disableapp'
  743. && $request->getMethod() === 'POST'
  744. && ((string)$request->getParam('appid')) !== ''
  745. ) {
  746. \OCP\JSON::callCheck();
  747. \OCP\JSON::checkAdminUser();
  748. $appId = (string)$request->getParam('appid');
  749. $appId = \OC_App::cleanAppId($appId);
  750. \OC_App::disable($appId);
  751. \OC_JSON::success();
  752. exit();
  753. }
  754. // Always load authentication apps
  755. OC_App::loadApps(['authentication']);
  756. // Load minimum set of apps
  757. if (!self::checkUpgrade(false)
  758. && !$systemConfig->getValue('maintenance', false)) {
  759. // For logged-in users: Load everything
  760. if(OC_User::isLoggedIn()) {
  761. OC_App::loadApps();
  762. } else {
  763. // For guests: Load only filesystem and logging
  764. OC_App::loadApps(array('filesystem', 'logging'));
  765. self::handleLogin($request);
  766. }
  767. }
  768. if (!self::$CLI) {
  769. try {
  770. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  771. OC_App::loadApps(array('filesystem', 'logging'));
  772. OC_App::loadApps();
  773. }
  774. self::checkSingleUserMode();
  775. OC_Util::setupFS();
  776. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  777. return;
  778. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  779. //header('HTTP/1.0 404 Not Found');
  780. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  781. OC_Response::setStatus(405);
  782. return;
  783. }
  784. }
  785. // Handle WebDAV
  786. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  787. // not allowed any more to prevent people
  788. // mounting this root directly.
  789. // Users need to mount remote.php/webdav instead.
  790. header('HTTP/1.1 405 Method Not Allowed');
  791. header('Status: 405 Method Not Allowed');
  792. return;
  793. }
  794. // Someone is logged in
  795. if (OC_User::isLoggedIn()) {
  796. OC_App::loadApps();
  797. OC_User::setupBackends();
  798. OC_Util::setupFS();
  799. // FIXME
  800. // Redirect to default application
  801. OC_Util::redirectToDefaultPage();
  802. } else {
  803. // Not handled and not logged in
  804. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  805. }
  806. }
  807. /**
  808. * Check login: apache auth, auth token, basic auth
  809. *
  810. * @param OCP\IRequest $request
  811. * @return boolean
  812. */
  813. private static function handleLogin(OCP\IRequest $request) {
  814. $userSession = self::$server->getUserSession();
  815. if (OC_User::handleApacheAuth()) {
  816. return true;
  817. }
  818. if ($userSession->tryTokenLogin($request)) {
  819. return true;
  820. }
  821. if ($userSession->tryBasicAuthLogin($request)) {
  822. return true;
  823. }
  824. return false;
  825. }
  826. protected static function handleAuthHeaders() {
  827. //copy http auth headers for apache+php-fcgid work around
  828. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  829. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  830. }
  831. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  832. $vars = array(
  833. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  834. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  835. );
  836. foreach ($vars as $var) {
  837. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  838. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  839. $_SERVER['PHP_AUTH_USER'] = $name;
  840. $_SERVER['PHP_AUTH_PW'] = $password;
  841. break;
  842. }
  843. }
  844. }
  845. }
  846. OC::init();