1
0

base.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. // render error page
  263. $template = new OC_Template('', 'update.use-cli', 'guest');
  264. $template->assign('productName', 'nextcloud'); // for now
  265. $template->assign('version', OC_Util::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', OC_Util::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. // set the session name to the instance id - which is unique
  342. $session = new \OC\Session\Internal(
  343. $sessionName,
  344. logger('core'),
  345. );
  346. $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
  347. $session = $cryptoWrapper->wrapSession($session);
  348. self::$server->setSession($session);
  349. // if session can't be started break with http 500 error
  350. } catch (Exception $e) {
  351. Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
  352. //show the user a detailed error page
  353. OC_Template::printExceptionErrorPage($e, 500);
  354. die();
  355. }
  356. //try to set the session lifetime
  357. $sessionLifeTime = self::getSessionLifeTime();
  358. // session timeout
  359. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  360. if (isset($_COOKIE[session_name()])) {
  361. setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
  362. }
  363. Server::get(IUserSession::class)->logout();
  364. }
  365. if (!self::hasSessionRelaxedExpiry()) {
  366. $session->set('LAST_ACTIVITY', time());
  367. }
  368. $session->close();
  369. }
  370. private static function getSessionLifeTime(): int {
  371. return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
  372. }
  373. /**
  374. * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
  375. */
  376. public static function hasSessionRelaxedExpiry(): bool {
  377. return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
  378. }
  379. /**
  380. * Try to set some values to the required Nextcloud default
  381. */
  382. public static function setRequiredIniValues(): void {
  383. @ini_set('default_charset', 'UTF-8');
  384. @ini_set('gd.jpeg_ignore_warning', '1');
  385. }
  386. /**
  387. * Send the same site cookies
  388. */
  389. private static function sendSameSiteCookies(): void {
  390. $cookieParams = session_get_cookie_params();
  391. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  392. $policies = [
  393. 'lax',
  394. 'strict',
  395. ];
  396. // Append __Host to the cookie if it meets the requirements
  397. $cookiePrefix = '';
  398. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  399. $cookiePrefix = '__Host-';
  400. }
  401. foreach ($policies as $policy) {
  402. header(
  403. sprintf(
  404. 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  405. $cookiePrefix,
  406. $policy,
  407. $cookieParams['path'],
  408. $policy
  409. ),
  410. false
  411. );
  412. }
  413. }
  414. /**
  415. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  416. * be set in every request if cookies are sent to add a second level of
  417. * defense against CSRF.
  418. *
  419. * If the cookie is not sent this will set the cookie and reload the page.
  420. * We use an additional cookie since we want to protect logout CSRF and
  421. * also we can't directly interfere with PHP's session mechanism.
  422. */
  423. private static function performSameSiteCookieProtection(\OCP\IConfig $config): void {
  424. $request = Server::get(IRequest::class);
  425. // Some user agents are notorious and don't really properly follow HTTP
  426. // specifications. For those, have an automated opt-out. Since the protection
  427. // for remote.php is applied in base.php as starting point we need to opt out
  428. // here.
  429. $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
  430. // Fallback, if csrf.optout is unset
  431. if (!is_array($incompatibleUserAgents)) {
  432. $incompatibleUserAgents = [
  433. // OS X Finder
  434. '/^WebDAVFS/',
  435. // Windows webdav drive
  436. '/^Microsoft-WebDAV-MiniRedir/',
  437. ];
  438. }
  439. if ($request->isUserAgent($incompatibleUserAgents)) {
  440. return;
  441. }
  442. if (count($_COOKIE) > 0) {
  443. $requestUri = $request->getScriptName();
  444. $processingScript = explode('/', $requestUri);
  445. $processingScript = $processingScript[count($processingScript) - 1];
  446. // index.php routes are handled in the middleware
  447. if ($processingScript === 'index.php') {
  448. return;
  449. }
  450. // All other endpoints require the lax and the strict cookie
  451. if (!$request->passesStrictCookieCheck()) {
  452. logger('core')->warning('Request does not pass strict cookie check');
  453. self::sendSameSiteCookies();
  454. // Debug mode gets access to the resources without strict cookie
  455. // due to the fact that the SabreDAV browser also lives there.
  456. if (!$config->getSystemValueBool('debug', false)) {
  457. http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
  458. header('Content-Type: application/json');
  459. echo json_encode(['error' => 'Strict Cookie has not been found in request']);
  460. exit();
  461. }
  462. }
  463. } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  464. self::sendSameSiteCookies();
  465. }
  466. }
  467. public static function init(): void {
  468. // prevent any XML processing from loading external entities
  469. libxml_set_external_entity_loader(static function () {
  470. return null;
  471. });
  472. // calculate the root directories
  473. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  474. // register autoloader
  475. $loaderStart = microtime(true);
  476. require_once __DIR__ . '/autoloader.php';
  477. self::$loader = new \OC\Autoloader([
  478. OC::$SERVERROOT . '/lib/private/legacy',
  479. ]);
  480. if (defined('PHPUNIT_RUN')) {
  481. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  482. }
  483. spl_autoload_register([self::$loader, 'load']);
  484. $loaderEnd = microtime(true);
  485. self::$CLI = (php_sapi_name() == 'cli');
  486. // Add default composer PSR-4 autoloader, ensure apcu to be disabled
  487. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  488. self::$composerAutoloader->setApcuPrefix(null);
  489. try {
  490. self::initPaths();
  491. // setup 3rdparty autoloader
  492. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  493. if (!file_exists($vendorAutoLoad)) {
  494. 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".');
  495. }
  496. require_once $vendorAutoLoad;
  497. } catch (\RuntimeException $e) {
  498. if (!self::$CLI) {
  499. http_response_code(503);
  500. }
  501. // we can't use the template error page here, because this needs the
  502. // DI container which isn't available yet
  503. print($e->getMessage());
  504. exit();
  505. }
  506. // setup the basic server
  507. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  508. self::$server->boot();
  509. if (self::$CLI && in_array('--'.\OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
  510. \OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
  511. }
  512. $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
  513. $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  514. $eventLogger->start('boot', 'Initialize');
  515. // Override php.ini and log everything if we're troubleshooting
  516. if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
  517. error_reporting(E_ALL);
  518. }
  519. // Don't display errors and log them
  520. @ini_set('display_errors', '0');
  521. @ini_set('log_errors', '1');
  522. if (!date_default_timezone_set('UTC')) {
  523. throw new \RuntimeException('Could not set timezone to UTC');
  524. }
  525. //try to configure php to enable big file uploads.
  526. //this doesn´t work always depending on the webserver and php configuration.
  527. //Let´s try to overwrite some defaults if they are smaller than 1 hour
  528. if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
  529. @ini_set('max_execution_time', strval(3600));
  530. }
  531. if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
  532. @ini_set('max_input_time', strval(3600));
  533. }
  534. //try to set the maximum execution time to the largest time limit we have
  535. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  536. @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
  537. }
  538. self::setRequiredIniValues();
  539. self::handleAuthHeaders();
  540. $systemConfig = Server::get(\OC\SystemConfig::class);
  541. self::registerAutoloaderCache($systemConfig);
  542. // initialize intl fallback if necessary
  543. OC_Util::isSetLocaleWorking();
  544. $config = Server::get(\OCP\IConfig::class);
  545. if (!defined('PHPUNIT_RUN')) {
  546. $errorHandler = new OC\Log\ErrorHandler(
  547. \OCP\Server::get(\Psr\Log\LoggerInterface::class),
  548. );
  549. $exceptionHandler = [$errorHandler, 'onException'];
  550. if ($config->getSystemValueBool('debug', false)) {
  551. set_error_handler([$errorHandler, 'onAll'], E_ALL);
  552. if (\OC::$CLI) {
  553. $exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
  554. }
  555. } else {
  556. set_error_handler([$errorHandler, 'onError']);
  557. }
  558. register_shutdown_function([$errorHandler, 'onShutdown']);
  559. set_exception_handler($exceptionHandler);
  560. }
  561. /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
  562. $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
  563. $bootstrapCoordinator->runInitialRegistration();
  564. $eventLogger->start('init_session', 'Initialize session');
  565. OC_App::loadApps(['session']);
  566. if (!self::$CLI) {
  567. self::initSession();
  568. }
  569. $eventLogger->end('init_session');
  570. self::checkConfig();
  571. self::checkInstalled($systemConfig);
  572. OC_Response::addSecurityHeaders();
  573. self::performSameSiteCookieProtection($config);
  574. if (!defined('OC_CONSOLE')) {
  575. $errors = OC_Util::checkServer($systemConfig);
  576. if (count($errors) > 0) {
  577. if (!self::$CLI) {
  578. http_response_code(503);
  579. OC_Util::addStyle('guest');
  580. try {
  581. OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
  582. exit;
  583. } catch (\Exception $e) {
  584. // In case any error happens when showing the error page, we simply fall back to posting the text.
  585. // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
  586. }
  587. }
  588. // Convert l10n string into regular string for usage in database
  589. $staticErrors = [];
  590. foreach ($errors as $error) {
  591. echo $error['error'] . "\n";
  592. echo $error['hint'] . "\n\n";
  593. $staticErrors[] = [
  594. 'error' => (string)$error['error'],
  595. 'hint' => (string)$error['hint'],
  596. ];
  597. }
  598. try {
  599. $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  600. } catch (\Exception $e) {
  601. echo('Writing to database failed');
  602. }
  603. exit(1);
  604. } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
  605. $config->deleteAppValue('core', 'cronErrors');
  606. }
  607. }
  608. // User and Groups
  609. if (!$systemConfig->getValue("installed", false)) {
  610. self::$server->getSession()->set('user_id', '');
  611. }
  612. OC_User::useBackend(new \OC\User\Database());
  613. Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
  614. // Subscribe to the hook
  615. \OCP\Util::connectHook(
  616. '\OCA\Files_Sharing\API\Server2Server',
  617. 'preLoginNameUsedAsUserName',
  618. '\OC\User\Database',
  619. 'preLoginNameUsedAsUserName'
  620. );
  621. //setup extra user backends
  622. if (!\OCP\Util::needUpgrade()) {
  623. OC_User::setupBackends();
  624. } else {
  625. // Run upgrades in incognito mode
  626. OC_User::setIncognitoMode(true);
  627. }
  628. self::registerCleanupHooks($systemConfig);
  629. self::registerShareHooks($systemConfig);
  630. self::registerEncryptionWrapperAndHooks();
  631. self::registerAccountHooks();
  632. self::registerResourceCollectionHooks();
  633. self::registerFileReferenceEventListener();
  634. self::registerRenderReferenceEventListener();
  635. self::registerAppRestrictionsHooks();
  636. // Make sure that the application class is not loaded before the database is setup
  637. if ($systemConfig->getValue("installed", false)) {
  638. OC_App::loadApp('settings');
  639. /* Build core application to make sure that listeners are registered */
  640. Server::get(\OC\Core\Application::class);
  641. }
  642. //make sure temporary files are cleaned up
  643. $tmpManager = Server::get(\OCP\ITempManager::class);
  644. register_shutdown_function([$tmpManager, 'clean']);
  645. $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
  646. register_shutdown_function([$lockProvider, 'releaseAll']);
  647. // Check whether the sample configuration has been copied
  648. if ($systemConfig->getValue('copied_sample_config', false)) {
  649. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  650. OC_Template::printErrorPage(
  651. $l->t('Sample configuration detected'),
  652. $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'),
  653. 503
  654. );
  655. return;
  656. }
  657. $request = Server::get(IRequest::class);
  658. $host = $request->getInsecureServerHost();
  659. /**
  660. * if the host passed in headers isn't trusted
  661. * FIXME: Should not be in here at all :see_no_evil:
  662. */
  663. if (!OC::$CLI
  664. && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
  665. && $config->getSystemValueBool('installed', false)
  666. ) {
  667. // Allow access to CSS resources
  668. $isScssRequest = false;
  669. if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
  670. $isScssRequest = true;
  671. }
  672. if (substr($request->getRequestUri(), -11) === '/status.php') {
  673. http_response_code(400);
  674. header('Content-Type: application/json');
  675. echo '{"error": "Trusted domain error.", "code": 15}';
  676. exit();
  677. }
  678. if (!$isScssRequest) {
  679. http_response_code(400);
  680. Server::get(LoggerInterface::class)->info(
  681. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  682. [
  683. 'app' => 'core',
  684. 'remoteAddress' => $request->getRemoteAddress(),
  685. 'host' => $host,
  686. ]
  687. );
  688. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  689. $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
  690. $tmpl->printPage();
  691. exit();
  692. }
  693. }
  694. $eventLogger->end('boot');
  695. $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
  696. $eventLogger->start('runtime', 'Runtime');
  697. $eventLogger->start('request', 'Full request after boot');
  698. register_shutdown_function(function () use ($eventLogger) {
  699. $eventLogger->end('request');
  700. });
  701. }
  702. /**
  703. * register hooks for the cleanup of cache and bruteforce protection
  704. */
  705. public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
  706. //don't try to do this before we are properly setup
  707. if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
  708. // NOTE: This will be replaced to use OCP
  709. $userSession = Server::get(\OC\User\Session::class);
  710. $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
  711. if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
  712. // reset brute force delay for this IP address and username
  713. $uid = $userSession->getUser()->getUID();
  714. $request = Server::get(IRequest::class);
  715. $throttler = Server::get(IThrottler::class);
  716. $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
  717. }
  718. try {
  719. $cache = new \OC\Cache\File();
  720. $cache->gc();
  721. } catch (\OC\ServerNotAvailableException $e) {
  722. // not a GC exception, pass it on
  723. throw $e;
  724. } catch (\OC\ForbiddenException $e) {
  725. // filesystem blocked for this request, ignore
  726. } catch (\Exception $e) {
  727. // a GC exception should not prevent users from using OC,
  728. // so log the exception
  729. Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
  730. 'app' => 'core',
  731. 'exception' => $e,
  732. ]);
  733. }
  734. });
  735. }
  736. }
  737. private static function registerEncryptionWrapperAndHooks(): void {
  738. $manager = Server::get(\OCP\Encryption\IManager::class);
  739. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  740. $enabled = $manager->isEnabled();
  741. if ($enabled) {
  742. \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
  743. \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
  744. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
  745. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
  746. }
  747. }
  748. private static function registerAccountHooks(): void {
  749. /** @var IEventDispatcher $dispatcher */
  750. $dispatcher = Server::get(IEventDispatcher::class);
  751. $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
  752. }
  753. private static function registerAppRestrictionsHooks(): void {
  754. /** @var \OC\Group\Manager $groupManager */
  755. $groupManager = Server::get(\OCP\IGroupManager::class);
  756. $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
  757. $appManager = Server::get(\OCP\App\IAppManager::class);
  758. $apps = $appManager->getEnabledAppsForGroup($group);
  759. foreach ($apps as $appId) {
  760. $restrictions = $appManager->getAppRestriction($appId);
  761. if (empty($restrictions)) {
  762. continue;
  763. }
  764. $key = array_search($group->getGID(), $restrictions);
  765. unset($restrictions[$key]);
  766. $restrictions = array_values($restrictions);
  767. if (empty($restrictions)) {
  768. $appManager->disableApp($appId);
  769. } else {
  770. $appManager->enableAppForGroups($appId, $restrictions);
  771. }
  772. }
  773. });
  774. }
  775. private static function registerResourceCollectionHooks(): void {
  776. \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
  777. }
  778. private static function registerFileReferenceEventListener(): void {
  779. \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
  780. }
  781. private static function registerRenderReferenceEventListener() {
  782. \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
  783. }
  784. /**
  785. * register hooks for sharing
  786. */
  787. public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
  788. if ($systemConfig->getValue('installed')) {
  789. OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
  790. OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
  791. /** @var IEventDispatcher $dispatcher */
  792. $dispatcher = Server::get(IEventDispatcher::class);
  793. $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
  794. }
  795. }
  796. protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
  797. // The class loader takes an optional low-latency cache, which MUST be
  798. // namespaced. The instanceid is used for namespacing, but might be
  799. // unavailable at this point. Furthermore, it might not be possible to
  800. // generate an instanceid via \OC_Util::getInstanceId() because the
  801. // config file may not be writable. As such, we only register a class
  802. // loader cache if instanceid is available without trying to create one.
  803. $instanceId = $systemConfig->getValue('instanceid', null);
  804. if ($instanceId) {
  805. try {
  806. $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
  807. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  808. } catch (\Exception $ex) {
  809. }
  810. }
  811. }
  812. /**
  813. * Handle the request
  814. */
  815. public static function handleRequest(): void {
  816. Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
  817. $systemConfig = Server::get(\OC\SystemConfig::class);
  818. // Check if Nextcloud is installed or in maintenance (update) mode
  819. if (!$systemConfig->getValue('installed', false)) {
  820. \OC::$server->getSession()->clear();
  821. $controller = Server::get(\OC\Core\Controller\SetupController::class);
  822. $controller->run($_POST);
  823. exit();
  824. }
  825. $request = Server::get(IRequest::class);
  826. $requestPath = $request->getRawPathInfo();
  827. if ($requestPath === '/heartbeat') {
  828. return;
  829. }
  830. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  831. self::checkMaintenanceMode($systemConfig);
  832. if (\OCP\Util::needUpgrade()) {
  833. if (function_exists('opcache_reset')) {
  834. opcache_reset();
  835. }
  836. if (!((bool) $systemConfig->getValue('maintenance', false))) {
  837. self::printUpgradePage($systemConfig);
  838. exit();
  839. }
  840. }
  841. }
  842. // Always load authentication apps
  843. OC_App::loadApps(['authentication']);
  844. OC_App::loadApps(['extended_authentication']);
  845. // Load minimum set of apps
  846. if (!\OCP\Util::needUpgrade()
  847. && !((bool) $systemConfig->getValue('maintenance', false))) {
  848. // For logged-in users: Load everything
  849. if (Server::get(IUserSession::class)->isLoggedIn()) {
  850. OC_App::loadApps();
  851. } else {
  852. // For guests: Load only filesystem and logging
  853. OC_App::loadApps(['filesystem', 'logging']);
  854. // Don't try to login when a client is trying to get a OAuth token.
  855. // OAuth needs to support basic auth too, so the login is not valid
  856. // inside Nextcloud and the Login exception would ruin it.
  857. if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
  858. self::handleLogin($request);
  859. }
  860. }
  861. }
  862. if (!self::$CLI) {
  863. try {
  864. if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
  865. OC_App::loadApps(['filesystem', 'logging']);
  866. OC_App::loadApps();
  867. }
  868. Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
  869. return;
  870. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  871. //header('HTTP/1.0 404 Not Found');
  872. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  873. http_response_code(405);
  874. return;
  875. }
  876. }
  877. // Handle WebDAV
  878. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  879. // not allowed any more to prevent people
  880. // mounting this root directly.
  881. // Users need to mount remote.php/webdav instead.
  882. http_response_code(405);
  883. return;
  884. }
  885. // Handle requests for JSON or XML
  886. $acceptHeader = $request->getHeader('Accept');
  887. if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
  888. http_response_code(404);
  889. return;
  890. }
  891. // Handle resources that can't be found
  892. // This prevents browsers from redirecting to the default page and then
  893. // attempting to parse HTML as CSS and similar.
  894. $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
  895. if (in_array($destinationHeader, ['font', 'script', 'style'])) {
  896. http_response_code(404);
  897. return;
  898. }
  899. // Redirect to the default app or login only as an entry point
  900. if ($requestPath === '') {
  901. // Someone is logged in
  902. if (Server::get(IUserSession::class)->isLoggedIn()) {
  903. header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
  904. } else {
  905. // Not handled and not logged in
  906. header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
  907. }
  908. return;
  909. }
  910. try {
  911. Server::get(\OC\Route\Router::class)->match('/error/404');
  912. } catch (\Exception $e) {
  913. if (!$e instanceof MethodNotAllowedException) {
  914. logger('core')->emergency($e->getMessage(), ['exception' => $e]);
  915. }
  916. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  917. OC_Template::printErrorPage(
  918. '404',
  919. $l->t('The page could not be found on the server.'),
  920. 404
  921. );
  922. }
  923. }
  924. /**
  925. * Check login: apache auth, auth token, basic auth
  926. */
  927. public static function handleLogin(OCP\IRequest $request): bool {
  928. if ($request->getHeader('X-Nextcloud-Federation')) {
  929. return false;
  930. }
  931. $userSession = Server::get(\OC\User\Session::class);
  932. if (OC_User::handleApacheAuth()) {
  933. return true;
  934. }
  935. if (self::tryAppAPILogin($request)) {
  936. return true;
  937. }
  938. if ($userSession->tryTokenLogin($request)) {
  939. return true;
  940. }
  941. if (isset($_COOKIE['nc_username'])
  942. && isset($_COOKIE['nc_token'])
  943. && isset($_COOKIE['nc_session_id'])
  944. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  945. return true;
  946. }
  947. if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
  948. return true;
  949. }
  950. return false;
  951. }
  952. protected static function handleAuthHeaders(): void {
  953. //copy http auth headers for apache+php-fcgid work around
  954. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  955. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  956. }
  957. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  958. $vars = [
  959. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  960. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  961. ];
  962. foreach ($vars as $var) {
  963. if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  964. $credentials = explode(':', base64_decode($matches[1]), 2);
  965. if (count($credentials) === 2) {
  966. $_SERVER['PHP_AUTH_USER'] = $credentials[0];
  967. $_SERVER['PHP_AUTH_PW'] = $credentials[1];
  968. break;
  969. }
  970. }
  971. }
  972. }
  973. protected static function tryAppAPILogin(OCP\IRequest $request): bool {
  974. $appManager = Server::get(OCP\App\IAppManager::class);
  975. if (!$request->getHeader('AUTHORIZATION-APP-API')) {
  976. return false;
  977. }
  978. if (!$appManager->isInstalled('app_api')) {
  979. return false;
  980. }
  981. try {
  982. $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
  983. return $appAPIService->validateExAppRequestToNC($request);
  984. } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
  985. return false;
  986. }
  987. }
  988. }
  989. OC::init();