base.php 40 KB

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