base.php 37 KB

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