base.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. /*
  59. * requested app
  60. */
  61. public static $REQUESTEDAPP = '';
  62. /*
  63. * requested file of app
  64. */
  65. public static $REQUESTEDFILE = '';
  66. /**
  67. * check if owncloud runs in cli mode
  68. */
  69. public static $CLI = false;
  70. /*
  71. * OC router
  72. */
  73. protected static $router = null;
  74. /**
  75. * @var \OC\Session\Session
  76. */
  77. public static $session = null;
  78. /**
  79. * @var \OC\Autoloader $loader
  80. */
  81. public static $loader = null;
  82. public static function initPaths() {
  83. // calculate the root directories
  84. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  85. // ensure we can find OC_Config
  86. set_include_path(
  87. OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
  88. get_include_path()
  89. );
  90. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  91. $scriptName = OC_Request::scriptName();
  92. if (substr($scriptName, -1) == '/') {
  93. $scriptName .= 'index.php';
  94. //make sure suburi follows the same rules as scriptName
  95. if (substr(OC::$SUBURI, -9) != 'index.php') {
  96. if (substr(OC::$SUBURI, -1) != '/') {
  97. OC::$SUBURI = OC::$SUBURI . '/';
  98. }
  99. OC::$SUBURI = OC::$SUBURI . 'index.php';
  100. }
  101. }
  102. OC::$WEBROOT = substr($scriptName, 0, strlen($scriptName) - strlen(OC::$SUBURI));
  103. if (OC::$WEBROOT != '' and OC::$WEBROOT[0] !== '/') {
  104. OC::$WEBROOT = '/' . OC::$WEBROOT;
  105. }
  106. // search the 3rdparty folder
  107. if (OC_Config::getValue('3rdpartyroot', '') <> '' and OC_Config::getValue('3rdpartyurl', '') <> '') {
  108. OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', '');
  109. OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', '');
  110. } elseif (file_exists(OC::$SERVERROOT . '/3rdparty')) {
  111. OC::$THIRDPARTYROOT = OC::$SERVERROOT;
  112. OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
  113. } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
  114. OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
  115. OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
  116. } else {
  117. throw new Exception('3rdparty directory not found! Please put the ownCloud 3rdparty'
  118. .' folder in the ownCloud folder or the folder above.'
  119. .' You can also configure the location in the config.php file.');
  120. }
  121. // search the apps folder
  122. $config_paths = OC_Config::getValue('apps_paths', array());
  123. if (!empty($config_paths)) {
  124. foreach ($config_paths as $paths) {
  125. if (isset($paths['url']) && isset($paths['path'])) {
  126. $paths['url'] = rtrim($paths['url'], '/');
  127. $paths['path'] = rtrim($paths['path'], '/');
  128. OC::$APPSROOTS[] = $paths;
  129. }
  130. }
  131. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  132. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  133. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  134. OC::$APPSROOTS[] = array(
  135. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  136. 'url' => '/apps',
  137. 'writable' => true
  138. );
  139. }
  140. if (empty(OC::$APPSROOTS)) {
  141. throw new Exception('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
  142. .' or the folder above. You can also configure the location in the config.php file.');
  143. }
  144. $paths = array();
  145. foreach (OC::$APPSROOTS as $path) {
  146. $paths[] = $path['path'];
  147. }
  148. // set the right include path
  149. set_include_path(
  150. OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
  151. OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
  152. OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
  153. implode($paths, PATH_SEPARATOR) . PATH_SEPARATOR .
  154. get_include_path() . PATH_SEPARATOR .
  155. OC::$SERVERROOT
  156. );
  157. }
  158. public static function checkConfig() {
  159. if (file_exists(OC::$SERVERROOT . "/config/config.php")
  160. and !is_writable(OC::$SERVERROOT . "/config/config.php")) {
  161. $defaults = new OC_Defaults();
  162. OC_Template::printErrorPage(
  163. "Can't write into config directory!",
  164. 'This can usually be fixed by '
  165. .'<a href="' . $defaults->getDocBaseUrl() . '/server/5.0/admin_manual/installation/installation_source.html#set-the-directory-permissions" target="_blank">giving the webserver write access to the config directory</a>.'
  166. );
  167. }
  168. }
  169. public static function checkInstalled() {
  170. // Redirect to installer if not installed
  171. if (!OC_Config::getValue('installed', false) && OC::$SUBURI != '/index.php') {
  172. if (!OC::$CLI) {
  173. $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
  174. header("Location: $url");
  175. }
  176. exit();
  177. }
  178. }
  179. public static function checkSSL() {
  180. // redirect to https site if configured
  181. if (OC_Config::getValue("forcessl", false)) {
  182. header('Strict-Transport-Security: max-age=31536000');
  183. ini_set("session.cookie_secure", "on");
  184. if (OC_Request::serverProtocol() <> 'https' and !OC::$CLI) {
  185. $url = "https://" . OC_Request::serverHost() . OC_Request::requestUri();
  186. header("Location: $url");
  187. exit();
  188. }
  189. } else {
  190. // Invalidate HSTS headers
  191. if (OC_Request::serverProtocol() === 'https') {
  192. header('Strict-Transport-Security: max-age=0');
  193. }
  194. }
  195. }
  196. public static function checkMaintenanceMode() {
  197. // Allow ajax update script to execute without being stopped
  198. if (OC_Config::getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  199. // send http status 503
  200. header('HTTP/1.1 503 Service Temporarily Unavailable');
  201. header('Status: 503 Service Temporarily Unavailable');
  202. header('Retry-After: 120');
  203. // render error page
  204. OC_Template::printErrorPage('ownCloud is in maintenance mode');
  205. }
  206. }
  207. public static function checkUpgrade($showTemplate = true) {
  208. if (OC_Config::getValue('installed', false)) {
  209. $installedVersion = OC_Config::getValue('version', '0.0.0');
  210. $currentVersion = implode('.', OC_Util::getVersion());
  211. if (version_compare($currentVersion, $installedVersion, '>')) {
  212. if ($showTemplate && !OC_Config::getValue('maintenance', false)) {
  213. OC_Config::setValue('theme', '');
  214. $minimizerCSS = new OC_Minimizer_CSS();
  215. $minimizerCSS->clearCache();
  216. $minimizerJS = new OC_Minimizer_JS();
  217. $minimizerJS->clearCache();
  218. OC_Util::addscript('update');
  219. $tmpl = new OC_Template('', 'update', 'guest');
  220. $tmpl->assign('version', OC_Util::getVersionString());
  221. $tmpl->printPage();
  222. exit();
  223. } else {
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. }
  230. public static function initTemplateEngine() {
  231. // Add the stuff we need always
  232. OC_Util::addScript("jquery-1.10.0.min");
  233. OC_Util::addScript("jquery-migrate-1.2.1.min");
  234. OC_Util::addScript("jquery-ui-1.10.0.custom");
  235. OC_Util::addScript("jquery-showpassword");
  236. OC_Util::addScript("jquery.infieldlabel");
  237. OC_Util::addScript("jquery-tipsy");
  238. OC_Util::addScript("compatibility");
  239. OC_Util::addScript("jquery.ocdialog");
  240. OC_Util::addScript("oc-dialogs");
  241. OC_Util::addScript("octemplate");
  242. OC_Util::addScript("js");
  243. OC_Util::addScript("eventsource");
  244. OC_Util::addScript("config");
  245. //OC_Util::addScript( "multiselect" );
  246. OC_Util::addScript('search', 'result');
  247. OC_Util::addScript('router');
  248. OC_Util::addStyle("styles");
  249. OC_Util::addStyle("multiselect");
  250. OC_Util::addStyle("jquery-ui-1.10.0.custom");
  251. OC_Util::addStyle("jquery-tipsy");
  252. OC_Util::addStyle("jquery.ocdialog");
  253. OC_Util::addScript("oc-requesttoken");
  254. }
  255. public static function initSession() {
  256. // prevents javascript from accessing php session cookies
  257. ini_set('session.cookie_httponly', '1;');
  258. // set the cookie path to the ownCloud directory
  259. $cookie_path = OC::$WEBROOT ?: '/';
  260. ini_set('session.cookie_path', $cookie_path);
  261. //set the session object to a dummy session so code relying on the session existing still works
  262. self::$session = new \OC\Session\Memory('');
  263. try{
  264. // set the session name to the instance id - which is unique
  265. self::$session = new \OC\Session\Internal(OC_Util::getInstanceId());
  266. // if session cant be started break with http 500 error
  267. }catch (Exception $e){
  268. OC_Log::write('core', 'Session could not be initialized',
  269. OC_Log::ERROR);
  270. header('HTTP/1.1 500 Internal Server Error');
  271. OC_Util::addStyle("styles");
  272. $error = 'Session could not be initialized. Please contact your ';
  273. $error .= 'system administrator';
  274. OC_Template::printErrorPage($error);
  275. }
  276. $sessionLifeTime = self::getSessionLifeTime();
  277. // regenerate session id periodically to avoid session fixation
  278. if (!self::$session->exists('SID_CREATED')) {
  279. self::$session->set('SID_CREATED', time());
  280. } else if (time() - self::$session->get('SID_CREATED') > $sessionLifeTime / 2) {
  281. session_regenerate_id(true);
  282. self::$session->set('SID_CREATED', time());
  283. }
  284. // session timeout
  285. if (self::$session->exists('LAST_ACTIVITY') && (time() - self::$session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  286. if (isset($_COOKIE[session_name()])) {
  287. setcookie(session_name(), '', time() - 42000, $cookie_path);
  288. }
  289. session_unset();
  290. session_destroy();
  291. session_start();
  292. }
  293. self::$session->set('LAST_ACTIVITY', time());
  294. }
  295. /**
  296. * @return int
  297. */
  298. private static function getSessionLifeTime() {
  299. return OC_Config::getValue('session_lifetime', 60 * 60 * 24);
  300. }
  301. public static function getRouter() {
  302. if (!isset(OC::$router)) {
  303. OC::$router = new OC_Router();
  304. OC::$router->loadRoutes();
  305. }
  306. return OC::$router;
  307. }
  308. public static function loadAppClassPaths() {
  309. foreach (OC_APP::getEnabledApps() as $app) {
  310. $file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
  311. if (file_exists($file)) {
  312. require_once $file;
  313. }
  314. }
  315. }
  316. public static function init() {
  317. // register autoloader
  318. require_once __DIR__ . '/autoloader.php';
  319. self::$loader=new \OC\Autoloader();
  320. self::$loader->registerPrefix('Doctrine\\Common', 'doctrine/common/lib');
  321. self::$loader->registerPrefix('Doctrine\\DBAL', 'doctrine/dbal/lib');
  322. self::$loader->registerPrefix('Symfony\\Component\\Routing', 'symfony/routing');
  323. self::$loader->registerPrefix('Sabre\\VObject', '3rdparty');
  324. self::$loader->registerPrefix('Sabre_', '3rdparty');
  325. self::$loader->registerPrefix('Patchwork', '3rdparty');
  326. spl_autoload_register(array(self::$loader, 'load'));
  327. // set some stuff
  328. //ob_start();
  329. error_reporting(E_ALL | E_STRICT);
  330. if (defined('DEBUG') && DEBUG) {
  331. ini_set('display_errors', 1);
  332. }
  333. self::$CLI = (php_sapi_name() == 'cli');
  334. date_default_timezone_set('UTC');
  335. ini_set('arg_separator.output', '&amp;');
  336. // try to switch magic quotes off.
  337. if (get_magic_quotes_gpc()==1) {
  338. ini_set('magic_quotes_runtime', 0);
  339. }
  340. //try to configure php to enable big file uploads.
  341. //this doesn´t work always depending on the webserver and php configuration.
  342. //Let´s try to overwrite some defaults anyways
  343. //try to set the maximum execution time to 60min
  344. @set_time_limit(3600);
  345. @ini_set('max_execution_time', 3600);
  346. @ini_set('max_input_time', 3600);
  347. //try to set the maximum filesize to 10G
  348. @ini_set('upload_max_filesize', '10G');
  349. @ini_set('post_max_size', '10G');
  350. @ini_set('file_uploads', '50');
  351. //copy http auth headers for apache+php-fcgid work around
  352. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  353. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  354. }
  355. //set http auth headers for apache+php-cgi work around
  356. if (isset($_SERVER['HTTP_AUTHORIZATION'])
  357. && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
  358. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  359. $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
  360. $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
  361. }
  362. //set http auth headers for apache+php-cgi work around if variable gets renamed by apache
  363. if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])
  364. && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
  365. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  366. $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
  367. $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
  368. }
  369. self::initPaths();
  370. OC_Util::issetlocaleworking();
  371. // set debug mode if an xdebug session is active
  372. if (!defined('DEBUG') || !DEBUG) {
  373. if (isset($_COOKIE['XDEBUG_SESSION'])) {
  374. define('DEBUG', true);
  375. }
  376. }
  377. if (!defined('PHPUNIT_RUN')) {
  378. if (defined('DEBUG') and DEBUG) {
  379. set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
  380. } else {
  381. OC\Log\ErrorHandler::register();
  382. OC\Log\ErrorHandler::setLogger(OC_Log::$object);
  383. }
  384. }
  385. // register the stream wrappers
  386. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  387. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  388. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  389. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  390. self::initTemplateEngine();
  391. if ( !self::$CLI ) {
  392. self::initSession();
  393. } else {
  394. self::$session = new \OC\Session\Memory('');
  395. }
  396. self::checkConfig();
  397. self::checkInstalled();
  398. self::checkSSL();
  399. $errors = OC_Util::checkServer();
  400. if (count($errors) > 0) {
  401. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  402. exit;
  403. }
  404. //try to set the session lifetime
  405. $sessionLifeTime = self::getSessionLifeTime();
  406. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  407. // User and Groups
  408. if (!OC_Config::getValue("installed", false)) {
  409. self::$session->set('user_id','');
  410. }
  411. OC_User::useBackend(new OC_User_Database());
  412. OC_Group::useBackend(new OC_Group_Database());
  413. if (isset($_SERVER['PHP_AUTH_USER']) && self::$session->exists('user_id')
  414. && $_SERVER['PHP_AUTH_USER'] != self::$session->get('user_id')) {
  415. OC_User::logout();
  416. }
  417. // Load Apps
  418. // This includes plugins for users and filesystems as well
  419. global $RUNTIME_NOAPPS;
  420. global $RUNTIME_APPTYPES;
  421. if (!$RUNTIME_NOAPPS) {
  422. if ($RUNTIME_APPTYPES) {
  423. OC_App::loadApps($RUNTIME_APPTYPES);
  424. } else {
  425. OC_App::loadApps();
  426. }
  427. }
  428. //setup extra user backends
  429. OC_User::setupBackends();
  430. self::registerCacheHooks();
  431. self::registerFilesystemHooks();
  432. self::registerShareHooks();
  433. //make sure temporary files are cleaned up
  434. register_shutdown_function(array('OC_Helper', 'cleanTmp'));
  435. //parse the given parameters
  436. self::$REQUESTEDAPP = (isset($_GET['app']) && trim($_GET['app']) != '' && !is_null($_GET['app']) ? OC_App::cleanAppId(strip_tags($_GET['app'])) : OC_Config::getValue('defaultapp', 'files'));
  437. if (substr_count(self::$REQUESTEDAPP, '?') != 0) {
  438. $app = substr(self::$REQUESTEDAPP, 0, strpos(self::$REQUESTEDAPP, '?'));
  439. $param = substr($_GET['app'], strpos($_GET['app'], '?') + 1);
  440. parse_str($param, $get);
  441. $_GET = array_merge($_GET, $get);
  442. self::$REQUESTEDAPP = $app;
  443. $_GET['app'] = $app;
  444. }
  445. self::$REQUESTEDFILE = (isset($_GET['getfile']) ? $_GET['getfile'] : null);
  446. if (substr_count(self::$REQUESTEDFILE, '?') != 0) {
  447. $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?'));
  448. $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1);
  449. parse_str($param, $get);
  450. $_GET = array_merge($_GET, $get);
  451. self::$REQUESTEDFILE = $file;
  452. $_GET['getfile'] = $file;
  453. }
  454. if (!is_null(self::$REQUESTEDFILE)) {
  455. $subdir = OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . self::$REQUESTEDFILE;
  456. $parent = OC_App::getAppPath(OC::$REQUESTEDAPP);
  457. if (!OC_Helper::issubdirectory($subdir, $parent)) {
  458. self::$REQUESTEDFILE = null;
  459. header('HTTP/1.0 404 Not Found');
  460. exit;
  461. }
  462. }
  463. // write error into log if locale can't be set
  464. if (OC_Util::issetlocaleworking() == false) {
  465. OC_Log::write('core',
  466. 'setting locale to en_US.UTF-8/en_US.UTF8 failed. Support is probably not installed on your system',
  467. OC_Log::ERROR);
  468. }
  469. if (OC_Config::getValue('installed', false) && !self::checkUpgrade(false)) {
  470. if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
  471. OC_Util::addScript('backgroundjobs');
  472. }
  473. }
  474. }
  475. /**
  476. * register hooks for the cache
  477. */
  478. public static function registerCacheHooks() {
  479. if (OC_Config::getValue('installed', false)) { //don't try to do this before we are properly setup
  480. // register cache cleanup jobs
  481. try { //if this is executed before the upgrade to the new backgroundjob system is completed it will throw an exception
  482. \OCP\BackgroundJob::registerJob('OC_Cache_FileGlobalGC');
  483. } catch (Exception $e) {
  484. }
  485. OC_Hook::connect('OC_User', 'post_login', 'OC_Cache_File', 'loginListener');
  486. }
  487. }
  488. /**
  489. * register hooks for the filesystem
  490. */
  491. public static function registerFilesystemHooks() {
  492. // Check for blacklisted files
  493. OC_Hook::connect('OC_Filesystem', 'write', 'OC_Filesystem', 'isBlacklisted');
  494. OC_Hook::connect('OC_Filesystem', 'rename', 'OC_Filesystem', 'isBlacklisted');
  495. }
  496. /**
  497. * register hooks for sharing
  498. */
  499. public static function registerShareHooks() {
  500. if(\OC_Config::getValue('installed')) {
  501. OC_Hook::connect('OC_User', 'post_deleteUser', 'OCP\Share', 'post_deleteUser');
  502. OC_Hook::connect('OC_User', 'post_addToGroup', 'OCP\Share', 'post_addToGroup');
  503. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OCP\Share', 'post_removeFromGroup');
  504. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OCP\Share', 'post_deleteGroup');
  505. }
  506. }
  507. /**
  508. * @brief Handle the request
  509. */
  510. public static function handleRequest() {
  511. // load all the classpaths from the enabled apps so they are available
  512. // in the routing files of each app
  513. OC::loadAppClassPaths();
  514. // Check if ownCloud is installed or in maintenance (update) mode
  515. if (!OC_Config::getValue('installed', false)) {
  516. require_once 'core/setup.php';
  517. exit();
  518. }
  519. $request = OC_Request::getPathInfo();
  520. if(substr($request, -3) !== '.js') {// we need these files during the upgrade
  521. self::checkMaintenanceMode();
  522. self::checkUpgrade();
  523. }
  524. // Test it the user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
  525. OC::tryBasicAuthLogin();
  526. if (!self::$CLI) {
  527. try {
  528. if (!OC_Config::getValue('maintenance', false)) {
  529. OC_App::loadApps();
  530. }
  531. OC::getRouter()->match(OC_Request::getRawPathInfo());
  532. return;
  533. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  534. //header('HTTP/1.0 404 Not Found');
  535. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  536. OC_Response::setStatus(405);
  537. return;
  538. }
  539. }
  540. $app = OC::$REQUESTEDAPP;
  541. $file = OC::$REQUESTEDFILE;
  542. $param = array('app' => $app, 'file' => $file);
  543. // Handle app css files
  544. if (substr($file, -3) == 'css') {
  545. self::loadCSSFile($param);
  546. return;
  547. }
  548. // Handle redirect URL for logged in users
  549. if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
  550. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  551. // Deny the redirect if the URL contains a @
  552. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  553. if (strpos($location, '@') === false) {
  554. header('Location: ' . $location);
  555. return;
  556. }
  557. }
  558. // Handle WebDAV
  559. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  560. header('location: ' . OC_Helper::linkToRemote('webdav'));
  561. return;
  562. }
  563. // Someone is logged in :
  564. if (OC_User::isLoggedIn()) {
  565. OC_App::loadApps();
  566. OC_User::setupBackends();
  567. if (isset($_GET["logout"]) and ($_GET["logout"])) {
  568. if (isset($_COOKIE['oc_token'])) {
  569. OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
  570. }
  571. OC_User::logout();
  572. header("Location: " . OC::$WEBROOT . '/');
  573. } else {
  574. if (is_null($file)) {
  575. $param['file'] = 'index.php';
  576. }
  577. $file_ext = substr($param['file'], -3);
  578. if ($file_ext != 'php'
  579. || !self::loadAppScriptFile($param)
  580. ) {
  581. header('HTTP/1.0 404 Not Found');
  582. }
  583. }
  584. return;
  585. }
  586. // Not handled and not logged in
  587. self::handleLogin();
  588. }
  589. public static function loadAppScriptFile($param) {
  590. OC_App::loadApps();
  591. $app = $param['app'];
  592. $file = $param['file'];
  593. $app_path = OC_App::getAppPath($app);
  594. $file = $app_path . '/' . $file;
  595. unset($app, $app_path);
  596. if (file_exists($file)) {
  597. require_once $file;
  598. return true;
  599. }
  600. return false;
  601. }
  602. public static function loadCSSFile($param) {
  603. $app = $param['app'];
  604. $file = $param['file'];
  605. $app_path = OC_App::getAppPath($app);
  606. if (file_exists($app_path . '/' . $file)) {
  607. $app_web_path = OC_App::getAppWebPath($app);
  608. $filepath = $app_web_path . '/' . $file;
  609. $minimizer = new OC_Minimizer_CSS();
  610. $info = array($app_path, $app_web_path, $file);
  611. $minimizer->output(array($info), $filepath);
  612. }
  613. }
  614. protected static function handleLogin() {
  615. OC_App::loadApps(array('prelogin'));
  616. $error = array();
  617. // remember was checked after last login
  618. if (OC::tryRememberLogin()) {
  619. $error[] = 'invalidcookie';
  620. // Someone wants to log in :
  621. } elseif (OC::tryFormLogin()) {
  622. $error[] = 'invalidpassword';
  623. }
  624. OC_Util::displayLoginPage(array_unique($error));
  625. }
  626. protected static function cleanupLoginTokens($user) {
  627. $cutoff = time() - OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  628. $tokens = OC_Preferences::getKeys($user, 'login_token');
  629. foreach ($tokens as $token) {
  630. $time = OC_Preferences::getValue($user, 'login_token', $token);
  631. if ($time < $cutoff) {
  632. OC_Preferences::deleteKey($user, 'login_token', $token);
  633. }
  634. }
  635. }
  636. protected static function tryRememberLogin() {
  637. if (!isset($_COOKIE["oc_remember_login"])
  638. || !isset($_COOKIE["oc_token"])
  639. || !isset($_COOKIE["oc_username"])
  640. || !$_COOKIE["oc_remember_login"]
  641. ) {
  642. return false;
  643. }
  644. OC_App::loadApps(array('authentication'));
  645. if (defined("DEBUG") && DEBUG) {
  646. OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
  647. }
  648. // confirm credentials in cookie
  649. if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username'])) {
  650. // delete outdated cookies
  651. self::cleanupLoginTokens($_COOKIE['oc_username']);
  652. // get stored tokens
  653. $tokens = OC_Preferences::getKeys($_COOKIE['oc_username'], 'login_token');
  654. // test cookies token against stored tokens
  655. if (in_array($_COOKIE['oc_token'], $tokens, true)) {
  656. // replace successfully used token with a new one
  657. OC_Preferences::deleteKey($_COOKIE['oc_username'], 'login_token', $_COOKIE['oc_token']);
  658. $token = OC_Util::generate_random_bytes(32);
  659. OC_Preferences::setValue($_COOKIE['oc_username'], 'login_token', $token, time());
  660. OC_User::setMagicInCookie($_COOKIE['oc_username'], $token);
  661. // login
  662. OC_User::setUserId($_COOKIE['oc_username']);
  663. OC_Util::redirectToDefaultPage();
  664. // doesn't return
  665. }
  666. // if you reach this point you have changed your password
  667. // or you are an attacker
  668. // we can not delete tokens here because users may reach
  669. // this point multiple times after a password change
  670. OC_Log::write('core', 'Authentication cookie rejected for user ' . $_COOKIE['oc_username'], OC_Log::WARN);
  671. }
  672. OC_User::unsetMagicInCookie();
  673. return true;
  674. }
  675. protected static function tryFormLogin() {
  676. if (!isset($_POST["user"]) || !isset($_POST['password'])) {
  677. return false;
  678. }
  679. OC_App::loadApps();
  680. //setup extra user backends
  681. OC_User::setupBackends();
  682. if (OC_User::login($_POST["user"], $_POST["password"])) {
  683. // setting up the time zone
  684. if (isset($_POST['timezone-offset'])) {
  685. self::$session->set('timezone', $_POST['timezone-offset']);
  686. }
  687. self::cleanupLoginTokens($_POST['user']);
  688. if (!empty($_POST["remember_login"])) {
  689. if (defined("DEBUG") && DEBUG) {
  690. OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
  691. }
  692. $token = OC_Util::generate_random_bytes(32);
  693. OC_Preferences::setValue($_POST['user'], 'login_token', $token, time());
  694. OC_User::setMagicInCookie($_POST["user"], $token);
  695. } else {
  696. OC_User::unsetMagicInCookie();
  697. }
  698. OC_Util::redirectToDefaultPage();
  699. exit();
  700. }
  701. return true;
  702. }
  703. protected static function tryBasicAuthLogin() {
  704. if (!isset($_SERVER["PHP_AUTH_USER"])
  705. || !isset($_SERVER["PHP_AUTH_PW"])
  706. ) {
  707. return false;
  708. }
  709. OC_App::loadApps(array('authentication'));
  710. if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
  711. //OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
  712. OC_User::unsetMagicInCookie();
  713. $_SERVER['HTTP_REQUESTTOKEN'] = OC_Util::callRegister();
  714. }
  715. return true;
  716. }
  717. }
  718. // define runtime variables - unless this already has been done
  719. if (!isset($RUNTIME_NOAPPS)) {
  720. $RUNTIME_NOAPPS = false;
  721. }
  722. if (!function_exists('get_temp_dir')) {
  723. function get_temp_dir() {
  724. if ($temp = ini_get('upload_tmp_dir')) return $temp;
  725. if ($temp = getenv('TMP')) return $temp;
  726. if ($temp = getenv('TEMP')) return $temp;
  727. if ($temp = getenv('TMPDIR')) return $temp;
  728. $temp = tempnam(__FILE__, '');
  729. if (file_exists($temp)) {
  730. unlink($temp);
  731. return dirname($temp);
  732. }
  733. if ($temp = sys_get_temp_dir()) return $temp;
  734. return null;
  735. }
  736. }
  737. OC::init();