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

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