1
0

base.php 39 KB

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