You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.php 32KB

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