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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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 <rmccorkell@karoshi.org.uk>
  30. * @author scolebrook <scolebrook@mac.com>
  31. * @author Stefan Herbrechtsmeier <stefan@herbrechtsmeier.net>
  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) 2015, 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. * @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. OC_Config::$object = 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()));
  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 = OC_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 = OC_Config::getValue('overwritewebroot', '');
  157. }
  158. }
  159. // search the 3rdparty folder
  160. OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', null);
  161. OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', null);
  162. if (empty(OC::$THIRDPARTYROOT) && empty(OC::$THIRDPARTYWEBROOT)) {
  163. if (file_exists(OC::$SERVERROOT . '/3rdparty')) {
  164. OC::$THIRDPARTYROOT = OC::$SERVERROOT;
  165. OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
  166. } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
  167. OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
  168. OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
  169. }
  170. }
  171. if (empty(OC::$THIRDPARTYROOT) || !file_exists(OC::$THIRDPARTYROOT)) {
  172. throw new \RuntimeException('3rdparty directory not found! Please put the ownCloud 3rdparty'
  173. . ' folder in the ownCloud folder or the folder above.'
  174. . ' You can also configure the location in the config.php file.');
  175. }
  176. // search the apps folder
  177. $config_paths = OC_Config::getValue('apps_paths', array());
  178. if (!empty($config_paths)) {
  179. foreach ($config_paths as $paths) {
  180. if (isset($paths['url']) && isset($paths['path'])) {
  181. $paths['url'] = rtrim($paths['url'], '/');
  182. $paths['path'] = rtrim($paths['path'], '/');
  183. OC::$APPSROOTS[] = $paths;
  184. }
  185. }
  186. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  187. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  188. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  189. OC::$APPSROOTS[] = array(
  190. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  191. 'url' => '/apps',
  192. 'writable' => true
  193. );
  194. }
  195. if (empty(OC::$APPSROOTS)) {
  196. throw new \RuntimeException('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
  197. . ' or the folder above. You can also configure the location in the config.php file.');
  198. }
  199. $paths = array();
  200. foreach (OC::$APPSROOTS as $path) {
  201. $paths[] = $path['path'];
  202. if (!is_dir($path['path'])) {
  203. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the ownCloud apps folder in the'
  204. . ' ownCloud folder or the folder above. You can also configure the location in the'
  205. . ' config.php file.', $path['path']));
  206. }
  207. }
  208. // set the right include path
  209. set_include_path(
  210. OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
  211. OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
  212. OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
  213. implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
  214. get_include_path() . PATH_SEPARATOR .
  215. OC::$SERVERROOT
  216. );
  217. }
  218. public static function checkConfig() {
  219. $l = \OC::$server->getL10N('lib');
  220. // Create config if it does not already exist
  221. $configFilePath = self::$configDir .'/config.php';
  222. if(!file_exists($configFilePath)) {
  223. @touch($configFilePath);
  224. }
  225. // Check if config is writable
  226. $configFileWritable = is_writable($configFilePath);
  227. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  228. || !$configFileWritable && self::checkUpgrade(false)) {
  229. if (self::$CLI) {
  230. echo $l->t('Cannot write into "config" directory!')."\n";
  231. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  232. echo "\n";
  233. echo $l->t('See %s', array(\OC_Helper::linkToDocs('admin-dir_permissions')))."\n";
  234. exit;
  235. } else {
  236. OC_Template::printErrorPage(
  237. $l->t('Cannot write into "config" directory!'),
  238. $l->t('This can usually be fixed by '
  239. . '%sgiving the webserver write access to the config directory%s.',
  240. array('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>'))
  241. );
  242. }
  243. }
  244. }
  245. public static function checkInstalled() {
  246. if (defined('OC_CONSOLE')) {
  247. return;
  248. }
  249. // Redirect to installer if not installed
  250. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
  251. if (OC::$CLI) {
  252. throw new Exception('Not installed');
  253. } else {
  254. $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
  255. header('Location: ' . $url);
  256. }
  257. exit();
  258. }
  259. }
  260. public static function checkMaintenanceMode() {
  261. // Allow ajax update script to execute without being stopped
  262. if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  263. // send http status 503
  264. header('HTTP/1.1 503 Service Temporarily Unavailable');
  265. header('Status: 503 Service Temporarily Unavailable');
  266. header('Retry-After: 120');
  267. // render error page
  268. $template = new OC_Template('', 'update.user', 'guest');
  269. OC_Util::addscript('maintenance-check');
  270. $template->printPage();
  271. die();
  272. }
  273. }
  274. public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
  275. if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
  276. return;
  277. }
  278. $user = OC_User::getUserSession()->getUser();
  279. if ($user) {
  280. $group = \OC::$server->getGroupManager()->get('admin');
  281. if ($group->inGroup($user)) {
  282. return;
  283. }
  284. } else {
  285. if(!$lockIfNoUserLoggedIn) {
  286. return;
  287. }
  288. }
  289. // send http status 503
  290. header('HTTP/1.1 503 Service Temporarily Unavailable');
  291. header('Status: 503 Service Temporarily Unavailable');
  292. header('Retry-After: 120');
  293. // render error page
  294. $template = new OC_Template('', 'singleuser.user', 'guest');
  295. $template->printPage();
  296. die();
  297. }
  298. /**
  299. * check if the instance needs to perform an upgrade
  300. *
  301. * @return bool
  302. * @deprecated use \OCP\Util::needUpgrade() instead
  303. */
  304. public static function needUpgrade() {
  305. return \OCP\Util::needUpgrade();
  306. }
  307. /**
  308. * Checks if the version requires an update and shows
  309. * @param bool $showTemplate Whether an update screen should get shown
  310. * @return bool|void
  311. */
  312. public static function checkUpgrade($showTemplate = true) {
  313. if (\OCP\Util::needUpgrade()) {
  314. $systemConfig = \OC::$server->getSystemConfig();
  315. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  316. self::printUpgradePage();
  317. exit();
  318. } else {
  319. return true;
  320. }
  321. }
  322. return false;
  323. }
  324. /**
  325. * Prints the upgrade page
  326. */
  327. private static function printUpgradePage() {
  328. $systemConfig = \OC::$server->getSystemConfig();
  329. $oldTheme = $systemConfig->getValue('theme');
  330. $systemConfig->setValue('theme', '');
  331. \OCP\Util::addScript('config'); // needed for web root
  332. \OCP\Util::addScript('update');
  333. // check whether this is a core update or apps update
  334. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  335. $currentVersion = implode('.', OC_Util::getVersion());
  336. $appManager = \OC::$server->getAppManager();
  337. $tmpl = new OC_Template('', 'update.admin', 'guest');
  338. $tmpl->assign('version', OC_Util::getVersionString());
  339. // if not a core upgrade, then it's apps upgrade
  340. if (version_compare($currentVersion, $installedVersion, '=')) {
  341. $tmpl->assign('isAppsOnlyUpgrade', true);
  342. } else {
  343. $tmpl->assign('isAppsOnlyUpgrade', false);
  344. }
  345. // get third party apps
  346. $ocVersion = OC_Util::getVersion();
  347. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  348. $tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
  349. $tmpl->assign('productName', 'ownCloud'); // for now
  350. $tmpl->assign('oldTheme', $oldTheme);
  351. $tmpl->printPage();
  352. }
  353. public static function initSession() {
  354. // prevents javascript from accessing php session cookies
  355. ini_set('session.cookie_httponly', true);
  356. // set the cookie path to the ownCloud directory
  357. $cookie_path = OC::$WEBROOT ? : '/';
  358. ini_set('session.cookie_path', $cookie_path);
  359. // Let the session name be changed in the initSession Hook
  360. $sessionName = OC_Util::getInstanceId();
  361. try {
  362. // Allow session apps to create a custom session object
  363. $useCustomSession = false;
  364. $session = self::$server->getSession();
  365. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  366. if (!$useCustomSession) {
  367. // set the session name to the instance id - which is unique
  368. $session = new \OC\Session\Internal($sessionName);
  369. }
  370. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  371. $session = $cryptoWrapper->wrapSession($session);
  372. self::$server->setSession($session);
  373. // if session cant be started break with http 500 error
  374. } catch (Exception $e) {
  375. \OCP\Util::logException('base', $e);
  376. //show the user a detailed error page
  377. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  378. OC_Template::printExceptionErrorPage($e);
  379. }
  380. $sessionLifeTime = self::getSessionLifeTime();
  381. // regenerate session id periodically to avoid session fixation
  382. /**
  383. * @var \OCP\ISession $session
  384. */
  385. $session = self::$server->getSession();
  386. if (!$session->exists('SID_CREATED')) {
  387. $session->set('SID_CREATED', time());
  388. } else if (time() - $session->get('SID_CREATED') > $sessionLifeTime / 2) {
  389. session_regenerate_id(true);
  390. $session->set('SID_CREATED', time());
  391. }
  392. // session timeout
  393. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  394. if (isset($_COOKIE[session_name()])) {
  395. setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
  396. unset($_COOKIE[session_name()]);
  397. }
  398. session_unset();
  399. session_destroy();
  400. session_start();
  401. }
  402. $session->set('LAST_ACTIVITY', time());
  403. }
  404. /**
  405. * @return string
  406. */
  407. private static function getSessionLifeTime() {
  408. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  409. }
  410. public static function loadAppClassPaths() {
  411. foreach (OC_APP::getEnabledApps() as $app) {
  412. $file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
  413. if (file_exists($file)) {
  414. require_once $file;
  415. }
  416. }
  417. }
  418. /**
  419. * Try to set some values to the required ownCloud default
  420. */
  421. public static function setRequiredIniValues() {
  422. @ini_set('default_charset', 'UTF-8');
  423. }
  424. public static function init() {
  425. // calculate the root directories
  426. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  427. // register autoloader
  428. $loaderStart = microtime(true);
  429. require_once __DIR__ . '/autoloader.php';
  430. self::$loader = new \OC\Autoloader([
  431. OC::$SERVERROOT . '/lib',
  432. OC::$SERVERROOT . '/core',
  433. OC::$SERVERROOT . '/settings',
  434. OC::$SERVERROOT . '/ocs',
  435. OC::$SERVERROOT . '/ocs-provider',
  436. OC::$SERVERROOT . '/3rdparty',
  437. OC::$SERVERROOT . '/tests',
  438. ]);
  439. spl_autoload_register(array(self::$loader, 'load'));
  440. $loaderEnd = microtime(true);
  441. self::$CLI = (php_sapi_name() == 'cli');
  442. try {
  443. self::initPaths();
  444. // setup 3rdparty autoloader
  445. $vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
  446. if (!file_exists($vendorAutoLoad)) {
  447. 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".');
  448. }
  449. require_once $vendorAutoLoad;
  450. } catch (\RuntimeException $e) {
  451. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  452. // we can't use the template error page here, because this needs the
  453. // DI container which isn't available yet
  454. print($e->getMessage());
  455. exit();
  456. }
  457. // setup the basic server
  458. self::$server = new \OC\Server(\OC::$WEBROOT);
  459. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  460. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  461. // Don't display errors and log them
  462. error_reporting(E_ALL | E_STRICT);
  463. @ini_set('display_errors', 0);
  464. @ini_set('log_errors', 1);
  465. date_default_timezone_set('UTC');
  466. //try to configure php to enable big file uploads.
  467. //this doesn´t work always depending on the webserver and php configuration.
  468. //Let´s try to overwrite some defaults anyway
  469. //try to set the maximum execution time to 60min
  470. @set_time_limit(3600);
  471. @ini_set('max_execution_time', 3600);
  472. @ini_set('max_input_time', 3600);
  473. //try to set the maximum filesize to 10G
  474. @ini_set('upload_max_filesize', '10G');
  475. @ini_set('post_max_size', '10G');
  476. @ini_set('file_uploads', '50');
  477. self::setRequiredIniValues();
  478. self::handleAuthHeaders();
  479. self::registerAutoloaderCache();
  480. // initialize intl fallback is necessary
  481. \Patchwork\Utf8\Bootup::initIntl();
  482. OC_Util::isSetLocaleWorking();
  483. if (!defined('PHPUNIT_RUN')) {
  484. $logger = \OC::$server->getLogger();
  485. OC\Log\ErrorHandler::setLogger($logger);
  486. if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
  487. OC\Log\ErrorHandler::register(true);
  488. set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
  489. } else {
  490. OC\Log\ErrorHandler::register();
  491. }
  492. }
  493. // register the stream wrappers
  494. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  495. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  496. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  497. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  498. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  499. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  500. OC_App::loadApps(array('session'));
  501. if (!self::$CLI) {
  502. self::initSession();
  503. }
  504. \OC::$server->getEventLogger()->end('init_session');
  505. self::checkConfig();
  506. self::checkInstalled();
  507. OC_Response::addSecurityHeaders();
  508. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  509. ini_set('session.cookie_secure', true);
  510. }
  511. if (!defined('OC_CONSOLE')) {
  512. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  513. if (count($errors) > 0) {
  514. if (self::$CLI) {
  515. // Convert l10n string into regular string for usage in database
  516. $staticErrors = [];
  517. foreach ($errors as $error) {
  518. echo $error['error'] . "\n";
  519. echo $error['hint'] . "\n\n";
  520. $staticErrors[] = [
  521. 'error' => (string)$error['error'],
  522. 'hint' => (string)$error['hint'],
  523. ];
  524. }
  525. try {
  526. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  527. } catch (\Exception $e) {
  528. echo('Writing to database failed');
  529. }
  530. exit(1);
  531. } else {
  532. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  533. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  534. exit;
  535. }
  536. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  537. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  538. }
  539. }
  540. //try to set the session lifetime
  541. $sessionLifeTime = self::getSessionLifeTime();
  542. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  543. $systemConfig = \OC::$server->getSystemConfig();
  544. // User and Groups
  545. if (!$systemConfig->getValue("installed", false)) {
  546. self::$server->getSession()->set('user_id', '');
  547. }
  548. OC_User::useBackend(new OC_User_Database());
  549. OC_Group::useBackend(new OC_Group_Database());
  550. // Subscribe to the hook
  551. \OCP\Util::connectHook(
  552. '\OCA\Files_Sharing\API\Server2Server',
  553. 'preLoginNameUsedAsUserName',
  554. '\OC_User_Database',
  555. 'preLoginNameUsedAsUserName'
  556. );
  557. //setup extra user backends
  558. if (!self::checkUpgrade(false)) {
  559. OC_User::setupBackends();
  560. }
  561. self::registerCacheHooks();
  562. self::registerFilesystemHooks();
  563. if ($systemConfig->getValue('enable_previews', true)) {
  564. self::registerPreviewHooks();
  565. }
  566. self::registerShareHooks();
  567. self::registerLogRotate();
  568. self::registerLocalAddressBook();
  569. self::registerEncryptionWrapper();
  570. self::registerEncryptionHooks();
  571. //make sure temporary files are cleaned up
  572. $tmpManager = \OC::$server->getTempManager();
  573. register_shutdown_function(array($tmpManager, 'clean'));
  574. $lockProvider = \OC::$server->getLockingProvider();
  575. register_shutdown_function(array($lockProvider, 'releaseAll'));
  576. // Check whether the sample configuration has been copied
  577. if($systemConfig->getValue('copied_sample_config', false)) {
  578. $l = \OC::$server->getL10N('lib');
  579. header('HTTP/1.1 503 Service Temporarily Unavailable');
  580. header('Status: 503 Service Temporarily Unavailable');
  581. OC_Template::printErrorPage(
  582. $l->t('Sample configuration detected'),
  583. $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')
  584. );
  585. return;
  586. }
  587. $request = \OC::$server->getRequest();
  588. $host = $request->getInsecureServerHost();
  589. /**
  590. * if the host passed in headers isn't trusted
  591. * FIXME: Should not be in here at all :see_no_evil:
  592. */
  593. if (!OC::$CLI
  594. // overwritehost is always trusted, workaround to not have to make
  595. // \OC\AppFramework\Http\Request::getOverwriteHost public
  596. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  597. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  598. && self::$server->getConfig()->getSystemValue('installed', false)
  599. ) {
  600. header('HTTP/1.1 400 Bad Request');
  601. header('Status: 400 Bad Request');
  602. \OC::$server->getLogger()->warning(
  603. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  604. [
  605. 'app' => 'core',
  606. 'remoteAddress' => $request->getRemoteAddress(),
  607. 'host' => $host,
  608. ]
  609. );
  610. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  611. $tmpl->assign('domain', $request->server['SERVER_NAME']);
  612. $tmpl->printPage();
  613. exit();
  614. }
  615. \OC::$server->getEventLogger()->end('boot');
  616. }
  617. private static function registerLocalAddressBook() {
  618. self::$server->getContactsManager()->register(function() {
  619. $userManager = \OC::$server->getUserManager();
  620. \OC::$server->getContactsManager()->registerAddressBook(
  621. new \OC\Contacts\LocalAddressBook($userManager));
  622. });
  623. }
  624. /**
  625. * register hooks for the cache
  626. */
  627. public static function registerCacheHooks() {
  628. //don't try to do this before we are properly setup
  629. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  630. // NOTE: This will be replaced to use OCP
  631. $userSession = self::$server->getUserSession();
  632. $userSession->listen('\OC\User', 'postLogin', function () {
  633. try {
  634. $cache = new \OC\Cache\File();
  635. $cache->gc();
  636. } catch (\Exception $e) {
  637. // a GC exception should not prevent users from using OC,
  638. // so log the exception
  639. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  640. }
  641. });
  642. }
  643. }
  644. private static function registerEncryptionWrapper() {
  645. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OC\Encryption\Manager', 'setupStorage');
  646. }
  647. private static function registerEncryptionHooks() {
  648. $enabled = self::$server->getEncryptionManager()->isEnabled();
  649. if ($enabled) {
  650. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  651. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  652. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  653. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  654. }
  655. }
  656. /**
  657. * register hooks for the cache
  658. */
  659. public static function registerLogRotate() {
  660. $systemConfig = \OC::$server->getSystemConfig();
  661. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  662. //don't try to do this before we are properly setup
  663. //use custom logfile path if defined, otherwise use default of owncloud.log in data directory
  664. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
  665. }
  666. }
  667. /**
  668. * register hooks for the filesystem
  669. */
  670. public static function registerFilesystemHooks() {
  671. // Check for blacklisted files
  672. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  673. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  674. }
  675. /**
  676. * register hooks for previews
  677. */
  678. public static function registerPreviewHooks() {
  679. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  680. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  681. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  682. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  683. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  684. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
  685. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  686. OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
  687. }
  688. /**
  689. * register hooks for sharing
  690. */
  691. public static function registerShareHooks() {
  692. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  693. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
  694. OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
  695. OC_Hook::connect('OC_Group', 'pre_addToGroup', 'OC\Share\Hooks', 'pre_addToGroup');
  696. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
  697. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\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. Futhermore, 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\Setup\Controller($setupHelper);
  732. $controller->run($_POST);
  733. exit();
  734. }
  735. $request = \OC::$server->getRequest()->getPathInfo();
  736. if (substr($request, -3) !== '.js') { // we need these files during the upgrade
  737. self::checkMaintenanceMode();
  738. self::checkUpgrade();
  739. }
  740. // Always load authentication apps
  741. OC_App::loadApps(['authentication']);
  742. // Load minimum set of apps
  743. if (!self::checkUpgrade(false)
  744. && !$systemConfig->getValue('maintenance', false)) {
  745. // For logged-in users: Load everything
  746. if(OC_User::isLoggedIn()) {
  747. OC_App::loadApps();
  748. } else {
  749. // For guests: Load only filesystem and logging
  750. OC_App::loadApps(array('filesystem', 'logging'));
  751. \OC_User::tryBasicAuthLogin();
  752. }
  753. }
  754. if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
  755. try {
  756. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  757. OC_App::loadApps(array('filesystem', 'logging'));
  758. OC_App::loadApps();
  759. }
  760. self::checkSingleUserMode();
  761. OC_Util::setupFS();
  762. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  763. return;
  764. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  765. //header('HTTP/1.0 404 Not Found');
  766. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  767. OC_Response::setStatus(405);
  768. return;
  769. }
  770. }
  771. // Handle redirect URL for logged in users
  772. if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
  773. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  774. // Deny the redirect if the URL contains a @
  775. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  776. if (strpos($location, '@') === false) {
  777. header('Location: ' . $location);
  778. return;
  779. }
  780. }
  781. // Handle WebDAV
  782. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  783. // not allowed any more to prevent people
  784. // mounting this root directly.
  785. // Users need to mount remote.php/webdav instead.
  786. header('HTTP/1.1 405 Method Not Allowed');
  787. header('Status: 405 Method Not Allowed');
  788. return;
  789. }
  790. // Redirect to index if the logout link is accessed without valid session
  791. // this is needed to prevent "Token expired" messages while login if a session is expired
  792. // @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
  793. if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
  794. header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
  795. return;
  796. }
  797. // Someone is logged in
  798. if (OC_User::isLoggedIn()) {
  799. OC_App::loadApps();
  800. OC_User::setupBackends();
  801. OC_Util::setupFS();
  802. if (isset($_GET["logout"]) and ($_GET["logout"])) {
  803. OC_JSON::callCheck();
  804. if (isset($_COOKIE['oc_token'])) {
  805. \OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
  806. }
  807. OC_User::logout();
  808. // redirect to webroot and add slash if webroot is empty
  809. header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
  810. } else {
  811. // Redirect to default application
  812. OC_Util::redirectToDefaultPage();
  813. }
  814. } else {
  815. // Not handled and not logged in
  816. self::handleLogin();
  817. }
  818. }
  819. protected static function handleAuthHeaders() {
  820. //copy http auth headers for apache+php-fcgid work around
  821. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  822. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  823. }
  824. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  825. $vars = array(
  826. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  827. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  828. );
  829. foreach ($vars as $var) {
  830. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  831. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  832. $_SERVER['PHP_AUTH_USER'] = $name;
  833. $_SERVER['PHP_AUTH_PW'] = $password;
  834. break;
  835. }
  836. }
  837. }
  838. protected static function handleLogin() {
  839. OC_App::loadApps(array('prelogin'));
  840. $error = array();
  841. $messages = [];
  842. try {
  843. // auth possible via apache module?
  844. if (OC::tryApacheAuth()) {
  845. $error[] = 'apacheauthfailed';
  846. } // remember was checked after last login
  847. elseif (OC::tryRememberLogin()) {
  848. $error[] = 'invalidcookie';
  849. } // logon via web form
  850. elseif (OC::tryFormLogin()) {
  851. $error[] = 'invalidpassword';
  852. }
  853. } catch (\OC\User\LoginException $e) {
  854. $messages[] = $e->getMessage();
  855. } catch (\Exception $ex) {
  856. \OCP\Util::logException('handleLogin', $ex);
  857. // do not disclose information. show generic error
  858. $error[] = 'internalexception';
  859. }
  860. OC_Util::displayLoginPage(array_unique($error), $messages);
  861. }
  862. /**
  863. * Remove outdated and therefore invalid tokens for a user
  864. * @param string $user
  865. */
  866. protected static function cleanupLoginTokens($user) {
  867. $config = \OC::$server->getConfig();
  868. $cutoff = time() - $config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  869. $tokens = $config->getUserKeys($user, 'login_token');
  870. foreach ($tokens as $token) {
  871. $time = $config->getUserValue($user, 'login_token', $token);
  872. if ($time < $cutoff) {
  873. $config->deleteUserValue($user, 'login_token', $token);
  874. }
  875. }
  876. }
  877. /**
  878. * Try to login a user via HTTP authentication
  879. * @return bool|void
  880. */
  881. protected static function tryApacheAuth() {
  882. $return = OC_User::handleApacheAuth();
  883. // if return is true we are logged in -> redirect to the default page
  884. if ($return === true) {
  885. $_REQUEST['redirect_url'] = \OC::$server->getRequest()->getRequestUri();
  886. OC_Util::redirectToDefaultPage();
  887. exit;
  888. }
  889. // in case $return is null apache based auth is not enabled
  890. return is_null($return) ? false : true;
  891. }
  892. /**
  893. * Try to login a user using the remember me cookie.
  894. * @return bool Whether the provided cookie was valid
  895. */
  896. protected static function tryRememberLogin() {
  897. if (!isset($_COOKIE["oc_remember_login"])
  898. || !isset($_COOKIE["oc_token"])
  899. || !isset($_COOKIE["oc_username"])
  900. || !$_COOKIE["oc_remember_login"]
  901. || !OC_Util::rememberLoginAllowed()
  902. ) {
  903. return false;
  904. }
  905. if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
  906. \OCP\Util::writeLog('core', 'Trying to login from cookie', \OCP\Util::DEBUG);
  907. }
  908. if(OC_User::userExists($_COOKIE['oc_username'])) {
  909. self::cleanupLoginTokens($_COOKIE['oc_username']);
  910. // verify whether the supplied "remember me" token was valid
  911. $granted = OC_User::loginWithCookie(
  912. $_COOKIE['oc_username'], $_COOKIE['oc_token']);
  913. if($granted === true) {
  914. OC_Util::redirectToDefaultPage();
  915. // doesn't return
  916. }
  917. \OCP\Util::writeLog('core', 'Authentication cookie rejected for user ' .
  918. $_COOKIE['oc_username'], \OCP\Util::WARN);
  919. // if you reach this point you have changed your password
  920. // or you are an attacker
  921. // we can not delete tokens here because users may reach
  922. // this point multiple times after a password change
  923. }
  924. OC_User::unsetMagicInCookie();
  925. return true;
  926. }
  927. /**
  928. * Tries to login a user using the form based authentication
  929. * @return bool|void
  930. */
  931. protected static function tryFormLogin() {
  932. if (!isset($_POST["user"]) || !isset($_POST['password'])) {
  933. return false;
  934. }
  935. if(!OC_Util::isCallRegistered()) {
  936. return false;
  937. }
  938. OC_App::loadApps();
  939. //setup extra user backends
  940. OC_User::setupBackends();
  941. if (OC_User::login((string)$_POST["user"], (string)$_POST["password"])) {
  942. $userId = OC_User::getUser();
  943. // setting up the time zone
  944. if (isset($_POST['timezone-offset'])) {
  945. self::$server->getSession()->set('timezone', (string)$_POST['timezone-offset']);
  946. self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', (string)$_POST['timezone']);
  947. }
  948. self::cleanupLoginTokens($userId);
  949. if (!empty($_POST["remember_login"])) {
  950. $config = self::$server->getConfig();
  951. if ($config->getSystemValue('debug', false)) {
  952. self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
  953. }
  954. $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32);
  955. $config->setUserValue($userId, 'login_token', $token, time());
  956. OC_User::setMagicInCookie($userId, $token);
  957. } else {
  958. OC_User::unsetMagicInCookie();
  959. }
  960. OC_Util::redirectToDefaultPage();
  961. exit();
  962. }
  963. return true;
  964. }
  965. }
  966. OC::init();