1
0

AppManager.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\App;
  8. use InvalidArgumentException;
  9. use OC\AppConfig;
  10. use OC\AppFramework\Bootstrap\Coordinator;
  11. use OC\ServerNotAvailableException;
  12. use OCP\Activity\IManager as IActivityManager;
  13. use OCP\App\AppPathNotFoundException;
  14. use OCP\App\Events\AppDisableEvent;
  15. use OCP\App\Events\AppEnableEvent;
  16. use OCP\App\IAppManager;
  17. use OCP\App\ManagerEvent;
  18. use OCP\Collaboration\AutoComplete\IManager as IAutoCompleteManager;
  19. use OCP\Collaboration\Collaborators\ISearch as ICollaboratorSearch;
  20. use OCP\Diagnostics\IEventLogger;
  21. use OCP\EventDispatcher\IEventDispatcher;
  22. use OCP\ICacheFactory;
  23. use OCP\IConfig;
  24. use OCP\IGroup;
  25. use OCP\IGroupManager;
  26. use OCP\IURLGenerator;
  27. use OCP\IUser;
  28. use OCP\IUserSession;
  29. use OCP\Settings\IManager as ISettingsManager;
  30. use Psr\Log\LoggerInterface;
  31. class AppManager implements IAppManager {
  32. /**
  33. * Apps with these types can not be enabled for certain groups only
  34. * @var string[]
  35. */
  36. protected $protectedAppTypes = [
  37. 'filesystem',
  38. 'prelogin',
  39. 'authentication',
  40. 'logging',
  41. 'prevent_group_restriction',
  42. ];
  43. /** @var string[] $appId => $enabled */
  44. private array $installedAppsCache = [];
  45. /** @var string[]|null */
  46. private ?array $shippedApps = null;
  47. private array $alwaysEnabled = [];
  48. private array $defaultEnabled = [];
  49. /** @var array */
  50. private array $appInfos = [];
  51. /** @var array */
  52. private array $appVersions = [];
  53. /** @var array */
  54. private array $autoDisabledApps = [];
  55. private array $appTypes = [];
  56. /** @var array<string, true> */
  57. private array $loadedApps = [];
  58. private ?AppConfig $appConfig = null;
  59. private ?IURLGenerator $urlGenerator = null;
  60. /**
  61. * Be extremely careful when injecting classes here. The AppManager is used by the installer,
  62. * so it needs to work before installation. See how AppConfig and IURLGenerator are injected for reference
  63. */
  64. public function __construct(
  65. private IUserSession $userSession,
  66. private IConfig $config,
  67. private IGroupManager $groupManager,
  68. private ICacheFactory $memCacheFactory,
  69. private IEventDispatcher $dispatcher,
  70. private LoggerInterface $logger,
  71. ) {
  72. }
  73. public function getAppIcon(string $appId, bool $dark = false): ?string {
  74. $possibleIcons = $dark ? [$appId . '-dark.svg', 'app-dark.svg'] : [$appId . '.svg', 'app.svg'];
  75. $icon = null;
  76. foreach ($possibleIcons as $iconName) {
  77. try {
  78. $icon = $this->getUrlGenerator()->imagePath($appId, $iconName);
  79. break;
  80. } catch (\RuntimeException $e) {
  81. // ignore
  82. }
  83. }
  84. return $icon;
  85. }
  86. private function getAppConfig(): AppConfig {
  87. if ($this->appConfig !== null) {
  88. return $this->appConfig;
  89. }
  90. if (!$this->config->getSystemValueBool('installed', false)) {
  91. throw new \Exception('Nextcloud is not installed yet, AppConfig is not available');
  92. }
  93. $this->appConfig = \OCP\Server::get(AppConfig::class);
  94. return $this->appConfig;
  95. }
  96. private function getUrlGenerator(): IURLGenerator {
  97. if ($this->urlGenerator !== null) {
  98. return $this->urlGenerator;
  99. }
  100. if (!$this->config->getSystemValueBool('installed', false)) {
  101. throw new \Exception('Nextcloud is not installed yet, AppConfig is not available');
  102. }
  103. $this->urlGenerator = \OCP\Server::get(IURLGenerator::class);
  104. return $this->urlGenerator;
  105. }
  106. /**
  107. * @return string[] $appId => $enabled
  108. */
  109. private function getInstalledAppsValues(): array {
  110. if (!$this->installedAppsCache) {
  111. $values = $this->getAppConfig()->getValues(false, 'enabled');
  112. $alwaysEnabledApps = $this->getAlwaysEnabledApps();
  113. foreach ($alwaysEnabledApps as $appId) {
  114. $values[$appId] = 'yes';
  115. }
  116. $this->installedAppsCache = array_filter($values, function ($value) {
  117. return $value !== 'no';
  118. });
  119. ksort($this->installedAppsCache);
  120. }
  121. return $this->installedAppsCache;
  122. }
  123. /**
  124. * List all installed apps
  125. *
  126. * @return string[]
  127. */
  128. public function getInstalledApps() {
  129. return array_keys($this->getInstalledAppsValues());
  130. }
  131. /**
  132. * List all apps enabled for a user
  133. *
  134. * @param \OCP\IUser $user
  135. * @return string[]
  136. */
  137. public function getEnabledAppsForUser(IUser $user) {
  138. $apps = $this->getInstalledAppsValues();
  139. $appsForUser = array_filter($apps, function ($enabled) use ($user) {
  140. return $this->checkAppForUser($enabled, $user);
  141. });
  142. return array_keys($appsForUser);
  143. }
  144. /**
  145. * @param IGroup $group
  146. * @return array
  147. */
  148. public function getEnabledAppsForGroup(IGroup $group): array {
  149. $apps = $this->getInstalledAppsValues();
  150. $appsForGroups = array_filter($apps, function ($enabled) use ($group) {
  151. return $this->checkAppForGroups($enabled, $group);
  152. });
  153. return array_keys($appsForGroups);
  154. }
  155. /**
  156. * Loads all apps
  157. *
  158. * @param string[] $types
  159. * @return bool
  160. *
  161. * This function walks through the Nextcloud directory and loads all apps
  162. * it can find. A directory contains an app if the file /appinfo/info.xml
  163. * exists.
  164. *
  165. * if $types is set to non-empty array, only apps of those types will be loaded
  166. */
  167. public function loadApps(array $types = []): bool {
  168. if ($this->config->getSystemValueBool('maintenance', false)) {
  169. return false;
  170. }
  171. // Load the enabled apps here
  172. $apps = \OC_App::getEnabledApps();
  173. // Add each apps' folder as allowed class path
  174. foreach ($apps as $app) {
  175. // If the app is already loaded then autoloading it makes no sense
  176. if (!$this->isAppLoaded($app)) {
  177. $path = \OC_App::getAppPath($app);
  178. if ($path !== false) {
  179. \OC_App::registerAutoloading($app, $path);
  180. }
  181. }
  182. }
  183. // prevent app.php from printing output
  184. ob_start();
  185. foreach ($apps as $app) {
  186. if (!$this->isAppLoaded($app) && ($types === [] || $this->isType($app, $types))) {
  187. try {
  188. $this->loadApp($app);
  189. } catch (\Throwable $e) {
  190. $this->logger->emergency('Error during app loading: ' . $e->getMessage(), [
  191. 'exception' => $e,
  192. 'app' => $app,
  193. ]);
  194. }
  195. }
  196. }
  197. ob_end_clean();
  198. return true;
  199. }
  200. /**
  201. * check if an app is of a specific type
  202. *
  203. * @param string $app
  204. * @param array $types
  205. * @return bool
  206. */
  207. public function isType(string $app, array $types): bool {
  208. $appTypes = $this->getAppTypes($app);
  209. foreach ($types as $type) {
  210. if (in_array($type, $appTypes, true)) {
  211. return true;
  212. }
  213. }
  214. return false;
  215. }
  216. /**
  217. * get the types of an app
  218. *
  219. * @param string $app
  220. * @return string[]
  221. */
  222. private function getAppTypes(string $app): array {
  223. //load the cache
  224. if (count($this->appTypes) === 0) {
  225. $this->appTypes = $this->getAppConfig()->getValues(false, 'types') ?: [];
  226. }
  227. if (isset($this->appTypes[$app])) {
  228. return explode(',', $this->appTypes[$app]);
  229. }
  230. return [];
  231. }
  232. /**
  233. * @return array
  234. */
  235. public function getAutoDisabledApps(): array {
  236. return $this->autoDisabledApps;
  237. }
  238. /**
  239. * @param string $appId
  240. * @return array
  241. */
  242. public function getAppRestriction(string $appId): array {
  243. $values = $this->getInstalledAppsValues();
  244. if (!isset($values[$appId])) {
  245. return [];
  246. }
  247. if ($values[$appId] === 'yes' || $values[$appId] === 'no') {
  248. return [];
  249. }
  250. return json_decode($values[$appId], true);
  251. }
  252. /**
  253. * Check if an app is enabled for user
  254. *
  255. * @param string $appId
  256. * @param \OCP\IUser|null $user (optional) if not defined, the currently logged in user will be used
  257. * @return bool
  258. */
  259. public function isEnabledForUser($appId, $user = null) {
  260. if ($this->isAlwaysEnabled($appId)) {
  261. return true;
  262. }
  263. if ($user === null) {
  264. $user = $this->userSession->getUser();
  265. }
  266. $installedApps = $this->getInstalledAppsValues();
  267. if (isset($installedApps[$appId])) {
  268. return $this->checkAppForUser($installedApps[$appId], $user);
  269. } else {
  270. return false;
  271. }
  272. }
  273. private function checkAppForUser(string $enabled, ?IUser $user): bool {
  274. if ($enabled === 'yes') {
  275. return true;
  276. } elseif ($user === null) {
  277. return false;
  278. } else {
  279. if (empty($enabled)) {
  280. return false;
  281. }
  282. $groupIds = json_decode($enabled);
  283. if (!is_array($groupIds)) {
  284. $jsonError = json_last_error();
  285. $jsonErrorMsg = json_last_error_msg();
  286. // this really should never happen (if it does, the admin should check the `enabled` key value via `occ config:list` because it's bogus for some reason)
  287. $this->logger->warning('AppManager::checkAppForUser - can\'t decode group IDs listed in app\'s enabled config key: ' . print_r($enabled, true) . ' - JSON error (' . $jsonError . ') ' . $jsonErrorMsg);
  288. return false;
  289. }
  290. $userGroups = $this->groupManager->getUserGroupIds($user);
  291. foreach ($userGroups as $groupId) {
  292. if (in_array($groupId, $groupIds, true)) {
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. }
  299. private function checkAppForGroups(string $enabled, IGroup $group): bool {
  300. if ($enabled === 'yes') {
  301. return true;
  302. } else {
  303. if (empty($enabled)) {
  304. return false;
  305. }
  306. $groupIds = json_decode($enabled);
  307. if (!is_array($groupIds)) {
  308. $jsonError = json_last_error();
  309. $jsonErrorMsg = json_last_error_msg();
  310. // this really should never happen (if it does, the admin should check the `enabled` key value via `occ config:list` because it's bogus for some reason)
  311. $this->logger->warning('AppManager::checkAppForGroups - can\'t decode group IDs listed in app\'s enabled config key: ' . print_r($enabled, true) . ' - JSON error (' . $jsonError . ') ' . $jsonErrorMsg);
  312. return false;
  313. }
  314. return in_array($group->getGID(), $groupIds);
  315. }
  316. }
  317. /**
  318. * Check if an app is enabled in the instance
  319. *
  320. * Notice: This actually checks if the app is enabled and not only if it is installed.
  321. *
  322. * @param string $appId
  323. * @param IGroup[]|String[] $groups
  324. * @return bool
  325. */
  326. public function isInstalled($appId) {
  327. $installedApps = $this->getInstalledAppsValues();
  328. return isset($installedApps[$appId]);
  329. }
  330. public function ignoreNextcloudRequirementForApp(string $appId): void {
  331. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  332. if (!in_array($appId, $ignoreMaxApps, true)) {
  333. $ignoreMaxApps[] = $appId;
  334. $this->config->setSystemValue('app_install_overwrite', $ignoreMaxApps);
  335. }
  336. }
  337. public function loadApp(string $app): void {
  338. if (isset($this->loadedApps[$app])) {
  339. return;
  340. }
  341. $this->loadedApps[$app] = true;
  342. $appPath = \OC_App::getAppPath($app);
  343. if ($appPath === false) {
  344. return;
  345. }
  346. $eventLogger = \OC::$server->get(\OCP\Diagnostics\IEventLogger::class);
  347. $eventLogger->start("bootstrap:load_app:$app", "Load $app");
  348. // in case someone calls loadApp() directly
  349. \OC_App::registerAutoloading($app, $appPath);
  350. /** @var Coordinator $coordinator */
  351. $coordinator = \OC::$server->get(Coordinator::class);
  352. $isBootable = $coordinator->isBootable($app);
  353. $hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
  354. $eventLogger = \OC::$server->get(IEventLogger::class);
  355. $eventLogger->start('bootstrap:load_app_' . $app, 'Load app: ' . $app);
  356. if ($isBootable && $hasAppPhpFile) {
  357. $this->logger->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
  358. 'app' => $app,
  359. ]);
  360. } elseif ($hasAppPhpFile) {
  361. $eventLogger->start("bootstrap:load_app:$app:app.php", "Load legacy app.php app $app");
  362. $this->logger->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
  363. 'app' => $app,
  364. ]);
  365. try {
  366. self::requireAppFile($appPath);
  367. } catch (\Throwable $ex) {
  368. if ($ex instanceof ServerNotAvailableException) {
  369. throw $ex;
  370. }
  371. if (!$this->isShipped($app) && !$this->isType($app, ['authentication'])) {
  372. $this->logger->error("App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(), [
  373. 'exception' => $ex,
  374. ]);
  375. // Only disable apps which are not shipped and that are not authentication apps
  376. $this->disableApp($app, true);
  377. } else {
  378. $this->logger->error("App $app threw an error during app.php load: " . $ex->getMessage(), [
  379. 'exception' => $ex,
  380. ]);
  381. }
  382. }
  383. $eventLogger->end("bootstrap:load_app:$app:app.php");
  384. }
  385. $coordinator->bootApp($app);
  386. $eventLogger->start("bootstrap:load_app:$app:info", "Load info.xml for $app and register any services defined in it");
  387. $info = $this->getAppInfo($app);
  388. if (!empty($info['activity'])) {
  389. $activityManager = \OC::$server->get(IActivityManager::class);
  390. if (!empty($info['activity']['filters'])) {
  391. foreach ($info['activity']['filters'] as $filter) {
  392. $activityManager->registerFilter($filter);
  393. }
  394. }
  395. if (!empty($info['activity']['settings'])) {
  396. foreach ($info['activity']['settings'] as $setting) {
  397. $activityManager->registerSetting($setting);
  398. }
  399. }
  400. if (!empty($info['activity']['providers'])) {
  401. foreach ($info['activity']['providers'] as $provider) {
  402. $activityManager->registerProvider($provider);
  403. }
  404. }
  405. }
  406. if (!empty($info['settings'])) {
  407. $settingsManager = \OC::$server->get(ISettingsManager::class);
  408. if (!empty($info['settings']['admin'])) {
  409. foreach ($info['settings']['admin'] as $setting) {
  410. $settingsManager->registerSetting('admin', $setting);
  411. }
  412. }
  413. if (!empty($info['settings']['admin-section'])) {
  414. foreach ($info['settings']['admin-section'] as $section) {
  415. $settingsManager->registerSection('admin', $section);
  416. }
  417. }
  418. if (!empty($info['settings']['personal'])) {
  419. foreach ($info['settings']['personal'] as $setting) {
  420. $settingsManager->registerSetting('personal', $setting);
  421. }
  422. }
  423. if (!empty($info['settings']['personal-section'])) {
  424. foreach ($info['settings']['personal-section'] as $section) {
  425. $settingsManager->registerSection('personal', $section);
  426. }
  427. }
  428. }
  429. if (!empty($info['collaboration']['plugins'])) {
  430. // deal with one or many plugin entries
  431. $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
  432. [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
  433. $collaboratorSearch = null;
  434. $autoCompleteManager = null;
  435. foreach ($plugins as $plugin) {
  436. if ($plugin['@attributes']['type'] === 'collaborator-search') {
  437. $pluginInfo = [
  438. 'shareType' => $plugin['@attributes']['share-type'],
  439. 'class' => $plugin['@value'],
  440. ];
  441. $collaboratorSearch ??= \OC::$server->get(ICollaboratorSearch::class);
  442. $collaboratorSearch->registerPlugin($pluginInfo);
  443. } elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
  444. $autoCompleteManager ??= \OC::$server->get(IAutoCompleteManager::class);
  445. $autoCompleteManager->registerSorter($plugin['@value']);
  446. }
  447. }
  448. }
  449. $eventLogger->end("bootstrap:load_app:$app:info");
  450. $eventLogger->end("bootstrap:load_app:$app");
  451. }
  452. /**
  453. * Check if an app is loaded
  454. * @param string $app app id
  455. * @since 26.0.0
  456. */
  457. public function isAppLoaded(string $app): bool {
  458. return isset($this->loadedApps[$app]);
  459. }
  460. /**
  461. * Load app.php from the given app
  462. *
  463. * @param string $app app name
  464. * @throws \Error
  465. */
  466. private static function requireAppFile(string $app): void {
  467. // encapsulated here to avoid variable scope conflicts
  468. require_once $app . '/appinfo/app.php';
  469. }
  470. /**
  471. * Enable an app for every user
  472. *
  473. * @param string $appId
  474. * @param bool $forceEnable
  475. * @throws AppPathNotFoundException
  476. */
  477. public function enableApp(string $appId, bool $forceEnable = false): void {
  478. // Check if app exists
  479. $this->getAppPath($appId);
  480. if ($forceEnable) {
  481. $this->ignoreNextcloudRequirementForApp($appId);
  482. }
  483. $this->installedAppsCache[$appId] = 'yes';
  484. $this->getAppConfig()->setValue($appId, 'enabled', 'yes');
  485. $this->dispatcher->dispatchTyped(new AppEnableEvent($appId));
  486. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
  487. ManagerEvent::EVENT_APP_ENABLE, $appId
  488. ));
  489. $this->clearAppsCache();
  490. }
  491. /**
  492. * Whether a list of types contains a protected app type
  493. *
  494. * @param string[] $types
  495. * @return bool
  496. */
  497. public function hasProtectedAppType($types) {
  498. if (empty($types)) {
  499. return false;
  500. }
  501. $protectedTypes = array_intersect($this->protectedAppTypes, $types);
  502. return !empty($protectedTypes);
  503. }
  504. /**
  505. * Enable an app only for specific groups
  506. *
  507. * @param string $appId
  508. * @param IGroup[] $groups
  509. * @param bool $forceEnable
  510. * @throws \InvalidArgumentException if app can't be enabled for groups
  511. * @throws AppPathNotFoundException
  512. */
  513. public function enableAppForGroups(string $appId, array $groups, bool $forceEnable = false): void {
  514. // Check if app exists
  515. $this->getAppPath($appId);
  516. $info = $this->getAppInfo($appId);
  517. if (!empty($info['types']) && $this->hasProtectedAppType($info['types'])) {
  518. throw new \InvalidArgumentException("$appId can't be enabled for groups.");
  519. }
  520. if ($forceEnable) {
  521. $this->ignoreNextcloudRequirementForApp($appId);
  522. }
  523. /** @var string[] $groupIds */
  524. $groupIds = array_map(function ($group) {
  525. /** @var IGroup $group */
  526. return ($group instanceof IGroup)
  527. ? $group->getGID()
  528. : $group;
  529. }, $groups);
  530. $this->installedAppsCache[$appId] = json_encode($groupIds);
  531. $this->getAppConfig()->setValue($appId, 'enabled', json_encode($groupIds));
  532. $this->dispatcher->dispatchTyped(new AppEnableEvent($appId, $groupIds));
  533. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
  534. ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
  535. ));
  536. $this->clearAppsCache();
  537. }
  538. /**
  539. * Disable an app for every user
  540. *
  541. * @param string $appId
  542. * @param bool $automaticDisabled
  543. * @throws \Exception if app can't be disabled
  544. */
  545. public function disableApp($appId, $automaticDisabled = false) {
  546. if ($this->isAlwaysEnabled($appId)) {
  547. throw new \Exception("$appId can't be disabled.");
  548. }
  549. if ($automaticDisabled) {
  550. $previousSetting = $this->getAppConfig()->getValue($appId, 'enabled', 'yes');
  551. if ($previousSetting !== 'yes' && $previousSetting !== 'no') {
  552. $previousSetting = json_decode($previousSetting, true);
  553. }
  554. $this->autoDisabledApps[$appId] = $previousSetting;
  555. }
  556. unset($this->installedAppsCache[$appId]);
  557. $this->getAppConfig()->setValue($appId, 'enabled', 'no');
  558. // run uninstall steps
  559. $appData = $this->getAppInfo($appId);
  560. if (!is_null($appData)) {
  561. \OC_App::executeRepairSteps($appId, $appData['repair-steps']['uninstall']);
  562. }
  563. $this->dispatcher->dispatchTyped(new AppDisableEvent($appId));
  564. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
  565. ManagerEvent::EVENT_APP_DISABLE, $appId
  566. ));
  567. $this->clearAppsCache();
  568. }
  569. /**
  570. * Get the directory for the given app.
  571. *
  572. * @param string $appId
  573. * @return string
  574. * @throws AppPathNotFoundException if app folder can't be found
  575. */
  576. public function getAppPath($appId) {
  577. $appPath = \OC_App::getAppPath($appId);
  578. if ($appPath === false) {
  579. throw new AppPathNotFoundException('Could not find path for ' . $appId);
  580. }
  581. return $appPath;
  582. }
  583. /**
  584. * Get the web path for the given app.
  585. *
  586. * @param string $appId
  587. * @return string
  588. * @throws AppPathNotFoundException if app path can't be found
  589. */
  590. public function getAppWebPath(string $appId): string {
  591. $appWebPath = \OC_App::getAppWebPath($appId);
  592. if ($appWebPath === false) {
  593. throw new AppPathNotFoundException('Could not find web path for ' . $appId);
  594. }
  595. return $appWebPath;
  596. }
  597. /**
  598. * Clear the cached list of apps when enabling/disabling an app
  599. */
  600. public function clearAppsCache() {
  601. $this->appInfos = [];
  602. }
  603. /**
  604. * Returns a list of apps that need upgrade
  605. *
  606. * @param string $version Nextcloud version as array of version components
  607. * @return array list of app info from apps that need an upgrade
  608. *
  609. * @internal
  610. */
  611. public function getAppsNeedingUpgrade($version) {
  612. $appsToUpgrade = [];
  613. $apps = $this->getInstalledApps();
  614. foreach ($apps as $appId) {
  615. $appInfo = $this->getAppInfo($appId);
  616. $appDbVersion = $this->getAppConfig()->getValue($appId, 'installed_version');
  617. if ($appDbVersion
  618. && isset($appInfo['version'])
  619. && version_compare($appInfo['version'], $appDbVersion, '>')
  620. && \OC_App::isAppCompatible($version, $appInfo)
  621. ) {
  622. $appsToUpgrade[] = $appInfo;
  623. }
  624. }
  625. return $appsToUpgrade;
  626. }
  627. /**
  628. * Returns the app information from "appinfo/info.xml".
  629. *
  630. * @param string|null $lang
  631. * @return array|null app info
  632. */
  633. public function getAppInfo(string $appId, bool $path = false, $lang = null) {
  634. if ($path) {
  635. $file = $appId;
  636. } else {
  637. if ($lang === null && isset($this->appInfos[$appId])) {
  638. return $this->appInfos[$appId];
  639. }
  640. try {
  641. $appPath = $this->getAppPath($appId);
  642. } catch (AppPathNotFoundException $e) {
  643. return null;
  644. }
  645. $file = $appPath . '/appinfo/info.xml';
  646. }
  647. $parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
  648. $data = $parser->parse($file);
  649. if (is_array($data)) {
  650. $data = \OC_App::parseAppInfo($data, $lang);
  651. }
  652. if ($lang === null) {
  653. $this->appInfos[$appId] = $data;
  654. }
  655. return $data;
  656. }
  657. public function getAppVersion(string $appId, bool $useCache = true): string {
  658. if (!$useCache || !isset($this->appVersions[$appId])) {
  659. $appInfo = $this->getAppInfo($appId);
  660. $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0';
  661. }
  662. return $this->appVersions[$appId];
  663. }
  664. /**
  665. * Returns a list of apps incompatible with the given version
  666. *
  667. * @param string $version Nextcloud version as array of version components
  668. *
  669. * @return array list of app info from incompatible apps
  670. *
  671. * @internal
  672. */
  673. public function getIncompatibleApps(string $version): array {
  674. $apps = $this->getInstalledApps();
  675. $incompatibleApps = [];
  676. foreach ($apps as $appId) {
  677. $info = $this->getAppInfo($appId);
  678. if ($info === null) {
  679. $incompatibleApps[] = ['id' => $appId, 'name' => $appId];
  680. } elseif (!\OC_App::isAppCompatible($version, $info)) {
  681. $incompatibleApps[] = $info;
  682. }
  683. }
  684. return $incompatibleApps;
  685. }
  686. /**
  687. * @inheritdoc
  688. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::isShipped()
  689. */
  690. public function isShipped($appId) {
  691. $this->loadShippedJson();
  692. return in_array($appId, $this->shippedApps, true);
  693. }
  694. private function isAlwaysEnabled(string $appId): bool {
  695. $alwaysEnabled = $this->getAlwaysEnabledApps();
  696. return in_array($appId, $alwaysEnabled, true);
  697. }
  698. /**
  699. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::loadShippedJson()
  700. * @throws \Exception
  701. */
  702. private function loadShippedJson(): void {
  703. if ($this->shippedApps === null) {
  704. $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
  705. if (!file_exists($shippedJson)) {
  706. throw new \Exception("File not found: $shippedJson");
  707. }
  708. $content = json_decode(file_get_contents($shippedJson), true);
  709. $this->shippedApps = $content['shippedApps'];
  710. $this->alwaysEnabled = $content['alwaysEnabled'];
  711. $this->defaultEnabled = $content['defaultEnabled'];
  712. }
  713. }
  714. /**
  715. * @inheritdoc
  716. */
  717. public function getAlwaysEnabledApps() {
  718. $this->loadShippedJson();
  719. return $this->alwaysEnabled;
  720. }
  721. /**
  722. * @inheritdoc
  723. */
  724. public function isDefaultEnabled(string $appId): bool {
  725. return (in_array($appId, $this->getDefaultEnabledApps()));
  726. }
  727. /**
  728. * @inheritdoc
  729. */
  730. public function getDefaultEnabledApps(): array {
  731. $this->loadShippedJson();
  732. return $this->defaultEnabled;
  733. }
  734. public function getDefaultAppForUser(?IUser $user = null, bool $withFallbacks = true): string {
  735. // Set fallback to always-enabled files app
  736. $appId = $withFallbacks ? 'files' : '';
  737. $defaultApps = explode(',', $this->config->getSystemValueString('defaultapp', ''));
  738. $defaultApps = array_filter($defaultApps);
  739. $user ??= $this->userSession->getUser();
  740. if ($user !== null) {
  741. $userDefaultApps = explode(',', $this->config->getUserValue($user->getUID(), 'core', 'defaultapp'));
  742. $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
  743. if (empty($defaultApps) && $withFallbacks) {
  744. /* Fallback on user defined apporder */
  745. $customOrders = json_decode($this->config->getUserValue($user->getUID(), 'core', 'apporder', '[]'), true, flags:JSON_THROW_ON_ERROR);
  746. if (!empty($customOrders)) {
  747. // filter only entries with app key (when added using closures or NavigationManager::add the app is not guranteed to be set)
  748. $customOrders = array_filter($customOrders, fn ($entry) => isset($entry['app']));
  749. // sort apps by order
  750. usort($customOrders, fn ($a, $b) => $a['order'] - $b['order']);
  751. // set default apps to sorted apps
  752. $defaultApps = array_map(fn ($entry) => $entry['app'], $customOrders);
  753. }
  754. }
  755. }
  756. if (empty($defaultApps) && $withFallbacks) {
  757. $defaultApps = ['dashboard','files'];
  758. }
  759. // Find the first app that is enabled for the current user
  760. foreach ($defaultApps as $defaultApp) {
  761. $defaultApp = \OC_App::cleanAppId(strip_tags($defaultApp));
  762. if ($this->isEnabledForUser($defaultApp, $user)) {
  763. $appId = $defaultApp;
  764. break;
  765. }
  766. }
  767. return $appId;
  768. }
  769. public function getDefaultApps(): array {
  770. return explode(',', $this->config->getSystemValueString('defaultapp', 'dashboard,files'));
  771. }
  772. public function setDefaultApps(array $defaultApps): void {
  773. foreach ($defaultApps as $app) {
  774. if (!$this->isInstalled($app)) {
  775. $this->logger->debug('Can not set not installed app as default app', ['missing_app' => $app]);
  776. throw new InvalidArgumentException('App is not installed');
  777. }
  778. }
  779. $this->config->setSystemValue('defaultapp', join(',', $defaultApps));
  780. }
  781. }