base.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. require_once 'public/constants.php';
  23. /**
  24. * Class that is a namespace for all global OC variables
  25. * No, we can not put this class in its own file because it is used by
  26. * OC_autoload!
  27. */
  28. class OC {
  29. /**
  30. * Associative array for autoloading. classname => filename
  31. */
  32. public static $CLASSPATH = array();
  33. /**
  34. * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
  35. */
  36. public static $SERVERROOT = '';
  37. /**
  38. * the current request path relative to the owncloud root (e.g. files/index.php)
  39. */
  40. private static $SUBURI = '';
  41. /**
  42. * the owncloud root path for http requests (e.g. owncloud/)
  43. */
  44. public static $WEBROOT = '';
  45. /**
  46. * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
  47. */
  48. public static $THIRDPARTYROOT = '';
  49. /**
  50. * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
  51. */
  52. public static $THIRDPARTYWEBROOT = '';
  53. /**
  54. * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
  55. * web path in 'url'
  56. */
  57. public static $APPSROOTS = array();
  58. public static $configDir;
  59. /**
  60. * requested app
  61. */
  62. public static $REQUESTEDAPP = '';
  63. /**
  64. * check if ownCloud runs in cli mode
  65. */
  66. public static $CLI = false;
  67. /**
  68. * @var \OC\Autoloader $loader
  69. */
  70. public static $loader = null;
  71. /**
  72. * @var \OC\Server
  73. */
  74. public static $server = null;
  75. public static function initPaths() {
  76. // calculate the root directories
  77. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  78. // ensure we can find OC_Config
  79. set_include_path(
  80. OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
  81. get_include_path()
  82. );
  83. if(defined('PHPUNIT_CONFIG_DIR')) {
  84. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  85. } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  86. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  87. } else {
  88. self::$configDir = OC::$SERVERROOT . '/config/';
  89. }
  90. OC_Config::$object = new \OC\Config(self::$configDir);
  91. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  92. $scriptName = OC_Request::scriptName();
  93. if (substr($scriptName, -1) == '/') {
  94. $scriptName .= 'index.php';
  95. //make sure suburi follows the same rules as scriptName
  96. if (substr(OC::$SUBURI, -9) != 'index.php') {
  97. if (substr(OC::$SUBURI, -1) != '/') {
  98. OC::$SUBURI = OC::$SUBURI . '/';
  99. }
  100. OC::$SUBURI = OC::$SUBURI . 'index.php';
  101. }
  102. }
  103. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  104. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  105. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  106. OC::$WEBROOT = '/' . OC::$WEBROOT;
  107. }
  108. } else {
  109. // The scriptName is not ending with OC::$SUBURI
  110. // This most likely means that we are calling from CLI.
  111. // However some cron jobs still need to generate
  112. // a web URL, so we use overwritewebroot as a fallback.
  113. OC::$WEBROOT = OC_Config::getValue('overwritewebroot', '');
  114. }
  115. // search the 3rdparty folder
  116. OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', null);
  117. OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', null);
  118. if (empty(OC::$THIRDPARTYROOT) && empty(OC::$THIRDPARTYWEBROOT)) {
  119. if (file_exists(OC::$SERVERROOT . '/3rdparty')) {
  120. OC::$THIRDPARTYROOT = OC::$SERVERROOT;
  121. OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
  122. } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
  123. OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
  124. OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
  125. }
  126. }
  127. if (empty(OC::$THIRDPARTYROOT) || !file_exists(OC::$THIRDPARTYROOT)) {
  128. echo('3rdparty directory not found! Please put the ownCloud 3rdparty'
  129. . ' folder in the ownCloud folder or the folder above.'
  130. . ' You can also configure the location in the config.php file.');
  131. return;
  132. }
  133. // search the apps folder
  134. $config_paths = OC_Config::getValue('apps_paths', array());
  135. if (!empty($config_paths)) {
  136. foreach ($config_paths as $paths) {
  137. if (isset($paths['url']) && isset($paths['path'])) {
  138. $paths['url'] = rtrim($paths['url'], '/');
  139. $paths['path'] = rtrim($paths['path'], '/');
  140. OC::$APPSROOTS[] = $paths;
  141. }
  142. }
  143. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  144. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  145. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  146. OC::$APPSROOTS[] = array(
  147. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  148. 'url' => '/apps',
  149. 'writable' => true
  150. );
  151. }
  152. if (empty(OC::$APPSROOTS)) {
  153. throw new Exception('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
  154. . ' or the folder above. You can also configure the location in the config.php file.');
  155. }
  156. $paths = array();
  157. foreach (OC::$APPSROOTS as $path) {
  158. $paths[] = $path['path'];
  159. }
  160. // set the right include path
  161. set_include_path(
  162. OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
  163. OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
  164. OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
  165. implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
  166. get_include_path() . PATH_SEPARATOR .
  167. OC::$SERVERROOT
  168. );
  169. }
  170. public static function checkConfig() {
  171. $l = \OC::$server->getL10N('lib');
  172. // Create config in case it does not already exists
  173. $configFilePath = self::$configDir .'/config.php';
  174. if(!file_exists($configFilePath)) {
  175. @touch($configFilePath);
  176. }
  177. // Check if config is writable
  178. $configFileWritable = is_writable($configFilePath);
  179. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  180. || !$configFileWritable && \OCP\Util::needUpgrade()) {
  181. if (self::$CLI) {
  182. echo $l->t('Cannot write into "config" directory!')."\n";
  183. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  184. echo "\n";
  185. echo $l->t('See %s', array(\OC_Helper::linkToDocs('admin-dir_permissions')))."\n";
  186. exit;
  187. } else {
  188. OC_Template::printErrorPage(
  189. $l->t('Cannot write into "config" directory!'),
  190. $l->t('This can usually be fixed by '
  191. . '%sgiving the webserver write access to the config directory%s.',
  192. array('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>'))
  193. );
  194. }
  195. }
  196. }
  197. public static function checkInstalled() {
  198. // Redirect to installer if not installed
  199. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
  200. if (OC::$CLI) {
  201. throw new Exception('Not installed');
  202. } else {
  203. $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
  204. header('Location: ' . $url);
  205. }
  206. exit();
  207. }
  208. }
  209. public static function checkSSL() {
  210. // redirect to https site if configured
  211. if (\OC::$server->getSystemConfig()->getValue('forcessl', false)) {
  212. // Default HSTS policy
  213. $header = 'Strict-Transport-Security: max-age=31536000';
  214. // If SSL for subdomains is enabled add "; includeSubDomains" to the header
  215. if(\OC::$server->getSystemConfig()->getValue('forceSSLforSubdomains', false)) {
  216. $header .= '; includeSubDomains';
  217. }
  218. header($header);
  219. ini_set('session.cookie_secure', 'on');
  220. if (OC_Request::serverProtocol() <> 'https' and !OC::$CLI) {
  221. $url = 'https://' . OC_Request::serverHost() . OC_Request::requestUri();
  222. header("Location: $url");
  223. exit();
  224. }
  225. } else {
  226. // Invalidate HSTS headers
  227. if (OC_Request::serverProtocol() === 'https') {
  228. header('Strict-Transport-Security: max-age=0');
  229. }
  230. }
  231. }
  232. public static function checkMaintenanceMode() {
  233. // Allow ajax update script to execute without being stopped
  234. if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  235. // send http status 503
  236. header('HTTP/1.1 503 Service Temporarily Unavailable');
  237. header('Status: 503 Service Temporarily Unavailable');
  238. header('Retry-After: 120');
  239. // render error page
  240. $tmpl = new OC_Template('', 'update.user', 'guest');
  241. OC_Util::addscript('maintenance-check');
  242. $tmpl->printPage();
  243. die();
  244. }
  245. }
  246. public static function checkSingleUserMode() {
  247. $user = OC_User::getUserSession()->getUser();
  248. $group = OC_Group::getManager()->get('admin');
  249. if ($user && \OC::$server->getSystemConfig()->getValue('singleuser', false) && !$group->inGroup($user)) {
  250. // send http status 503
  251. header('HTTP/1.1 503 Service Temporarily Unavailable');
  252. header('Status: 503 Service Temporarily Unavailable');
  253. header('Retry-After: 120');
  254. // render error page
  255. $tmpl = new OC_Template('', 'singleuser.user', 'guest');
  256. $tmpl->printPage();
  257. die();
  258. }
  259. }
  260. /**
  261. * check if the instance needs to preform an upgrade
  262. *
  263. * @return bool
  264. * @deprecated use \OCP\Util::needUpgrade() instead
  265. */
  266. public static function needUpgrade() {
  267. return \OCP\Util::needUpgrade();
  268. }
  269. /**
  270. * Checks if the version requires an update and shows
  271. * @param bool $showTemplate Whether an update screen should get shown
  272. * @return bool|void
  273. */
  274. public static function checkUpgrade($showTemplate = true) {
  275. if (\OCP\Util::needUpgrade()) {
  276. $systemConfig = \OC::$server->getSystemConfig();
  277. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  278. $version = OC_Util::getVersion();
  279. $oldTheme = $systemConfig->getValue('theme');
  280. $systemConfig->setValue('theme', '');
  281. OC_Util::addScript('config'); // needed for web root
  282. OC_Util::addScript('update');
  283. $tmpl = new OC_Template('', 'update.admin', 'guest');
  284. $tmpl->assign('version', OC_Util::getVersionString());
  285. // get third party apps
  286. $apps = OC_App::getEnabledApps();
  287. $incompatibleApps = array();
  288. foreach ($apps as $appId) {
  289. $info = OC_App::getAppInfo($appId);
  290. if(!OC_App::isAppCompatible($version, $info)) {
  291. $incompatibleApps[] = $info;
  292. }
  293. }
  294. $tmpl->assign('appList', $incompatibleApps);
  295. $tmpl->assign('productName', 'ownCloud'); // for now
  296. $tmpl->assign('oldTheme', $oldTheme);
  297. $tmpl->printPage();
  298. exit();
  299. } else {
  300. return true;
  301. }
  302. }
  303. return false;
  304. }
  305. public static function initTemplateEngine() {
  306. // Add the stuff we need always
  307. // following logic will import all vendor libraries that are
  308. // specified in core/js/core.json
  309. $fileContent = file_get_contents(OC::$SERVERROOT . '/core/js/core.json');
  310. if($fileContent !== false) {
  311. $coreDependencies = json_decode($fileContent, true);
  312. foreach($coreDependencies['vendor'] as $vendorLibrary) {
  313. // remove trailing ".js" as addVendorScript will append it
  314. OC_Util::addVendorScript(
  315. substr($vendorLibrary, 0, strlen($vendorLibrary) - 3));
  316. }
  317. } else {
  318. throw new \Exception('Cannot read core/js/core.json');
  319. }
  320. OC_Util::addScript("placeholders");
  321. OC_Util::addScript("jquery-tipsy");
  322. OC_Util::addScript("compatibility");
  323. OC_Util::addScript("jquery.ocdialog");
  324. OC_Util::addScript("oc-dialogs");
  325. OC_Util::addScript("js");
  326. OC_Util::addScript("l10n");
  327. OC_Util::addTranslations("core");
  328. OC_Util::addScript("octemplate");
  329. OC_Util::addScript("eventsource");
  330. OC_Util::addScript("config");
  331. //OC_Util::addScript( "multiselect" );
  332. OC_Util::addScript('search', 'search');
  333. OC_Util::addScript("oc-requesttoken");
  334. OC_Util::addScript("apps");
  335. OC_Util::addVendorScript('snapjs/dist/latest/snap');
  336. // avatars
  337. if (\OC::$server->getSystemConfig()->getValue('enable_avatars', true) === true) {
  338. \OC_Util::addScript('placeholder');
  339. \OC_Util::addVendorScript('blueimp-md5/js/md5');
  340. \OC_Util::addScript('jquery.avatar');
  341. \OC_Util::addScript('avatar');
  342. }
  343. OC_Util::addStyle("styles");
  344. OC_Util::addStyle("header");
  345. OC_Util::addStyle("mobile");
  346. OC_Util::addStyle("icons");
  347. OC_Util::addStyle("fonts");
  348. OC_Util::addStyle("apps");
  349. OC_Util::addStyle("fixes");
  350. OC_Util::addStyle("multiselect");
  351. OC_Util::addVendorStyle('jquery-ui/themes/base/jquery-ui');
  352. OC_Util::addStyle('jquery-ui-fixes');
  353. OC_Util::addStyle("jquery-tipsy");
  354. OC_Util::addStyle("jquery.ocdialog");
  355. }
  356. public static function initSession() {
  357. // prevents javascript from accessing php session cookies
  358. ini_set('session.cookie_httponly', '1;');
  359. // set the cookie path to the ownCloud directory
  360. $cookie_path = OC::$WEBROOT ? : '/';
  361. ini_set('session.cookie_path', $cookie_path);
  362. // Let the session name be changed in the initSession Hook
  363. $sessionName = OC_Util::getInstanceId();
  364. try {
  365. // Allow session apps to create a custom session object
  366. $useCustomSession = false;
  367. $session = self::$server->getSession();
  368. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  369. if($useCustomSession) {
  370. // use the session reference as the new Session
  371. self::$server->setSession($session);
  372. } else {
  373. // set the session name to the instance id - which is unique
  374. self::$server->setSession(new \OC\Session\Internal($sessionName));
  375. }
  376. // if session cant be started break with http 500 error
  377. } catch (Exception $e) {
  378. //show the user a detailed error page
  379. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  380. OC_Template::printExceptionErrorPage($e);
  381. }
  382. $sessionLifeTime = self::getSessionLifeTime();
  383. // regenerate session id periodically to avoid session fixation
  384. /**
  385. * @var \OCP\ISession $session
  386. */
  387. $session = self::$server->getSession();
  388. if (!$session->exists('SID_CREATED')) {
  389. $session->set('SID_CREATED', time());
  390. } else if (time() - $session->get('SID_CREATED') > $sessionLifeTime / 2) {
  391. session_regenerate_id(true);
  392. $session->set('SID_CREATED', time());
  393. }
  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(), '', time() - 42000, $cookie_path);
  398. }
  399. session_unset();
  400. session_destroy();
  401. session_start();
  402. }
  403. $session->set('LAST_ACTIVITY', time());
  404. }
  405. /**
  406. * @return string
  407. */
  408. private static function getSessionLifeTime() {
  409. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  410. }
  411. public static function loadAppClassPaths() {
  412. foreach (OC_APP::getEnabledApps() as $app) {
  413. $file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
  414. if (file_exists($file)) {
  415. require_once $file;
  416. }
  417. }
  418. }
  419. public static function init() {
  420. // register autoloader
  421. $loaderStart = microtime(true);
  422. require_once __DIR__ . '/autoloader.php';
  423. self::$loader = new \OC\Autoloader();
  424. spl_autoload_register(array(self::$loader, 'load'));
  425. $loaderEnd = microtime(true);
  426. self::initPaths();
  427. // setup 3rdparty autoloader
  428. $vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php';
  429. if (file_exists($vendorAutoLoad)) {
  430. require_once $vendorAutoLoad;
  431. } else {
  432. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  433. OC_Template::printErrorPage('Composer autoloader not found, unable to continue.');
  434. }
  435. // setup the basic server
  436. self::$server = new \OC\Server(\OC::$WEBROOT);
  437. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  438. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  439. // set some stuff
  440. //ob_start();
  441. error_reporting(E_ALL | E_STRICT);
  442. if (defined('DEBUG') && DEBUG) {
  443. ini_set('display_errors', 1);
  444. }
  445. self::$CLI = (php_sapi_name() == 'cli');
  446. date_default_timezone_set('UTC');
  447. ini_set('arg_separator.output', '&amp;');
  448. //try to configure php to enable big file uploads.
  449. //this doesn´t work always depending on the webserver and php configuration.
  450. //Let´s try to overwrite some defaults anyways
  451. //try to set the maximum execution time to 60min
  452. @set_time_limit(3600);
  453. @ini_set('max_execution_time', 3600);
  454. @ini_set('max_input_time', 3600);
  455. //try to set the maximum filesize to 10G
  456. @ini_set('upload_max_filesize', '10G');
  457. @ini_set('post_max_size', '10G');
  458. @ini_set('file_uploads', '50');
  459. self::handleAuthHeaders();
  460. self::registerAutoloaderCache();
  461. // initialize intl fallback is necessary
  462. \Patchwork\Utf8\Bootup::initIntl();
  463. OC_Util::isSetLocaleWorking();
  464. if (!defined('PHPUNIT_RUN')) {
  465. OC\Log\ErrorHandler::setLogger(OC_Log::$object);
  466. if (defined('DEBUG') and DEBUG) {
  467. OC\Log\ErrorHandler::register(true);
  468. set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
  469. } else {
  470. OC\Log\ErrorHandler::register();
  471. }
  472. }
  473. // register the stream wrappers
  474. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  475. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  476. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  477. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  478. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  479. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  480. OC_App::loadApps(array('session'));
  481. if (!self::$CLI) {
  482. self::initSession();
  483. }
  484. \OC::$server->getEventLogger()->end('init_session');
  485. self::initTemplateEngine();
  486. self::checkConfig();
  487. self::checkInstalled();
  488. self::checkSSL();
  489. OC_Response::addSecurityHeaders();
  490. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  491. if (count($errors) > 0) {
  492. if (self::$CLI) {
  493. foreach ($errors as $error) {
  494. echo $error['error'] . "\n";
  495. echo $error['hint'] . "\n\n";
  496. }
  497. } else {
  498. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  499. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  500. }
  501. exit;
  502. }
  503. //try to set the session lifetime
  504. $sessionLifeTime = self::getSessionLifeTime();
  505. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  506. $systemConfig = \OC::$server->getSystemConfig();
  507. // User and Groups
  508. if (!$systemConfig->getValue("installed", false)) {
  509. self::$server->getSession()->set('user_id', '');
  510. }
  511. OC_User::useBackend(new OC_User_Database());
  512. OC_Group::useBackend(new OC_Group_Database());
  513. //setup extra user backends
  514. if (!self::checkUpgrade(false)) {
  515. OC_User::setupBackends();
  516. }
  517. self::registerCacheHooks();
  518. self::registerFilesystemHooks();
  519. self::registerPreviewHooks();
  520. self::registerShareHooks();
  521. self::registerLogRotate();
  522. self::registerLocalAddressBook();
  523. //make sure temporary files are cleaned up
  524. $tmpManager = \OC::$server->getTempManager();
  525. register_shutdown_function(array($tmpManager, 'clean'));
  526. if ($systemConfig->getValue('installed', false) && !self::checkUpgrade(false)) {
  527. if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
  528. OC_Util::addScript('backgroundjobs');
  529. }
  530. }
  531. // Check whether the sample configuration has been copied
  532. if($systemConfig->getValue('copied_sample_config', false)) {
  533. $l = \OC::$server->getL10N('lib');
  534. header('HTTP/1.1 503 Service Temporarily Unavailable');
  535. header('Status: 503 Service Temporarily Unavailable');
  536. OC_Template::printErrorPage(
  537. $l->t('Sample configuration detected'),
  538. $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')
  539. );
  540. return;
  541. }
  542. $host = OC_Request::insecureServerHost();
  543. // if the host passed in headers isn't trusted
  544. if (!OC::$CLI
  545. // overwritehost is always trusted
  546. && OC_Request::getOverwriteHost() === null
  547. && !OC_Request::isTrustedDomain($host)
  548. ) {
  549. header('HTTP/1.1 400 Bad Request');
  550. header('Status: 400 Bad Request');
  551. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  552. $tmpl->assign('domain', $_SERVER['SERVER_NAME']);
  553. $tmpl->printPage();
  554. exit();
  555. }
  556. \OC::$server->getEventLogger()->end('boot');
  557. }
  558. private static function registerLocalAddressBook() {
  559. self::$server->getContactsManager()->register(function() {
  560. $userManager = \OC::$server->getUserManager();
  561. \OC::$server->getContactsManager()->registerAddressBook(
  562. new \OC\Contacts\LocalAddressBook($userManager));
  563. });
  564. }
  565. /**
  566. * register hooks for the cache
  567. */
  568. public static function registerCacheHooks() {
  569. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) { //don't try to do this before we are properly setup
  570. \OCP\BackgroundJob::registerJob('OC\Cache\FileGlobalGC');
  571. // NOTE: This will be replaced to use OCP
  572. $userSession = \OC_User::getUserSession();
  573. $userSession->listen('postLogin', '\OC\Cache\File', 'loginListener');
  574. }
  575. }
  576. /**
  577. * register hooks for the cache
  578. */
  579. public static function registerLogRotate() {
  580. $systemConfig = \OC::$server->getSystemConfig();
  581. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !\OCP\Util::needUpgrade()) {
  582. //don't try to do this before we are properly setup
  583. //use custom logfile path if defined, otherwise use default of owncloud.log in data directory
  584. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log'));
  585. }
  586. }
  587. /**
  588. * register hooks for the filesystem
  589. */
  590. public static function registerFilesystemHooks() {
  591. // Check for blacklisted files
  592. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  593. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  594. }
  595. /**
  596. * register hooks for previews
  597. */
  598. public static function registerPreviewHooks() {
  599. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  600. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  601. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  602. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  603. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  604. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete');
  605. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  606. }
  607. /**
  608. * register hooks for sharing
  609. */
  610. public static function registerShareHooks() {
  611. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  612. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share\Hooks', 'post_deleteUser');
  613. OC_Hook::connect('OC_User', 'post_addToGroup', 'OC\Share\Hooks', 'post_addToGroup');
  614. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share\Hooks', 'post_removeFromGroup');
  615. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share\Hooks', 'post_deleteGroup');
  616. }
  617. }
  618. protected static function registerAutoloaderCache() {
  619. // The class loader takes an optional low-latency cache, which MUST be
  620. // namespaced. The instanceid is used for namespacing, but might be
  621. // unavailable at this point. Futhermore, it might not be possible to
  622. // generate an instanceid via \OC_Util::getInstanceId() because the
  623. // config file may not be writable. As such, we only register a class
  624. // loader cache if instanceid is available without trying to create one.
  625. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  626. if ($instanceId) {
  627. try {
  628. $memcacheFactory = new \OC\Memcache\Factory($instanceId);
  629. self::$loader->setMemoryCache($memcacheFactory->createLowLatency('Autoloader'));
  630. } catch (\Exception $ex) {
  631. }
  632. }
  633. }
  634. /**
  635. * Handle the request
  636. */
  637. public static function handleRequest() {
  638. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  639. $systemConfig = \OC::$server->getSystemConfig();
  640. // load all the classpaths from the enabled apps so they are available
  641. // in the routing files of each app
  642. OC::loadAppClassPaths();
  643. // Check if ownCloud is installed or in maintenance (update) mode
  644. if (!$systemConfig->getValue('installed', false)) {
  645. \OC::$server->getSession()->clear();
  646. $controller = new OC\Core\Setup\Controller(\OC::$server->getConfig(), \OC::$server->getIniWrapper(), \OC::$server->getL10N('core'), new \OC_Defaults());
  647. $controller->run($_POST);
  648. exit();
  649. }
  650. $request = OC_Request::getPathInfo();
  651. if (substr($request, -3) !== '.js') { // we need these files during the upgrade
  652. self::checkMaintenanceMode();
  653. self::checkUpgrade();
  654. }
  655. // Load minimum set of apps
  656. if (!self::checkUpgrade(false)
  657. && !$systemConfig->getValue('maintenance', false)
  658. && !\OCP\Util::needUpgrade()) {
  659. // For logged-in users: Load everything
  660. if(OC_User::isLoggedIn()) {
  661. OC_App::loadApps();
  662. } else {
  663. // For guests: Load only authentication, filesystem and logging
  664. OC_App::loadApps(array('authentication'));
  665. OC_App::loadApps(array('filesystem', 'logging'));
  666. \OC_User::tryBasicAuthLogin();
  667. }
  668. }
  669. if (!self::$CLI and (!isset($_GET["logout"]) or ($_GET["logout"] !== 'true'))) {
  670. try {
  671. if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
  672. OC_App::loadApps(array('authentication'));
  673. OC_App::loadApps(array('filesystem', 'logging'));
  674. OC_App::loadApps();
  675. }
  676. self::checkSingleUserMode();
  677. OC_Util::setupFS();
  678. OC::$server->getRouter()->match(OC_Request::getRawPathInfo());
  679. return;
  680. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  681. //header('HTTP/1.0 404 Not Found');
  682. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  683. OC_Response::setStatus(405);
  684. return;
  685. }
  686. }
  687. // Handle redirect URL for logged in users
  688. if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
  689. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  690. // Deny the redirect if the URL contains a @
  691. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  692. if (strpos($location, '@') === false) {
  693. header('Location: ' . $location);
  694. return;
  695. }
  696. }
  697. // Handle WebDAV
  698. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  699. // not allowed any more to prevent people
  700. // mounting this root directly.
  701. // Users need to mount remote.php/webdav instead.
  702. header('HTTP/1.1 405 Method Not Allowed');
  703. header('Status: 405 Method Not Allowed');
  704. return;
  705. }
  706. // Redirect to index if the logout link is accessed without valid session
  707. // this is needed to prevent "Token expired" messages while login if a session is expired
  708. // @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583
  709. if(isset($_GET['logout']) && !OC_User::isLoggedIn()) {
  710. header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
  711. return;
  712. }
  713. // Someone is logged in
  714. if (OC_User::isLoggedIn()) {
  715. OC_App::loadApps();
  716. OC_User::setupBackends();
  717. OC_Util::setupFS();
  718. if (isset($_GET["logout"]) and ($_GET["logout"])) {
  719. OC_JSON::callCheck();
  720. if (isset($_COOKIE['oc_token'])) {
  721. \OC::$server->getConfig()->deleteUserValue(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
  722. }
  723. OC_User::logout();
  724. // redirect to webroot and add slash if webroot is empty
  725. header("Location: " . OC::$WEBROOT.(empty(OC::$WEBROOT) ? '/' : ''));
  726. } else {
  727. // Redirect to default application
  728. OC_Util::redirectToDefaultPage();
  729. }
  730. } else {
  731. // Not handled and not logged in
  732. self::handleLogin();
  733. }
  734. }
  735. protected static function handleAuthHeaders() {
  736. //copy http auth headers for apache+php-fcgid work around
  737. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  738. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  739. }
  740. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  741. $vars = array(
  742. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  743. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  744. );
  745. foreach ($vars as $var) {
  746. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  747. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  748. $_SERVER['PHP_AUTH_USER'] = $name;
  749. $_SERVER['PHP_AUTH_PW'] = $password;
  750. break;
  751. }
  752. }
  753. }
  754. protected static function handleLogin() {
  755. OC_App::loadApps(array('prelogin'));
  756. $error = array();
  757. $messages = [];
  758. try {
  759. // auth possible via apache module?
  760. if (OC::tryApacheAuth()) {
  761. $error[] = 'apacheauthfailed';
  762. } // remember was checked after last login
  763. elseif (OC::tryRememberLogin()) {
  764. $error[] = 'invalidcookie';
  765. } // logon via web form
  766. elseif (OC::tryFormLogin()) {
  767. $error[] = 'invalidpassword';
  768. }
  769. } catch (\OC\User\LoginException $e) {
  770. $messages[] = $e->getMessage();
  771. }
  772. OC_Util::displayLoginPage(array_unique($error), $messages);
  773. }
  774. /**
  775. * Remove outdated and therefore invalid tokens for a user
  776. * @param string $user
  777. */
  778. protected static function cleanupLoginTokens($user) {
  779. $config = \OC::$server->getConfig();
  780. $cutoff = time() - $config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  781. $tokens = $config->getUserKeys($user, 'login_token');
  782. foreach ($tokens as $token) {
  783. $time = $config->getUserValue($user, 'login_token', $token);
  784. if ($time < $cutoff) {
  785. $config->deleteUserValue($user, 'login_token', $token);
  786. }
  787. }
  788. }
  789. /**
  790. * Try to login a user via HTTP authentication
  791. * @return bool|void
  792. */
  793. protected static function tryApacheAuth() {
  794. $return = OC_User::handleApacheAuth();
  795. // if return is true we are logged in -> redirect to the default page
  796. if ($return === true) {
  797. $_REQUEST['redirect_url'] = \OC_Request::requestUri();
  798. OC_Util::redirectToDefaultPage();
  799. exit;
  800. }
  801. // in case $return is null apache based auth is not enabled
  802. return is_null($return) ? false : true;
  803. }
  804. /**
  805. * Try to login a user using the remember me cookie.
  806. * @return bool Whether the provided cookie was valid
  807. */
  808. protected static function tryRememberLogin() {
  809. if (!isset($_COOKIE["oc_remember_login"])
  810. || !isset($_COOKIE["oc_token"])
  811. || !isset($_COOKIE["oc_username"])
  812. || !$_COOKIE["oc_remember_login"]
  813. || !OC_Util::rememberLoginAllowed()
  814. ) {
  815. return false;
  816. }
  817. if (defined("DEBUG") && DEBUG) {
  818. OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
  819. }
  820. if(OC_User::userExists($_COOKIE['oc_username'])) {
  821. self::cleanupLoginTokens($_COOKIE['oc_username']);
  822. // verify whether the supplied "remember me" token was valid
  823. $granted = OC_User::loginWithCookie(
  824. $_COOKIE['oc_username'], $_COOKIE['oc_token']);
  825. if($granted === true) {
  826. OC_Util::redirectToDefaultPage();
  827. // doesn't return
  828. }
  829. OC_Log::write('core', 'Authentication cookie rejected for user ' .
  830. $_COOKIE['oc_username'], OC_Log::WARN);
  831. // if you reach this point you have changed your password
  832. // or you are an attacker
  833. // we can not delete tokens here because users may reach
  834. // this point multiple times after a password change
  835. }
  836. OC_User::unsetMagicInCookie();
  837. return true;
  838. }
  839. /**
  840. * Tries to login a user using the form based authentication
  841. * @return bool|void
  842. */
  843. protected static function tryFormLogin() {
  844. if (!isset($_POST["user"]) || !isset($_POST['password'])) {
  845. return false;
  846. }
  847. if(!OC_Util::isCallRegistered()) {
  848. return false;
  849. }
  850. OC_App::loadApps();
  851. //setup extra user backends
  852. OC_User::setupBackends();
  853. if (OC_User::login($_POST["user"], $_POST["password"])) {
  854. $userId = OC_User::getUser();
  855. // setting up the time zone
  856. if (isset($_POST['timezone-offset'])) {
  857. self::$server->getSession()->set('timezone', $_POST['timezone-offset']);
  858. self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', $_POST['timezone']);
  859. }
  860. self::cleanupLoginTokens($userId);
  861. if (!empty($_POST["remember_login"])) {
  862. if (defined("DEBUG") && DEBUG) {
  863. self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
  864. }
  865. $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32);
  866. self::$server->getConfig()->setUserValue($userId, 'login_token', $token, time());
  867. OC_User::setMagicInCookie($userId, $token);
  868. } else {
  869. OC_User::unsetMagicInCookie();
  870. }
  871. OC_Util::redirectToDefaultPage();
  872. exit();
  873. }
  874. return true;
  875. }
  876. }
  877. if (!function_exists('get_temp_dir')) {
  878. /**
  879. * Get the temporary dir to store uploaded data
  880. * @return null|string Path to the temporary directory or null
  881. */
  882. function get_temp_dir() {
  883. if ($temp = ini_get('upload_tmp_dir')) return $temp;
  884. if ($temp = getenv('TMP')) return $temp;
  885. if ($temp = getenv('TEMP')) return $temp;
  886. if ($temp = getenv('TMPDIR')) return $temp;
  887. $temp = tempnam(__FILE__, '');
  888. if (file_exists($temp)) {
  889. unlink($temp);
  890. return dirname($temp);
  891. }
  892. if ($temp = sys_get_temp_dir()) return $temp;
  893. return null;
  894. }
  895. }
  896. OC::init();