base.php 37 KB

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