base.php 32 KB

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