You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.php 36KB

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