base.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. * @var 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. /**
  83. * @var \OC\Server
  84. */
  85. public static $server = null;
  86. public static function initPaths() {
  87. // calculate the root directories
  88. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  89. // ensure we can find OC_Config
  90. set_include_path(
  91. OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
  92. get_include_path()
  93. );
  94. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  95. $scriptName = OC_Request::scriptName();
  96. if (substr($scriptName, -1) == '/') {
  97. $scriptName .= 'index.php';
  98. //make sure suburi follows the same rules as scriptName
  99. if (substr(OC::$SUBURI, -9) != 'index.php') {
  100. if (substr(OC::$SUBURI, -1) != '/') {
  101. OC::$SUBURI = OC::$SUBURI . '/';
  102. }
  103. OC::$SUBURI = OC::$SUBURI . 'index.php';
  104. }
  105. }
  106. OC::$WEBROOT = substr($scriptName, 0, strlen($scriptName) - strlen(OC::$SUBURI));
  107. if (OC::$WEBROOT != '' and OC::$WEBROOT[0] !== '/') {
  108. OC::$WEBROOT = '/' . OC::$WEBROOT;
  109. }
  110. // search the 3rdparty folder
  111. if (OC_Config::getValue('3rdpartyroot', '') <> '' and OC_Config::getValue('3rdpartyurl', '') <> '') {
  112. OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', '');
  113. OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', '');
  114. } elseif (file_exists(OC::$SERVERROOT . '/3rdparty')) {
  115. OC::$THIRDPARTYROOT = OC::$SERVERROOT;
  116. OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
  117. } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
  118. OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
  119. OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
  120. } else {
  121. throw new Exception('3rdparty directory not found! Please put the ownCloud 3rdparty'
  122. .' folder in the ownCloud folder or the folder above.'
  123. .' You can also configure the location in the config.php file.');
  124. }
  125. // search the apps folder
  126. $config_paths = OC_Config::getValue('apps_paths', array());
  127. if (!empty($config_paths)) {
  128. foreach ($config_paths as $paths) {
  129. if (isset($paths['url']) && isset($paths['path'])) {
  130. $paths['url'] = rtrim($paths['url'], '/');
  131. $paths['path'] = rtrim($paths['path'], '/');
  132. OC::$APPSROOTS[] = $paths;
  133. }
  134. }
  135. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  136. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  137. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  138. OC::$APPSROOTS[] = array(
  139. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  140. 'url' => '/apps',
  141. 'writable' => true
  142. );
  143. }
  144. if (empty(OC::$APPSROOTS)) {
  145. throw new Exception('apps directory not found! Please put the ownCloud apps folder in the ownCloud folder'
  146. .' or the folder above. You can also configure the location in the config.php file.');
  147. }
  148. $paths = array();
  149. foreach (OC::$APPSROOTS as $path) {
  150. $paths[] = $path['path'];
  151. }
  152. // set the right include path
  153. set_include_path(
  154. OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
  155. OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
  156. OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
  157. implode($paths, PATH_SEPARATOR) . PATH_SEPARATOR .
  158. get_include_path() . PATH_SEPARATOR .
  159. OC::$SERVERROOT
  160. );
  161. }
  162. public static function checkConfig() {
  163. if (file_exists(OC::$SERVERROOT . "/config/config.php")
  164. and !is_writable(OC::$SERVERROOT . "/config/config.php")) {
  165. $defaults = new OC_Defaults();
  166. OC_Template::printErrorPage(
  167. "Can't write into config directory!",
  168. 'This can usually be fixed by '
  169. .'<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">giving the webserver write access to the config directory</a>.'
  170. );
  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('', 'update.user', 'guest');
  209. $tmpl->printPage();
  210. die();
  211. }
  212. }
  213. public static function checkUpgrade($showTemplate = true) {
  214. if (OC_Config::getValue('installed', false)) {
  215. $installedVersion = OC_Config::getValue('version', '0.0.0');
  216. $currentVersion = implode('.', OC_Util::getVersion());
  217. if (version_compare($currentVersion, $installedVersion, '>')) {
  218. if ($showTemplate && !OC_Config::getValue('maintenance', false)) {
  219. OC_Config::setValue('theme', '');
  220. $minimizerCSS = new OC_Minimizer_CSS();
  221. $minimizerCSS->clearCache();
  222. $minimizerJS = new OC_Minimizer_JS();
  223. $minimizerJS->clearCache();
  224. OC_Util::addScript('update');
  225. $tmpl = new OC_Template('', 'update.admin', 'guest');
  226. $tmpl->assign('version', OC_Util::getVersionString());
  227. $tmpl->printPage();
  228. exit();
  229. } else {
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. }
  236. public static function initTemplateEngine() {
  237. // Add the stuff we need always
  238. OC_Util::addScript("jquery-1.10.0.min");
  239. OC_Util::addScript("jquery-migrate-1.2.1.min");
  240. OC_Util::addScript("jquery-ui-1.10.0.custom");
  241. OC_Util::addScript("jquery-showpassword");
  242. OC_Util::addScript("jquery.infieldlabel");
  243. OC_Util::addScript("jquery.placeholder");
  244. OC_Util::addScript("jquery-tipsy");
  245. OC_Util::addScript("compatibility");
  246. OC_Util::addScript("jquery.ocdialog");
  247. OC_Util::addScript("oc-dialogs");
  248. OC_Util::addScript("js");
  249. OC_Util::addScript("octemplate");
  250. OC_Util::addScript("eventsource");
  251. OC_Util::addScript("config");
  252. //OC_Util::addScript( "multiselect" );
  253. OC_Util::addScript('search', 'result');
  254. OC_Util::addScript('router');
  255. OC_Util::addScript("oc-requesttoken");
  256. // avatars
  257. if (\OC_Config::getValue('enable_avatars', true) === true) {
  258. \OC_Util::addScript('placeholder');
  259. \OC_Util::addScript('3rdparty', 'md5/md5.min');
  260. \OC_Util::addScript('jquery.avatar');
  261. \OC_Util::addScript('avatar');
  262. }
  263. OC_Util::addStyle("styles");
  264. OC_Util::addStyle("apps");
  265. OC_Util::addStyle("fixes");
  266. OC_Util::addStyle("multiselect");
  267. OC_Util::addStyle("jquery-ui-1.10.0.custom");
  268. OC_Util::addStyle("jquery-tipsy");
  269. OC_Util::addStyle("jquery.ocdialog");
  270. }
  271. public static function initSession() {
  272. // prevents javascript from accessing php session cookies
  273. ini_set('session.cookie_httponly', '1;');
  274. // set the cookie path to the ownCloud directory
  275. $cookie_path = OC::$WEBROOT ? : '/';
  276. ini_set('session.cookie_path', $cookie_path);
  277. //set the session object to a dummy session so code relying on the session existing still works
  278. self::$session = new \OC\Session\Memory('');
  279. try {
  280. // set the session name to the instance id - which is unique
  281. self::$session = new \OC\Session\Internal(OC_Util::getInstanceId());
  282. // if session cant be started break with http 500 error
  283. } catch (Exception $e) {
  284. //show the user a detailed error page
  285. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  286. OC_Template::printExceptionErrorPage($e);
  287. }
  288. $sessionLifeTime = self::getSessionLifeTime();
  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') > $sessionLifeTime / 2) {
  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') > $sessionLifeTime)) {
  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. /**
  308. * @return int
  309. */
  310. private static function getSessionLifeTime() {
  311. return OC_Config::getValue('session_lifetime', 60 * 60 * 24);
  312. }
  313. /**
  314. * @return OC_Router
  315. */
  316. public static function getRouter() {
  317. if (!isset(OC::$router)) {
  318. OC::$router = new OC_Router();
  319. OC::$router->loadRoutes();
  320. }
  321. return OC::$router;
  322. }
  323. public static function loadAppClassPaths() {
  324. foreach (OC_APP::getEnabledApps() as $app) {
  325. $file = OC_App::getAppPath($app) . '/appinfo/classpath.php';
  326. if (file_exists($file)) {
  327. require_once $file;
  328. }
  329. }
  330. }
  331. public static function init() {
  332. // register autoloader
  333. require_once __DIR__ . '/autoloader.php';
  334. self::$loader = new \OC\Autoloader();
  335. self::$loader->registerPrefix('Doctrine\\Common', 'doctrine/common/lib');
  336. self::$loader->registerPrefix('Doctrine\\DBAL', 'doctrine/dbal/lib');
  337. self::$loader->registerPrefix('Symfony\\Component\\Routing', 'symfony/routing');
  338. self::$loader->registerPrefix('Symfony\\Component\\Console', 'symfony/console');
  339. self::$loader->registerPrefix('Sabre\\VObject', '3rdparty');
  340. self::$loader->registerPrefix('Sabre_', '3rdparty');
  341. self::$loader->registerPrefix('Patchwork', '3rdparty');
  342. spl_autoload_register(array(self::$loader, 'load'));
  343. // set some stuff
  344. //ob_start();
  345. error_reporting(E_ALL | E_STRICT);
  346. if (defined('DEBUG') && DEBUG) {
  347. ini_set('display_errors', 1);
  348. }
  349. self::$CLI = (php_sapi_name() == 'cli');
  350. date_default_timezone_set('UTC');
  351. ini_set('arg_separator.output', '&amp;');
  352. // try to switch magic quotes off.
  353. if (get_magic_quotes_gpc() == 1) {
  354. ini_set('magic_quotes_runtime', 0);
  355. }
  356. //try to configure php to enable big file uploads.
  357. //this doesn´t work always depending on the webserver and php configuration.
  358. //Let´s try to overwrite some defaults anyways
  359. //try to set the maximum execution time to 60min
  360. @set_time_limit(3600);
  361. @ini_set('max_execution_time', 3600);
  362. @ini_set('max_input_time', 3600);
  363. //try to set the maximum filesize to 10G
  364. @ini_set('upload_max_filesize', '10G');
  365. @ini_set('post_max_size', '10G');
  366. @ini_set('file_uploads', '50');
  367. //copy http auth headers for apache+php-fcgid work around
  368. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  369. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  370. }
  371. //set http auth headers for apache+php-cgi work around
  372. if (isset($_SERVER['HTTP_AUTHORIZATION'])
  373. && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)
  374. ) {
  375. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  376. $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
  377. $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
  378. }
  379. //set http auth headers for apache+php-cgi work around if variable gets renamed by apache
  380. if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])
  381. && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)
  382. ) {
  383. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  384. $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
  385. $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
  386. }
  387. self::initPaths();
  388. if (OC_Config::getValue('instanceid', false)) {
  389. // \OC\Memcache\Cache has a hidden dependency on
  390. // OC_Util::getInstanceId() for namespacing. See #5409.
  391. try {
  392. self::$loader->setMemoryCache(\OC\Memcache\Factory::createLowLatency('Autoloader'));
  393. } catch(\Exception $ex) {
  394. }
  395. }
  396. OC_Util::isSetLocaleWorking();
  397. // set debug mode if an xdebug session is active
  398. if (!defined('DEBUG') || !DEBUG) {
  399. if (isset($_COOKIE['XDEBUG_SESSION'])) {
  400. define('DEBUG', true);
  401. }
  402. }
  403. if (!defined('PHPUNIT_RUN')) {
  404. if (defined('DEBUG') and DEBUG) {
  405. set_exception_handler(array('OC_Template', 'printExceptionErrorPage'));
  406. } else {
  407. OC\Log\ErrorHandler::register();
  408. OC\Log\ErrorHandler::setLogger(OC_Log::$object);
  409. }
  410. }
  411. // register the stream wrappers
  412. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  413. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  414. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  415. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  416. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  417. // setup the basic server
  418. self::$server = new \OC\Server();
  419. self::initTemplateEngine();
  420. if (!self::$CLI) {
  421. self::initSession();
  422. } else {
  423. self::$session = new \OC\Session\Memory('');
  424. }
  425. self::checkConfig();
  426. self::checkInstalled();
  427. self::checkSSL();
  428. $errors = OC_Util::checkServer();
  429. if (count($errors) > 0) {
  430. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  431. exit;
  432. }
  433. //try to set the session lifetime
  434. $sessionLifeTime = self::getSessionLifeTime();
  435. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  436. // User and Groups
  437. if (!OC_Config::getValue("installed", false)) {
  438. self::$session->set('user_id', '');
  439. }
  440. OC_User::useBackend(new OC_User_Database());
  441. OC_Group::useBackend(new OC_Group_Database());
  442. if (isset($_SERVER['PHP_AUTH_USER']) && self::$session->exists('user_id')
  443. && $_SERVER['PHP_AUTH_USER'] != self::$session->get('user_id')) {
  444. $sessionUser = self::$session->get('user_id');
  445. $serverUser = $_SERVER['PHP_AUTH_USER'];
  446. OC_Log::write('core',
  447. "Session user-id ($sessionUser) doesn't match SERVER[PHP_AUTH_USER] ($serverUser).",
  448. OC_Log::WARN);
  449. OC_User::logout();
  450. }
  451. // Load Apps
  452. // This includes plugins for users and filesystems as well
  453. global $RUNTIME_NOAPPS;
  454. global $RUNTIME_APPTYPES;
  455. if (!$RUNTIME_NOAPPS && !self::checkUpgrade(false)) {
  456. if ($RUNTIME_APPTYPES) {
  457. OC_App::loadApps($RUNTIME_APPTYPES);
  458. } else {
  459. OC_App::loadApps();
  460. }
  461. }
  462. //setup extra user backends
  463. OC_User::setupBackends();
  464. self::registerCacheHooks();
  465. self::registerFilesystemHooks();
  466. self::registerPreviewHooks();
  467. self::registerShareHooks();
  468. self::registerLogRotate();
  469. //make sure temporary files are cleaned up
  470. register_shutdown_function(array('OC_Helper', 'cleanTmp'));
  471. //parse the given parameters
  472. self::$REQUESTEDAPP = (isset($_GET['app']) && trim($_GET['app']) != '' && !is_null($_GET['app']) ? OC_App::cleanAppId(strip_tags($_GET['app'])) : OC_Config::getValue('defaultapp', 'files'));
  473. if (substr_count(self::$REQUESTEDAPP, '?') != 0) {
  474. $app = substr(self::$REQUESTEDAPP, 0, strpos(self::$REQUESTEDAPP, '?'));
  475. $param = substr($_GET['app'], strpos($_GET['app'], '?') + 1);
  476. parse_str($param, $get);
  477. $_GET = array_merge($_GET, $get);
  478. self::$REQUESTEDAPP = $app;
  479. $_GET['app'] = $app;
  480. }
  481. self::$REQUESTEDFILE = (isset($_GET['getfile']) ? $_GET['getfile'] : null);
  482. if (substr_count(self::$REQUESTEDFILE, '?') != 0) {
  483. $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?'));
  484. $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1);
  485. parse_str($param, $get);
  486. $_GET = array_merge($_GET, $get);
  487. self::$REQUESTEDFILE = $file;
  488. $_GET['getfile'] = $file;
  489. }
  490. if (!is_null(self::$REQUESTEDFILE)) {
  491. $subdir = OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . self::$REQUESTEDFILE;
  492. $parent = OC_App::getAppPath(OC::$REQUESTEDAPP);
  493. if (!OC_Helper::issubdirectory($subdir, $parent)) {
  494. self::$REQUESTEDFILE = null;
  495. header('HTTP/1.0 404 Not Found');
  496. exit;
  497. }
  498. }
  499. if (OC_Config::getValue('installed', false) && !self::checkUpgrade(false)) {
  500. if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
  501. OC_Util::addScript('backgroundjobs');
  502. }
  503. }
  504. }
  505. /**
  506. * register hooks for the cache
  507. */
  508. public static function registerCacheHooks() {
  509. if (OC_Config::getValue('installed', false)) { //don't try to do this before we are properly setup
  510. // register cache cleanup jobs
  511. try { //if this is executed before the upgrade to the new backgroundjob system is completed it will throw an exception
  512. \OCP\BackgroundJob::registerJob('OC\Cache\FileGlobalGC');
  513. } catch (Exception $e) {
  514. }
  515. // NOTE: This will be replaced to use OCP
  516. $userSession = \OC_User::getUserSession();
  517. $userSession->listen('postLogin', '\OC\Cache\File', 'loginListener');
  518. }
  519. }
  520. /**
  521. * register hooks for the cache
  522. */
  523. public static function registerLogRotate() {
  524. if (OC_Config::getValue('installed', false) && OC_Config::getValue('log_rotate_size', false)) {
  525. //don't try to do this before we are properly setup
  526. // register cache cleanup jobs
  527. try { //if this is executed before the upgrade to the new backgroundjob system is completed it will throw an exception
  528. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', OC_Config::getValue("datadirectory", OC::$SERVERROOT.'/data').'/owncloud.log');
  529. } catch (Exception $e) {
  530. }
  531. }
  532. }
  533. /**
  534. * register hooks for the filesystem
  535. */
  536. public static function registerFilesystemHooks() {
  537. // Check for blacklisted files
  538. OC_Hook::connect('OC_Filesystem', 'write', 'OC_Filesystem', 'isBlacklisted');
  539. OC_Hook::connect('OC_Filesystem', 'rename', 'OC_Filesystem', 'isBlacklisted');
  540. }
  541. /**
  542. * register hooks for previews
  543. */
  544. public static function registerPreviewHooks() {
  545. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  546. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'post_delete');
  547. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete');
  548. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  549. }
  550. /**
  551. * register hooks for sharing
  552. */
  553. public static function registerShareHooks() {
  554. if(\OC_Config::getValue('installed')) {
  555. OC_Hook::connect('OC_User', 'post_deleteUser', 'OCP\Share', 'post_deleteUser');
  556. OC_Hook::connect('OC_User', 'post_addToGroup', 'OCP\Share', 'post_addToGroup');
  557. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OCP\Share', 'post_removeFromGroup');
  558. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OCP\Share', 'post_deleteGroup');
  559. }
  560. }
  561. /**
  562. * @brief Handle the request
  563. */
  564. public static function handleRequest() {
  565. // load all the classpaths from the enabled apps so they are available
  566. // in the routing files of each app
  567. OC::loadAppClassPaths();
  568. // Check if ownCloud is installed or in maintenance (update) mode
  569. if (!OC_Config::getValue('installed', false)) {
  570. require_once 'core/setup.php';
  571. exit();
  572. }
  573. $request = OC_Request::getPathInfo();
  574. if(substr($request, -3) !== '.js') {// we need these files during the upgrade
  575. self::checkMaintenanceMode();
  576. self::checkUpgrade();
  577. }
  578. // Test it the user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
  579. OC::tryBasicAuthLogin();
  580. if (!self::$CLI) {
  581. try {
  582. if (!OC_Config::getValue('maintenance', false)) {
  583. OC_App::loadApps();
  584. }
  585. OC::getRouter()->match(OC_Request::getRawPathInfo());
  586. return;
  587. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  588. //header('HTTP/1.0 404 Not Found');
  589. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  590. OC_Response::setStatus(405);
  591. return;
  592. }
  593. }
  594. $app = OC::$REQUESTEDAPP;
  595. $file = OC::$REQUESTEDFILE;
  596. $param = array('app' => $app, 'file' => $file);
  597. // Handle app css files
  598. if (substr($file, -3) == 'css') {
  599. self::loadCSSFile($param);
  600. return;
  601. }
  602. // Handle redirect URL for logged in users
  603. if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
  604. $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
  605. // Deny the redirect if the URL contains a @
  606. // This prevents unvalidated redirects like ?redirect_url=:user@domain.com
  607. if (strpos($location, '@') === false) {
  608. header('Location: ' . $location);
  609. return;
  610. }
  611. }
  612. // Handle WebDAV
  613. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  614. // not allowed any more to prevent people
  615. // mounting this root directly.
  616. // Users need to mount remote.php/webdav instead.
  617. header('HTTP/1.1 405 Method Not Allowed');
  618. header('Status: 405 Method Not Allowed');
  619. return;
  620. }
  621. // Someone is logged in :
  622. if (OC_User::isLoggedIn()) {
  623. OC_App::loadApps();
  624. OC_User::setupBackends();
  625. if (isset($_GET["logout"]) and ($_GET["logout"])) {
  626. if (isset($_COOKIE['oc_token'])) {
  627. OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
  628. }
  629. OC_User::logout();
  630. header("Location: " . OC::$WEBROOT . '/');
  631. } else {
  632. if (is_null($file)) {
  633. $param['file'] = 'index.php';
  634. }
  635. $file_ext = substr($param['file'], -3);
  636. if ($file_ext != 'php'
  637. || !self::loadAppScriptFile($param)
  638. ) {
  639. header('HTTP/1.0 404 Not Found');
  640. }
  641. }
  642. return;
  643. }
  644. // Not handled and not logged in
  645. self::handleLogin();
  646. }
  647. public static function loadAppScriptFile($param) {
  648. OC_App::loadApps();
  649. $app = $param['app'];
  650. $file = $param['file'];
  651. $app_path = OC_App::getAppPath($app);
  652. if (OC_App::isEnabled($app) && $app_path !== false) {
  653. $file = $app_path . '/' . $file;
  654. unset($app, $app_path);
  655. if (file_exists($file)) {
  656. require_once $file;
  657. return true;
  658. }
  659. }
  660. header('HTTP/1.0 404 Not Found');
  661. return false;
  662. }
  663. public static function loadCSSFile($param) {
  664. $app = $param['app'];
  665. $file = $param['file'];
  666. $app_path = OC_App::getAppPath($app);
  667. if (file_exists($app_path . '/' . $file)) {
  668. $app_web_path = OC_App::getAppWebPath($app);
  669. $filepath = $app_web_path . '/' . $file;
  670. $minimizer = new OC_Minimizer_CSS();
  671. $info = array($app_path, $app_web_path, $file);
  672. $minimizer->output(array($info), $filepath);
  673. }
  674. }
  675. protected static function handleLogin() {
  676. OC_App::loadApps(array('prelogin'));
  677. $error = array();
  678. // auth possible via apache module?
  679. if (OC::tryApacheAuth()) {
  680. $error[] = 'apacheauthfailed';
  681. }
  682. // remember was checked after last login
  683. elseif (OC::tryRememberLogin()) {
  684. $error[] = 'invalidcookie';
  685. }
  686. // logon via web form
  687. elseif (OC::tryFormLogin()) {
  688. $error[] = 'invalidpassword';
  689. if ( OC_Config::getValue('log_authfailip', false) ) {
  690. OC_Log::write('core', 'Login failed: user \''.$_POST["user"].'\' , wrong password, IP:'.$_SERVER['REMOTE_ADDR'],
  691. OC_Log::WARN);
  692. } else {
  693. OC_Log::write('core', 'Login failed: user \''.$_POST["user"].'\' , wrong password, IP:set log_authfailip=true in conf',
  694. OC_Log::WARN);
  695. }
  696. }
  697. OC_Util::displayLoginPage(array_unique($error));
  698. }
  699. protected static function cleanupLoginTokens($user) {
  700. $cutoff = time() - OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
  701. $tokens = OC_Preferences::getKeys($user, 'login_token');
  702. foreach ($tokens as $token) {
  703. $time = OC_Preferences::getValue($user, 'login_token', $token);
  704. if ($time < $cutoff) {
  705. OC_Preferences::deleteKey($user, 'login_token', $token);
  706. }
  707. }
  708. }
  709. protected static function tryApacheAuth() {
  710. $return = OC_User::handleApacheAuth();
  711. // if return is true we are logged in -> redirect to the default page
  712. if ($return === true) {
  713. $_REQUEST['redirect_url'] = \OC_Request::requestUri();
  714. OC_Util::redirectToDefaultPage();
  715. exit;
  716. }
  717. // in case $return is null apache based auth is not enabled
  718. return is_null($return) ? false : true;
  719. }
  720. protected static function tryRememberLogin() {
  721. if (!isset($_COOKIE["oc_remember_login"])
  722. || !isset($_COOKIE["oc_token"])
  723. || !isset($_COOKIE["oc_username"])
  724. || !$_COOKIE["oc_remember_login"]
  725. || !OC_Util::rememberLoginAllowed()
  726. ) {
  727. return false;
  728. }
  729. OC_App::loadApps(array('authentication'));
  730. if (defined("DEBUG") && DEBUG) {
  731. OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
  732. }
  733. // confirm credentials in cookie
  734. if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username'])) {
  735. // delete outdated cookies
  736. self::cleanupLoginTokens($_COOKIE['oc_username']);
  737. // get stored tokens
  738. $tokens = OC_Preferences::getKeys($_COOKIE['oc_username'], 'login_token');
  739. // test cookies token against stored tokens
  740. if (in_array($_COOKIE['oc_token'], $tokens, true)) {
  741. // replace successfully used token with a new one
  742. OC_Preferences::deleteKey($_COOKIE['oc_username'], 'login_token', $_COOKIE['oc_token']);
  743. $token = OC_Util::generateRandomBytes(32);
  744. OC_Preferences::setValue($_COOKIE['oc_username'], 'login_token', $token, time());
  745. OC_User::setMagicInCookie($_COOKIE['oc_username'], $token);
  746. // login
  747. OC_User::setUserId($_COOKIE['oc_username']);
  748. OC_User::setDisplayName($_COOKIE['oc_username'], $_COOKIE['display_name']);
  749. OC_Util::redirectToDefaultPage();
  750. // doesn't return
  751. }
  752. // if you reach this point you have changed your password
  753. // or you are an attacker
  754. // we can not delete tokens here because users may reach
  755. // this point multiple times after a password change
  756. OC_Log::write('core', 'Authentication cookie rejected for user ' . $_COOKIE['oc_username'], OC_Log::WARN);
  757. }
  758. OC_User::unsetMagicInCookie();
  759. return true;
  760. }
  761. protected static function tryFormLogin() {
  762. if (!isset($_POST["user"]) || !isset($_POST['password'])) {
  763. return false;
  764. }
  765. OC_App::loadApps();
  766. //setup extra user backends
  767. OC_User::setupBackends();
  768. if (OC_User::login($_POST["user"], $_POST["password"])) {
  769. // setting up the time zone
  770. if (isset($_POST['timezone-offset'])) {
  771. self::$session->set('timezone', $_POST['timezone-offset']);
  772. }
  773. $userid = OC_User::getUser();
  774. self::cleanupLoginTokens($userid);
  775. if (!empty($_POST["remember_login"])) {
  776. if (defined("DEBUG") && DEBUG) {
  777. OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
  778. }
  779. $token = OC_Util::generateRandomBytes(32);
  780. OC_Preferences::setValue($userid, 'login_token', $token, time());
  781. OC_User::setMagicInCookie($userid, $token);
  782. } else {
  783. OC_User::unsetMagicInCookie();
  784. }
  785. OC_Util::redirectToDefaultPage();
  786. exit();
  787. }
  788. return true;
  789. }
  790. protected static function tryBasicAuthLogin() {
  791. if (!isset($_SERVER["PHP_AUTH_USER"])
  792. || !isset($_SERVER["PHP_AUTH_PW"])
  793. ) {
  794. return false;
  795. }
  796. OC_App::loadApps(array('authentication'));
  797. if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
  798. //OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
  799. OC_User::unsetMagicInCookie();
  800. $_SERVER['HTTP_REQUESTTOKEN'] = OC_Util::callRegister();
  801. }
  802. return true;
  803. }
  804. }
  805. // define runtime variables - unless this already has been done
  806. if (!isset($RUNTIME_NOAPPS)) {
  807. $RUNTIME_NOAPPS = false;
  808. }
  809. if (!function_exists('get_temp_dir')) {
  810. function get_temp_dir() {
  811. if ($temp = ini_get('upload_tmp_dir')) return $temp;
  812. if ($temp = getenv('TMP')) return $temp;
  813. if ($temp = getenv('TEMP')) return $temp;
  814. if ($temp = getenv('TMPDIR')) return $temp;
  815. $temp = tempnam(__FILE__, '');
  816. if (file_exists($temp)) {
  817. unlink($temp);
  818. return dirname($temp);
  819. }
  820. if ($temp = sys_get_temp_dir()) return $temp;
  821. return null;
  822. }
  823. }
  824. OC::init();