base.php 34 KB

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