base.php 39 KB

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