base.php 33 KB

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