PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/base.php

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