base.php 26 KB

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