base.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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 Bjoern Schiessle <bjoern@schiessle.org>
  11. * @author Björn Schießle <bjoern@schiessle.org>
  12. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  13. * @author Damjan Georgievski <gdamjan@gmail.com>
  14. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  15. * @author davidgumberg <davidnoizgumberg@gmail.com>
  16. * @author Eric Masseran <rico.masseran@gmail.com>
  17. * @author Florin Peter <github@florin-peter.de>
  18. * @author Greta Doci <gretadoci@gmail.com>
  19. * @author J0WI <J0WI@users.noreply.github.com>
  20. * @author Jakob Sack <mail@jakobsack.de>
  21. * @author jaltek <jaltek@mailbox.org>
  22. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  23. * @author Joachim Sokolowski <github@sokolowski.org>
  24. * @author Joas Schilling <coding@schilljs.com>
  25. * @author John Molakvoæ <skjnldsv@protonmail.com>
  26. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  27. * @author Jose Quinteiro <github@quinteiro.org>
  28. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  29. * @author Julius Härtl <jus@bitgrid.net>
  30. * @author Ko- <k.stoffelen@cs.ru.nl>
  31. * @author Lukas Reschke <lukas@statuscode.ch>
  32. * @author MartB <mart.b@outlook.de>
  33. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  34. * @author Morris Jobke <hey@morrisjobke.de>
  35. * @author Owen Winkler <a_github@midnightcircus.com>
  36. * @author Phil Davis <phil.davis@inf.org>
  37. * @author Ramiro Aparicio <rapariciog@gmail.com>
  38. * @author Robin Appelman <robin@icewind.nl>
  39. * @author Robin McCorkell <robin@mccorkell.me.uk>
  40. * @author Roeland Jago Douma <roeland@famdouma.nl>
  41. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  42. * @author Stefan Weil <sw@weilnetz.de>
  43. * @author Thomas Müller <thomas.mueller@tmit.eu>
  44. * @author Thomas Tanghus <thomas@tanghus.net>
  45. * @author Tobia De Koninck <tobia@ledfan.be>
  46. * @author Vincent Petry <vincent@nextcloud.com>
  47. * @author Volkan Gezer <volkangezer@gmail.com>
  48. *
  49. * @license AGPL-3.0
  50. *
  51. * This code is free software: you can redistribute it and/or modify
  52. * it under the terms of the GNU Affero General Public License, version 3,
  53. * as published by the Free Software Foundation.
  54. *
  55. * This program is distributed in the hope that it will be useful,
  56. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  57. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  58. * GNU Affero General Public License for more details.
  59. *
  60. * You should have received a copy of the GNU Affero General Public License, version 3,
  61. * along with this program. If not, see <http://www.gnu.org/licenses/>
  62. *
  63. */
  64. use OC\EventDispatcher\SymfonyAdapter;
  65. use OCP\EventDispatcher\IEventDispatcher;
  66. use OCP\Group\Events\UserRemovedEvent;
  67. use OCP\ILogger;
  68. use OCP\Server;
  69. use OCP\Share;
  70. use OC\Encryption\HookManager;
  71. use OC\Files\Filesystem;
  72. use OC\Share20\Hooks;
  73. use OCP\User\Events\UserChangedEvent;
  74. require_once 'public/Constants.php';
  75. /**
  76. * Class that is a namespace for all global OC variables
  77. * No, we can not put this class in its own file because it is used by
  78. * OC_autoload!
  79. */
  80. class OC {
  81. /**
  82. * Associative array for autoloading. classname => filename
  83. */
  84. public static $CLASSPATH = [];
  85. /**
  86. * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
  87. */
  88. public static $SERVERROOT = '';
  89. /**
  90. * the current request path relative to the Nextcloud root (e.g. files/index.php)
  91. */
  92. private static $SUBURI = '';
  93. /**
  94. * the Nextcloud root path for http requests (e.g. nextcloud/)
  95. */
  96. public static $WEBROOT = '';
  97. /**
  98. * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
  99. * web path in 'url'
  100. */
  101. public static $APPSROOTS = [];
  102. /**
  103. * @var string
  104. */
  105. public static $configDir;
  106. /**
  107. * requested app
  108. */
  109. public static $REQUESTEDAPP = '';
  110. /**
  111. * check if Nextcloud runs in cli mode
  112. */
  113. public static $CLI = false;
  114. /**
  115. * @var \OC\Autoloader $loader
  116. */
  117. public static $loader = null;
  118. /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
  119. public static $composerAutoloader = null;
  120. /**
  121. * @var \OC\Server
  122. */
  123. public static $server = null;
  124. /**
  125. * @var \OC\Config
  126. */
  127. private static $config = null;
  128. /**
  129. * @throws \RuntimeException when the 3rdparty directory is missing or
  130. * the app path list is empty or contains an invalid path
  131. */
  132. public static function initPaths() {
  133. if (defined('PHPUNIT_CONFIG_DIR')) {
  134. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  135. } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  136. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  137. } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
  138. self::$configDir = rtrim($dir, '/') . '/';
  139. } else {
  140. self::$configDir = OC::$SERVERROOT . '/config/';
  141. }
  142. self::$config = new \OC\Config(self::$configDir);
  143. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  144. /**
  145. * FIXME: The following lines are required because we can't yet instantiate
  146. * \OC::$server->getRequest() since \OC::$server does not yet exist.
  147. */
  148. $params = [
  149. 'server' => [
  150. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
  151. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
  152. ],
  153. ];
  154. $fakeRequest = new \OC\AppFramework\Http\Request(
  155. $params,
  156. new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
  157. new \OC\AllConfig(new \OC\SystemConfig(self::$config))
  158. );
  159. $scriptName = $fakeRequest->getScriptName();
  160. if (substr($scriptName, -1) == '/') {
  161. $scriptName .= 'index.php';
  162. //make sure suburi follows the same rules as scriptName
  163. if (substr(OC::$SUBURI, -9) != 'index.php') {
  164. if (substr(OC::$SUBURI, -1) != '/') {
  165. OC::$SUBURI = OC::$SUBURI . '/';
  166. }
  167. OC::$SUBURI = OC::$SUBURI . 'index.php';
  168. }
  169. }
  170. if (OC::$CLI) {
  171. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  172. } else {
  173. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  174. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  175. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  176. OC::$WEBROOT = '/' . OC::$WEBROOT;
  177. }
  178. } else {
  179. // The scriptName is not ending with OC::$SUBURI
  180. // This most likely means that we are calling from CLI.
  181. // However some cron jobs still need to generate
  182. // a web URL, so we use overwritewebroot as a fallback.
  183. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  184. }
  185. // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
  186. // slash which is required by URL generation.
  187. if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  188. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  189. header('Location: '.\OC::$WEBROOT.'/');
  190. exit();
  191. }
  192. }
  193. // search the apps folder
  194. $config_paths = self::$config->getValue('apps_paths', []);
  195. if (!empty($config_paths)) {
  196. foreach ($config_paths as $paths) {
  197. if (isset($paths['url']) && isset($paths['path'])) {
  198. $paths['url'] = rtrim($paths['url'], '/');
  199. $paths['path'] = rtrim($paths['path'], '/');
  200. OC::$APPSROOTS[] = $paths;
  201. }
  202. }
  203. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  204. OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
  205. }
  206. if (empty(OC::$APPSROOTS)) {
  207. throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
  208. . '. You can also configure the location in the config.php file.');
  209. }
  210. $paths = [];
  211. foreach (OC::$APPSROOTS as $path) {
  212. $paths[] = $path['path'];
  213. if (!is_dir($path['path'])) {
  214. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
  215. . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
  216. }
  217. }
  218. // set the right include path
  219. set_include_path(
  220. implode(PATH_SEPARATOR, $paths)
  221. );
  222. }
  223. public static function checkConfig() {
  224. $l = \OC::$server->getL10N('lib');
  225. // Create config if it does not already exist
  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. $urlGenerator = \OC::$server->getURLGenerator();
  235. if (self::$CLI) {
  236. echo $l->t('Cannot write into "config" directory!')."\n";
  237. echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
  238. echo "\n";
  239. echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
  240. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
  241. exit;
  242. } else {
  243. OC_Template::printErrorPage(
  244. $l->t('Cannot write into "config" directory!'),
  245. $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
  246. . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
  247. . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
  248. 503
  249. );
  250. }
  251. }
  252. }
  253. public static function checkInstalled(\OC\SystemConfig $systemConfig) {
  254. if (defined('OC_CONSOLE')) {
  255. return;
  256. }
  257. // Redirect to installer if not installed
  258. if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
  259. if (OC::$CLI) {
  260. throw new Exception('Not installed');
  261. } else {
  262. $url = OC::$WEBROOT . '/index.php';
  263. header('Location: ' . $url);
  264. }
  265. exit();
  266. }
  267. }
  268. public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
  269. // Allow ajax update script to execute without being stopped
  270. if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
  271. // send http status 503
  272. http_response_code(503);
  273. header('X-Nextcloud-Maintenance-Mode: 1');
  274. header('Retry-After: 120');
  275. // render error page
  276. $template = new OC_Template('', 'update.user', 'guest');
  277. \OCP\Util::addScript('core', 'maintenance');
  278. \OCP\Util::addStyle('core', 'guest');
  279. $template->printPage();
  280. die();
  281. }
  282. }
  283. /**
  284. * Prints the upgrade page
  285. *
  286. * @param \OC\SystemConfig $systemConfig
  287. */
  288. private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
  289. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  290. $tooBig = false;
  291. if (!$disableWebUpdater) {
  292. $apps = \OC::$server->getAppManager();
  293. if ($apps->isInstalled('user_ldap')) {
  294. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  295. $result = $qb->select($qb->func()->count('*', 'user_count'))
  296. ->from('ldap_user_mapping')
  297. ->execute();
  298. $row = $result->fetch();
  299. $result->closeCursor();
  300. $tooBig = ($row['user_count'] > 50);
  301. }
  302. if (!$tooBig && $apps->isInstalled('user_saml')) {
  303. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  304. $result = $qb->select($qb->func()->count('*', 'user_count'))
  305. ->from('user_saml_users')
  306. ->execute();
  307. $row = $result->fetch();
  308. $result->closeCursor();
  309. $tooBig = ($row['user_count'] > 50);
  310. }
  311. if (!$tooBig) {
  312. // count users
  313. $stats = \OC::$server->getUserManager()->countUsers();
  314. $totalUsers = array_sum($stats);
  315. $tooBig = ($totalUsers > 50);
  316. }
  317. }
  318. $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
  319. $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
  320. if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
  321. // send http status 503
  322. http_response_code(503);
  323. header('Retry-After: 120');
  324. // render error page
  325. $template = new OC_Template('', 'update.use-cli', 'guest');
  326. $template->assign('productName', 'nextcloud'); // for now
  327. $template->assign('version', OC_Util::getVersionString());
  328. $template->assign('tooBig', $tooBig);
  329. $template->printPage();
  330. die();
  331. }
  332. // check whether this is a core update or apps update
  333. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  334. $currentVersion = implode('.', \OCP\Util::getVersion());
  335. // if not a core upgrade, then it's apps upgrade
  336. $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
  337. $oldTheme = $systemConfig->getValue('theme');
  338. $systemConfig->setValue('theme', '');
  339. \OCP\Util::addScript('core', 'common');
  340. \OCP\Util::addScript('core', 'main');
  341. \OCP\Util::addTranslations('core');
  342. \OCP\Util::addScript('core', 'update');
  343. /** @var \OC\App\AppManager $appManager */
  344. $appManager = \OC::$server->getAppManager();
  345. $tmpl = new OC_Template('', 'update.admin', 'guest');
  346. $tmpl->assign('version', OC_Util::getVersionString());
  347. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  348. // get third party apps
  349. $ocVersion = \OCP\Util::getVersion();
  350. $ocVersion = implode('.', $ocVersion);
  351. $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
  352. $incompatibleShippedApps = [];
  353. foreach ($incompatibleApps as $appInfo) {
  354. if ($appManager->isShipped($appInfo['id'])) {
  355. $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
  356. }
  357. }
  358. if (!empty($incompatibleShippedApps)) {
  359. $l = \OC::$server->getL10N('core');
  360. $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
  361. throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
  362. }
  363. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  364. $tmpl->assign('incompatibleAppsList', $incompatibleApps);
  365. try {
  366. $defaults = new \OC_Defaults();
  367. $tmpl->assign('productName', $defaults->getName());
  368. } catch (Throwable $error) {
  369. $tmpl->assign('productName', 'Nextcloud');
  370. }
  371. $tmpl->assign('oldTheme', $oldTheme);
  372. $tmpl->printPage();
  373. }
  374. public static function initSession() {
  375. if (self::$server->getRequest()->getServerProtocol() === 'https') {
  376. ini_set('session.cookie_secure', 'true');
  377. }
  378. // prevents javascript from accessing php session cookies
  379. ini_set('session.cookie_httponly', 'true');
  380. // set the cookie path to the Nextcloud directory
  381. $cookie_path = OC::$WEBROOT ? : '/';
  382. ini_set('session.cookie_path', $cookie_path);
  383. // Let the session name be changed in the initSession Hook
  384. $sessionName = OC_Util::getInstanceId();
  385. try {
  386. // set the session name to the instance id - which is unique
  387. $session = new \OC\Session\Internal($sessionName);
  388. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  389. $session = $cryptoWrapper->wrapSession($session);
  390. self::$server->setSession($session);
  391. // if session can't be started break with http 500 error
  392. } catch (Exception $e) {
  393. \OC::$server->getLogger()->logException($e, ['app' => 'base']);
  394. //show the user a detailed error page
  395. OC_Template::printExceptionErrorPage($e, 500);
  396. die();
  397. }
  398. //try to set the session lifetime
  399. $sessionLifeTime = self::getSessionLifeTime();
  400. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  401. // session timeout
  402. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  403. if (isset($_COOKIE[session_name()])) {
  404. setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
  405. }
  406. \OC::$server->getUserSession()->logout();
  407. }
  408. if (!self::hasSessionRelaxedExpiry()) {
  409. $session->set('LAST_ACTIVITY', time());
  410. }
  411. $session->close();
  412. }
  413. /**
  414. * @return string
  415. */
  416. private static function getSessionLifeTime() {
  417. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  418. }
  419. /**
  420. * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
  421. */
  422. public static function hasSessionRelaxedExpiry(): bool {
  423. return \OC::$server->getConfig()->getSystemValue('session_relaxed_expiry', false);
  424. }
  425. /**
  426. * Try to set some values to the required Nextcloud default
  427. */
  428. public static function setRequiredIniValues() {
  429. @ini_set('default_charset', 'UTF-8');
  430. @ini_set('gd.jpeg_ignore_warning', '1');
  431. }
  432. /**
  433. * Send the same site cookies
  434. */
  435. private static function sendSameSiteCookies() {
  436. $cookieParams = session_get_cookie_params();
  437. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  438. $policies = [
  439. 'lax',
  440. 'strict',
  441. ];
  442. // Append __Host to the cookie if it meets the requirements
  443. $cookiePrefix = '';
  444. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  445. $cookiePrefix = '__Host-';
  446. }
  447. foreach ($policies as $policy) {
  448. header(
  449. sprintf(
  450. 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  451. $cookiePrefix,
  452. $policy,
  453. $cookieParams['path'],
  454. $policy
  455. ),
  456. false
  457. );
  458. }
  459. }
  460. /**
  461. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  462. * be set in every request if cookies are sent to add a second level of
  463. * defense against CSRF.
  464. *
  465. * If the cookie is not sent this will set the cookie and reload the page.
  466. * We use an additional cookie since we want to protect logout CSRF and
  467. * also we can't directly interfere with PHP's session mechanism.
  468. */
  469. private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
  470. $request = \OC::$server->getRequest();
  471. // Some user agents are notorious and don't really properly follow HTTP
  472. // specifications. For those, have an automated opt-out. Since the protection
  473. // for remote.php is applied in base.php as starting point we need to opt out
  474. // here.
  475. $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
  476. // Fallback, if csrf.optout is unset
  477. if (!is_array($incompatibleUserAgents)) {
  478. $incompatibleUserAgents = [
  479. // OS X Finder
  480. '/^WebDAVFS/',
  481. // Windows webdav drive
  482. '/^Microsoft-WebDAV-MiniRedir/',
  483. ];
  484. }
  485. if ($request->isUserAgent($incompatibleUserAgents)) {
  486. return;
  487. }
  488. if (count($_COOKIE) > 0) {
  489. $requestUri = $request->getScriptName();
  490. $processingScript = explode('/', $requestUri);
  491. $processingScript = $processingScript[count($processingScript) - 1];
  492. // index.php routes are handled in the middleware
  493. if ($processingScript === 'index.php') {
  494. return;
  495. }
  496. // All other endpoints require the lax and the strict cookie
  497. if (!$request->passesStrictCookieCheck()) {
  498. self::sendSameSiteCookies();
  499. // Debug mode gets access to the resources without strict cookie
  500. // due to the fact that the SabreDAV browser also lives there.
  501. if (!$config->getSystemValue('debug', false)) {
  502. http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
  503. exit();
  504. }
  505. }
  506. } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  507. self::sendSameSiteCookies();
  508. }
  509. }
  510. public static function init() {
  511. // calculate the root directories
  512. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  513. // register autoloader
  514. $loaderStart = microtime(true);
  515. require_once __DIR__ . '/autoloader.php';
  516. self::$loader = new \OC\Autoloader([
  517. OC::$SERVERROOT . '/lib/private/legacy',
  518. ]);
  519. if (defined('PHPUNIT_RUN')) {
  520. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  521. }
  522. spl_autoload_register([self::$loader, 'load']);
  523. $loaderEnd = microtime(true);
  524. self::$CLI = (php_sapi_name() == 'cli');
  525. // Add default composer PSR-4 autoloader
  526. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  527. try {
  528. self::initPaths();
  529. // setup 3rdparty autoloader
  530. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  531. if (!file_exists($vendorAutoLoad)) {
  532. 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".');
  533. }
  534. require_once $vendorAutoLoad;
  535. } catch (\RuntimeException $e) {
  536. if (!self::$CLI) {
  537. http_response_code(503);
  538. }
  539. // we can't use the template error page here, because this needs the
  540. // DI container which isn't available yet
  541. print($e->getMessage());
  542. exit();
  543. }
  544. // setup the basic server
  545. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  546. self::$server->boot();
  547. $eventLogger = \OC::$server->getEventLogger();
  548. $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  549. $eventLogger->start('boot', 'Initialize');
  550. // Override php.ini and log everything if we're troubleshooting
  551. if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
  552. error_reporting(E_ALL);
  553. }
  554. // Don't display errors and log them
  555. @ini_set('display_errors', '0');
  556. @ini_set('log_errors', '1');
  557. if (!date_default_timezone_set('UTC')) {
  558. throw new \RuntimeException('Could not set timezone to UTC');
  559. }
  560. //try to configure php to enable big file uploads.
  561. //this doesn´t work always depending on the webserver and php configuration.
  562. //Let´s try to overwrite some defaults if they are smaller than 1 hour
  563. if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
  564. @ini_set('max_execution_time', strval(3600));
  565. }
  566. if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
  567. @ini_set('max_input_time', strval(3600));
  568. }
  569. //try to set the maximum execution time to the largest time limit we have
  570. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  571. @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
  572. }
  573. self::setRequiredIniValues();
  574. self::handleAuthHeaders();
  575. $systemConfig = \OC::$server->get(\OC\SystemConfig::class);
  576. self::registerAutoloaderCache($systemConfig);
  577. // initialize intl fallback if necessary
  578. OC_Util::isSetLocaleWorking();
  579. $config = \OC::$server->get(\OCP\IConfig::class);
  580. if (!defined('PHPUNIT_RUN')) {
  581. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  582. $debug = $config->getSystemValue('debug', false);
  583. OC\Log\ErrorHandler::register($debug);
  584. }
  585. /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
  586. $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
  587. $bootstrapCoordinator->runInitialRegistration();
  588. $eventLogger->start('init_session', 'Initialize session');
  589. OC_App::loadApps(['session']);
  590. if (!self::$CLI) {
  591. self::initSession();
  592. }
  593. $eventLogger->end('init_session');
  594. self::checkConfig();
  595. self::checkInstalled($systemConfig);
  596. OC_Response::addSecurityHeaders();
  597. self::performSameSiteCookieProtection($config);
  598. if (!defined('OC_CONSOLE')) {
  599. $errors = OC_Util::checkServer($systemConfig);
  600. if (count($errors) > 0) {
  601. if (!self::$CLI) {
  602. http_response_code(503);
  603. OC_Util::addStyle('guest');
  604. try {
  605. OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
  606. exit;
  607. } catch (\Exception $e) {
  608. // In case any error happens when showing the error page, we simply fall back to posting the text.
  609. // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
  610. }
  611. }
  612. // Convert l10n string into regular string for usage in database
  613. $staticErrors = [];
  614. foreach ($errors as $error) {
  615. echo $error['error'] . "\n";
  616. echo $error['hint'] . "\n\n";
  617. $staticErrors[] = [
  618. 'error' => (string)$error['error'],
  619. 'hint' => (string)$error['hint'],
  620. ];
  621. }
  622. try {
  623. $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  624. } catch (\Exception $e) {
  625. echo('Writing to database failed');
  626. }
  627. exit(1);
  628. } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
  629. $config->deleteAppValue('core', 'cronErrors');
  630. }
  631. }
  632. // User and Groups
  633. if (!$systemConfig->getValue("installed", false)) {
  634. self::$server->getSession()->set('user_id', '');
  635. }
  636. OC_User::useBackend(new \OC\User\Database());
  637. \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
  638. // Subscribe to the hook
  639. \OCP\Util::connectHook(
  640. '\OCA\Files_Sharing\API\Server2Server',
  641. 'preLoginNameUsedAsUserName',
  642. '\OC\User\Database',
  643. 'preLoginNameUsedAsUserName'
  644. );
  645. //setup extra user backends
  646. if (!\OCP\Util::needUpgrade()) {
  647. OC_User::setupBackends();
  648. } else {
  649. // Run upgrades in incognito mode
  650. OC_User::setIncognitoMode(true);
  651. }
  652. self::registerCleanupHooks($systemConfig);
  653. self::registerShareHooks($systemConfig);
  654. self::registerEncryptionWrapperAndHooks();
  655. self::registerAccountHooks();
  656. self::registerResourceCollectionHooks();
  657. self::registerFileReferenceEventListener();
  658. self::registerAppRestrictionsHooks();
  659. // Make sure that the application class is not loaded before the database is setup
  660. if ($systemConfig->getValue("installed", false)) {
  661. OC_App::loadApp('settings');
  662. /* Build core application to make sure that listeners are registered */
  663. self::$server->get(\OC\Core\Application::class);
  664. }
  665. //make sure temporary files are cleaned up
  666. $tmpManager = \OC::$server->getTempManager();
  667. register_shutdown_function([$tmpManager, 'clean']);
  668. $lockProvider = \OC::$server->getLockingProvider();
  669. register_shutdown_function([$lockProvider, 'releaseAll']);
  670. // Check whether the sample configuration has been copied
  671. if ($systemConfig->getValue('copied_sample_config', false)) {
  672. $l = \OC::$server->getL10N('lib');
  673. OC_Template::printErrorPage(
  674. $l->t('Sample configuration detected'),
  675. $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'),
  676. 503
  677. );
  678. return;
  679. }
  680. $request = \OC::$server->getRequest();
  681. $host = $request->getInsecureServerHost();
  682. /**
  683. * if the host passed in headers isn't trusted
  684. * FIXME: Should not be in here at all :see_no_evil:
  685. */
  686. if (!OC::$CLI
  687. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  688. && $config->getSystemValue('installed', false)
  689. ) {
  690. // Allow access to CSS resources
  691. $isScssRequest = false;
  692. if (strpos($request->getPathInfo(), '/css/') === 0) {
  693. $isScssRequest = true;
  694. }
  695. if (substr($request->getRequestUri(), -11) === '/status.php') {
  696. http_response_code(400);
  697. header('Content-Type: application/json');
  698. echo '{"error": "Trusted domain error.", "code": 15}';
  699. exit();
  700. }
  701. if (!$isScssRequest) {
  702. http_response_code(400);
  703. \OC::$server->getLogger()->info(
  704. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  705. [
  706. 'app' => 'core',
  707. 'remoteAddress' => $request->getRemoteAddress(),
  708. 'host' => $host,
  709. ]
  710. );
  711. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  712. $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
  713. $tmpl->printPage();
  714. exit();
  715. }
  716. }
  717. $eventLogger->end('boot');
  718. $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
  719. $eventLogger->start('runtime', 'Runtime');
  720. $eventLogger->start('request', 'Full request after boot');
  721. register_shutdown_function(function () use ($eventLogger) {
  722. $eventLogger->end('request');
  723. });
  724. }
  725. /**
  726. * register hooks for the cleanup of cache and bruteforce protection
  727. */
  728. public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
  729. //don't try to do this before we are properly setup
  730. if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
  731. // NOTE: This will be replaced to use OCP
  732. $userSession = self::$server->getUserSession();
  733. $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
  734. if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
  735. // reset brute force delay for this IP address and username
  736. $uid = \OC::$server->getUserSession()->getUser()->getUID();
  737. $request = \OC::$server->getRequest();
  738. $throttler = \OC::$server->getBruteForceThrottler();
  739. $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
  740. }
  741. try {
  742. $cache = new \OC\Cache\File();
  743. $cache->gc();
  744. } catch (\OC\ServerNotAvailableException $e) {
  745. // not a GC exception, pass it on
  746. throw $e;
  747. } catch (\OC\ForbiddenException $e) {
  748. // filesystem blocked for this request, ignore
  749. } catch (\Exception $e) {
  750. // a GC exception should not prevent users from using OC,
  751. // so log the exception
  752. \OC::$server->getLogger()->logException($e, [
  753. 'message' => 'Exception when running cache gc.',
  754. 'level' => ILogger::WARN,
  755. 'app' => 'core',
  756. ]);
  757. }
  758. });
  759. }
  760. }
  761. private static function registerEncryptionWrapperAndHooks() {
  762. $manager = self::$server->getEncryptionManager();
  763. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  764. $enabled = $manager->isEnabled();
  765. if ($enabled) {
  766. \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
  767. \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
  768. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
  769. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
  770. }
  771. }
  772. private static function registerAccountHooks() {
  773. /** @var IEventDispatcher $dispatcher */
  774. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  775. $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
  776. }
  777. private static function registerAppRestrictionsHooks() {
  778. /** @var \OC\Group\Manager $groupManager */
  779. $groupManager = self::$server->query(\OCP\IGroupManager::class);
  780. $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
  781. $appManager = self::$server->getAppManager();
  782. $apps = $appManager->getEnabledAppsForGroup($group);
  783. foreach ($apps as $appId) {
  784. $restrictions = $appManager->getAppRestriction($appId);
  785. if (empty($restrictions)) {
  786. continue;
  787. }
  788. $key = array_search($group->getGID(), $restrictions);
  789. unset($restrictions[$key]);
  790. $restrictions = array_values($restrictions);
  791. if (empty($restrictions)) {
  792. $appManager->disableApp($appId);
  793. } else {
  794. $appManager->enableAppForGroups($appId, $restrictions);
  795. }
  796. }
  797. });
  798. }
  799. private static function registerResourceCollectionHooks() {
  800. \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
  801. }
  802. private static function registerFileReferenceEventListener() {
  803. \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
  804. }
  805. /**
  806. * register hooks for sharing
  807. */
  808. public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
  809. if ($systemConfig->getValue('installed')) {
  810. OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
  811. OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
  812. /** @var IEventDispatcher $dispatcher */
  813. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  814. $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
  815. }
  816. }
  817. protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
  818. // The class loader takes an optional low-latency cache, which MUST be
  819. // namespaced. The instanceid is used for namespacing, but might be
  820. // unavailable at this point. Furthermore, it might not be possible to
  821. // generate an instanceid via \OC_Util::getInstanceId() because the
  822. // config file may not be writable. As such, we only register a class
  823. // loader cache if instanceid is available without trying to create one.
  824. $instanceId = $systemConfig->getValue('instanceid', null);
  825. if ($instanceId) {
  826. try {
  827. $memcacheFactory = \OC::$server->getMemCacheFactory();
  828. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  829. } catch (\Exception $ex) {
  830. }
  831. }
  832. }
  833. /**
  834. * Handle the request
  835. */
  836. public static function handleRequest() {
  837. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  838. $systemConfig = \OC::$server->getSystemConfig();
  839. // Check if Nextcloud is installed or in maintenance (update) mode
  840. if (!$systemConfig->getValue('installed', false)) {
  841. \OC::$server->getSession()->clear();
  842. $setupHelper = new OC\Setup(
  843. $systemConfig,
  844. \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
  845. \OC::$server->getL10N('lib'),
  846. \OC::$server->query(\OCP\Defaults::class),
  847. \OC::$server->get(\Psr\Log\LoggerInterface::class),
  848. \OC::$server->getSecureRandom(),
  849. \OC::$server->query(\OC\Installer::class)
  850. );
  851. $controller = new OC\Core\Controller\SetupController($setupHelper);
  852. $controller->run($_POST);
  853. exit();
  854. }
  855. $request = \OC::$server->getRequest();
  856. $requestPath = $request->getRawPathInfo();
  857. if ($requestPath === '/heartbeat') {
  858. return;
  859. }
  860. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  861. self::checkMaintenanceMode($systemConfig);
  862. if (\OCP\Util::needUpgrade()) {
  863. if (function_exists('opcache_reset')) {
  864. opcache_reset();
  865. }
  866. if (!((bool) $systemConfig->getValue('maintenance', false))) {
  867. self::printUpgradePage($systemConfig);
  868. exit();
  869. }
  870. }
  871. }
  872. // emergency app disabling
  873. if ($requestPath === '/disableapp'
  874. && $request->getMethod() === 'POST'
  875. && ((array)$request->getParam('appid')) !== ''
  876. ) {
  877. \OC_JSON::callCheck();
  878. \OC_JSON::checkAdminUser();
  879. $appIds = (array)$request->getParam('appid');
  880. foreach ($appIds as $appId) {
  881. $appId = \OC_App::cleanAppId($appId);
  882. \OC::$server->getAppManager()->disableApp($appId);
  883. }
  884. \OC_JSON::success();
  885. exit();
  886. }
  887. // Always load authentication apps
  888. OC_App::loadApps(['authentication']);
  889. // Load minimum set of apps
  890. if (!\OCP\Util::needUpgrade()
  891. && !((bool) $systemConfig->getValue('maintenance', false))) {
  892. // For logged-in users: Load everything
  893. if (\OC::$server->getUserSession()->isLoggedIn()) {
  894. OC_App::loadApps();
  895. } else {
  896. // For guests: Load only filesystem and logging
  897. OC_App::loadApps(['filesystem', 'logging']);
  898. // Don't try to login when a client is trying to get a OAuth token.
  899. // OAuth needs to support basic auth too, so the login is not valid
  900. // inside Nextcloud and the Login exception would ruin it.
  901. if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
  902. self::handleLogin($request);
  903. }
  904. }
  905. }
  906. if (!self::$CLI) {
  907. try {
  908. if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
  909. OC_App::loadApps(['filesystem', 'logging']);
  910. OC_App::loadApps();
  911. }
  912. OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
  913. return;
  914. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  915. //header('HTTP/1.0 404 Not Found');
  916. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  917. http_response_code(405);
  918. return;
  919. }
  920. }
  921. // Handle WebDAV
  922. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  923. // not allowed any more to prevent people
  924. // mounting this root directly.
  925. // Users need to mount remote.php/webdav instead.
  926. http_response_code(405);
  927. return;
  928. }
  929. // Handle requests for JSON or XML
  930. $acceptHeader = $request->getHeader('Accept');
  931. if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
  932. http_response_code(404);
  933. return;
  934. }
  935. // Handle resources that can't be found
  936. // This prevents browsers from redirecting to the default page and then
  937. // attempting to parse HTML as CSS and similar.
  938. $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
  939. if (in_array($destinationHeader, ['font', 'script', 'style'])) {
  940. http_response_code(404);
  941. return;
  942. }
  943. // Someone is logged in
  944. if (\OC::$server->getUserSession()->isLoggedIn()) {
  945. OC_App::loadApps();
  946. OC_User::setupBackends();
  947. OC_Util::setupFS();
  948. header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
  949. } else {
  950. // Not handled and not logged in
  951. header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  952. }
  953. }
  954. /**
  955. * Check login: apache auth, auth token, basic auth
  956. *
  957. * @param OCP\IRequest $request
  958. * @return boolean
  959. */
  960. public static function handleLogin(OCP\IRequest $request) {
  961. $userSession = self::$server->getUserSession();
  962. if (OC_User::handleApacheAuth()) {
  963. return true;
  964. }
  965. if ($userSession->tryTokenLogin($request)) {
  966. return true;
  967. }
  968. if (isset($_COOKIE['nc_username'])
  969. && isset($_COOKIE['nc_token'])
  970. && isset($_COOKIE['nc_session_id'])
  971. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  972. return true;
  973. }
  974. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  975. return true;
  976. }
  977. return false;
  978. }
  979. protected static function handleAuthHeaders() {
  980. //copy http auth headers for apache+php-fcgid work around
  981. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  982. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  983. }
  984. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  985. $vars = [
  986. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  987. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  988. ];
  989. foreach ($vars as $var) {
  990. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  991. $credentials = explode(':', base64_decode($matches[1]), 2);
  992. if (count($credentials) === 2) {
  993. $_SERVER['PHP_AUTH_USER'] = $credentials[0];
  994. $_SERVER['PHP_AUTH_PW'] = $credentials[1];
  995. break;
  996. }
  997. }
  998. }
  999. }
  1000. }
  1001. OC::init();