1
0

AppManager.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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(IEventLogger::class);
  347. $eventLogger->start("bootstrap:load_app:$app", "Load app: $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. if ($isBootable && $hasAppPhpFile) {
  355. $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.', [
  356. 'app' => $app,
  357. ]);
  358. } elseif ($hasAppPhpFile) {
  359. $eventLogger->start("bootstrap:load_app:$app:app.php", "Load legacy app.php app $app");
  360. $this->logger->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
  361. 'app' => $app,
  362. ]);
  363. try {
  364. self::requireAppFile($appPath);
  365. } catch (\Throwable $ex) {
  366. if ($ex instanceof ServerNotAvailableException) {
  367. throw $ex;
  368. }
  369. if (!$this->isShipped($app) && !$this->isType($app, ['authentication'])) {
  370. $this->logger->error("App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(), [
  371. 'exception' => $ex,
  372. ]);
  373. // Only disable apps which are not shipped and that are not authentication apps
  374. $this->disableApp($app, true);
  375. } else {
  376. $this->logger->error("App $app threw an error during app.php load: " . $ex->getMessage(), [
  377. 'exception' => $ex,
  378. ]);
  379. }
  380. }
  381. $eventLogger->end("bootstrap:load_app:$app:app.php");
  382. }
  383. $coordinator->bootApp($app);
  384. $eventLogger->start("bootstrap:load_app:$app:info", "Load info.xml for $app and register any services defined in it");
  385. $info = $this->getAppInfo($app);
  386. if (!empty($info['activity'])) {
  387. $activityManager = \OC::$server->get(IActivityManager::class);
  388. if (!empty($info['activity']['filters'])) {
  389. foreach ($info['activity']['filters'] as $filter) {
  390. $activityManager->registerFilter($filter);
  391. }
  392. }
  393. if (!empty($info['activity']['settings'])) {
  394. foreach ($info['activity']['settings'] as $setting) {
  395. $activityManager->registerSetting($setting);
  396. }
  397. }
  398. if (!empty($info['activity']['providers'])) {
  399. foreach ($info['activity']['providers'] as $provider) {
  400. $activityManager->registerProvider($provider);
  401. }
  402. }
  403. }
  404. if (!empty($info['settings'])) {
  405. $settingsManager = \OC::$server->get(ISettingsManager::class);
  406. if (!empty($info['settings']['admin'])) {
  407. foreach ($info['settings']['admin'] as $setting) {
  408. $settingsManager->registerSetting('admin', $setting);
  409. }
  410. }
  411. if (!empty($info['settings']['admin-section'])) {
  412. foreach ($info['settings']['admin-section'] as $section) {
  413. $settingsManager->registerSection('admin', $section);
  414. }
  415. }
  416. if (!empty($info['settings']['personal'])) {
  417. foreach ($info['settings']['personal'] as $setting) {
  418. $settingsManager->registerSetting('personal', $setting);
  419. }
  420. }
  421. if (!empty($info['settings']['personal-section'])) {
  422. foreach ($info['settings']['personal-section'] as $section) {
  423. $settingsManager->registerSection('personal', $section);
  424. }
  425. }
  426. }
  427. if (!empty($info['collaboration']['plugins'])) {
  428. // deal with one or many plugin entries
  429. $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
  430. [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
  431. $collaboratorSearch = null;
  432. $autoCompleteManager = null;
  433. foreach ($plugins as $plugin) {
  434. if ($plugin['@attributes']['type'] === 'collaborator-search') {
  435. $pluginInfo = [
  436. 'shareType' => $plugin['@attributes']['share-type'],
  437. 'class' => $plugin['@value'],
  438. ];
  439. $collaboratorSearch ??= \OC::$server->get(ICollaboratorSearch::class);
  440. $collaboratorSearch->registerPlugin($pluginInfo);
  441. } elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
  442. $autoCompleteManager ??= \OC::$server->get(IAutoCompleteManager::class);
  443. $autoCompleteManager->registerSorter($plugin['@value']);
  444. }
  445. }
  446. }
  447. $eventLogger->end("bootstrap:load_app:$app:info");
  448. $eventLogger->end("bootstrap:load_app:$app");
  449. }
  450. /**
  451. * Check if an app is loaded
  452. * @param string $app app id
  453. * @since 26.0.0
  454. */
  455. public function isAppLoaded(string $app): bool {
  456. return isset($this->loadedApps[$app]);
  457. }
  458. /**
  459. * Load app.php from the given app
  460. *
  461. * @param string $app app name
  462. * @throws \Error
  463. */
  464. private static function requireAppFile(string $app): void {
  465. // encapsulated here to avoid variable scope conflicts
  466. require_once $app . '/appinfo/app.php';
  467. }
  468. /**
  469. * Enable an app for every user
  470. *
  471. * @param string $appId
  472. * @param bool $forceEnable
  473. * @throws AppPathNotFoundException
  474. */
  475. public function enableApp(string $appId, bool $forceEnable = false): void {
  476. // Check if app exists
  477. $this->getAppPath($appId);
  478. if ($forceEnable) {
  479. $this->ignoreNextcloudRequirementForApp($appId);
  480. }
  481. $this->installedAppsCache[$appId] = 'yes';
  482. $this->getAppConfig()->setValue($appId, 'enabled', 'yes');
  483. $this->dispatcher->dispatchTyped(new AppEnableEvent($appId));
  484. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
  485. ManagerEvent::EVENT_APP_ENABLE, $appId
  486. ));
  487. $this->clearAppsCache();
  488. }
  489. /**
  490. * Whether a list of types contains a protected app type
  491. *
  492. * @param string[] $types
  493. * @return bool
  494. */
  495. public function hasProtectedAppType($types) {
  496. if (empty($types)) {
  497. return false;
  498. }
  499. $protectedTypes = array_intersect($this->protectedAppTypes, $types);
  500. return !empty($protectedTypes);
  501. }
  502. /**
  503. * Enable an app only for specific groups
  504. *
  505. * @param string $appId
  506. * @param IGroup[] $groups
  507. * @param bool $forceEnable
  508. * @throws \InvalidArgumentException if app can't be enabled for groups
  509. * @throws AppPathNotFoundException
  510. */
  511. public function enableAppForGroups(string $appId, array $groups, bool $forceEnable = false): void {
  512. // Check if app exists
  513. $this->getAppPath($appId);
  514. $info = $this->getAppInfo($appId);
  515. if (!empty($info['types']) && $this->hasProtectedAppType($info['types'])) {
  516. throw new \InvalidArgumentException("$appId can't be enabled for groups.");
  517. }
  518. if ($forceEnable) {
  519. $this->ignoreNextcloudRequirementForApp($appId);
  520. }
  521. /** @var string[] $groupIds */
  522. $groupIds = array_map(function ($group) {
  523. /** @var IGroup $group */
  524. return ($group instanceof IGroup)
  525. ? $group->getGID()
  526. : $group;
  527. }, $groups);
  528. $this->installedAppsCache[$appId] = json_encode($groupIds);
  529. $this->getAppConfig()->setValue($appId, 'enabled', json_encode($groupIds));
  530. $this->dispatcher->dispatchTyped(new AppEnableEvent($appId, $groupIds));
  531. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
  532. ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
  533. ));
  534. $this->clearAppsCache();
  535. }
  536. /**
  537. * Disable an app for every user
  538. *
  539. * @param string $appId
  540. * @param bool $automaticDisabled
  541. * @throws \Exception if app can't be disabled
  542. */
  543. public function disableApp($appId, $automaticDisabled = false) {
  544. if ($this->isAlwaysEnabled($appId)) {
  545. throw new \Exception("$appId can't be disabled.");
  546. }
  547. if ($automaticDisabled) {
  548. $previousSetting = $this->getAppConfig()->getValue($appId, 'enabled', 'yes');
  549. if ($previousSetting !== 'yes' && $previousSetting !== 'no') {
  550. $previousSetting = json_decode($previousSetting, true);
  551. }
  552. $this->autoDisabledApps[$appId] = $previousSetting;
  553. }
  554. unset($this->installedAppsCache[$appId]);
  555. $this->getAppConfig()->setValue($appId, 'enabled', 'no');
  556. // run uninstall steps
  557. $appData = $this->getAppInfo($appId);
  558. if (!is_null($appData)) {
  559. \OC_App::executeRepairSteps($appId, $appData['repair-steps']['uninstall']);
  560. }
  561. $this->dispatcher->dispatchTyped(new AppDisableEvent($appId));
  562. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
  563. ManagerEvent::EVENT_APP_DISABLE, $appId
  564. ));
  565. $this->clearAppsCache();
  566. }
  567. /**
  568. * Get the directory for the given app.
  569. *
  570. * @param string $appId
  571. * @return string
  572. * @throws AppPathNotFoundException if app folder can't be found
  573. */
  574. public function getAppPath($appId) {
  575. $appPath = \OC_App::getAppPath($appId);
  576. if ($appPath === false) {
  577. throw new AppPathNotFoundException('Could not find path for ' . $appId);
  578. }
  579. return $appPath;
  580. }
  581. /**
  582. * Get the web path for the given app.
  583. *
  584. * @param string $appId
  585. * @return string
  586. * @throws AppPathNotFoundException if app path can't be found
  587. */
  588. public function getAppWebPath(string $appId): string {
  589. $appWebPath = \OC_App::getAppWebPath($appId);
  590. if ($appWebPath === false) {
  591. throw new AppPathNotFoundException('Could not find web path for ' . $appId);
  592. }
  593. return $appWebPath;
  594. }
  595. /**
  596. * Clear the cached list of apps when enabling/disabling an app
  597. */
  598. public function clearAppsCache() {
  599. $this->appInfos = [];
  600. }
  601. /**
  602. * Returns a list of apps that need upgrade
  603. *
  604. * @param string $version Nextcloud version as array of version components
  605. * @return array list of app info from apps that need an upgrade
  606. *
  607. * @internal
  608. */
  609. public function getAppsNeedingUpgrade($version) {
  610. $appsToUpgrade = [];
  611. $apps = $this->getInstalledApps();
  612. foreach ($apps as $appId) {
  613. $appInfo = $this->getAppInfo($appId);
  614. $appDbVersion = $this->getAppConfig()->getValue($appId, 'installed_version');
  615. if ($appDbVersion
  616. && isset($appInfo['version'])
  617. && version_compare($appInfo['version'], $appDbVersion, '>')
  618. && \OC_App::isAppCompatible($version, $appInfo)
  619. ) {
  620. $appsToUpgrade[] = $appInfo;
  621. }
  622. }
  623. return $appsToUpgrade;
  624. }
  625. /**
  626. * Returns the app information from "appinfo/info.xml".
  627. *
  628. * @param string|null $lang
  629. * @return array|null app info
  630. */
  631. public function getAppInfo(string $appId, bool $path = false, $lang = null) {
  632. if ($path) {
  633. $file = $appId;
  634. } else {
  635. if ($lang === null && isset($this->appInfos[$appId])) {
  636. return $this->appInfos[$appId];
  637. }
  638. try {
  639. $appPath = $this->getAppPath($appId);
  640. } catch (AppPathNotFoundException $e) {
  641. return null;
  642. }
  643. $file = $appPath . '/appinfo/info.xml';
  644. }
  645. $parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
  646. $data = $parser->parse($file);
  647. if (is_array($data)) {
  648. $data = \OC_App::parseAppInfo($data, $lang);
  649. }
  650. if ($lang === null) {
  651. $this->appInfos[$appId] = $data;
  652. }
  653. return $data;
  654. }
  655. public function getAppVersion(string $appId, bool $useCache = true): string {
  656. if (!$useCache || !isset($this->appVersions[$appId])) {
  657. $appInfo = $this->getAppInfo($appId);
  658. $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0';
  659. }
  660. return $this->appVersions[$appId];
  661. }
  662. /**
  663. * Returns a list of apps incompatible with the given version
  664. *
  665. * @param string $version Nextcloud version as array of version components
  666. *
  667. * @return array list of app info from incompatible apps
  668. *
  669. * @internal
  670. */
  671. public function getIncompatibleApps(string $version): array {
  672. $apps = $this->getInstalledApps();
  673. $incompatibleApps = [];
  674. foreach ($apps as $appId) {
  675. $info = $this->getAppInfo($appId);
  676. if ($info === null) {
  677. $incompatibleApps[] = ['id' => $appId, 'name' => $appId];
  678. } elseif (!\OC_App::isAppCompatible($version, $info)) {
  679. $incompatibleApps[] = $info;
  680. }
  681. }
  682. return $incompatibleApps;
  683. }
  684. /**
  685. * @inheritdoc
  686. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::isShipped()
  687. */
  688. public function isShipped($appId) {
  689. $this->loadShippedJson();
  690. return in_array($appId, $this->shippedApps, true);
  691. }
  692. private function isAlwaysEnabled(string $appId): bool {
  693. $alwaysEnabled = $this->getAlwaysEnabledApps();
  694. return in_array($appId, $alwaysEnabled, true);
  695. }
  696. /**
  697. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::loadShippedJson()
  698. * @throws \Exception
  699. */
  700. private function loadShippedJson(): void {
  701. if ($this->shippedApps === null) {
  702. $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
  703. if (!file_exists($shippedJson)) {
  704. throw new \Exception("File not found: $shippedJson");
  705. }
  706. $content = json_decode(file_get_contents($shippedJson), true);
  707. $this->shippedApps = $content['shippedApps'];
  708. $this->alwaysEnabled = $content['alwaysEnabled'];
  709. $this->defaultEnabled = $content['defaultEnabled'];
  710. }
  711. }
  712. /**
  713. * @inheritdoc
  714. */
  715. public function getAlwaysEnabledApps() {
  716. $this->loadShippedJson();
  717. return $this->alwaysEnabled;
  718. }
  719. /**
  720. * @inheritdoc
  721. */
  722. public function isDefaultEnabled(string $appId): bool {
  723. return (in_array($appId, $this->getDefaultEnabledApps()));
  724. }
  725. /**
  726. * @inheritdoc
  727. */
  728. public function getDefaultEnabledApps(): array {
  729. $this->loadShippedJson();
  730. return $this->defaultEnabled;
  731. }
  732. public function getDefaultAppForUser(?IUser $user = null, bool $withFallbacks = true): string {
  733. // Set fallback to always-enabled files app
  734. $appId = $withFallbacks ? 'files' : '';
  735. $defaultApps = explode(',', $this->config->getSystemValueString('defaultapp', ''));
  736. $defaultApps = array_filter($defaultApps);
  737. $user ??= $this->userSession->getUser();
  738. if ($user !== null) {
  739. $userDefaultApps = explode(',', $this->config->getUserValue($user->getUID(), 'core', 'defaultapp'));
  740. $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
  741. if (empty($defaultApps) && $withFallbacks) {
  742. /* Fallback on user defined apporder */
  743. $customOrders = json_decode($this->config->getUserValue($user->getUID(), 'core', 'apporder', '[]'), true, flags:JSON_THROW_ON_ERROR);
  744. if (!empty($customOrders)) {
  745. // filter only entries with app key (when added using closures or NavigationManager::add the app is not guranteed to be set)
  746. $customOrders = array_filter($customOrders, fn ($entry) => isset($entry['app']));
  747. // sort apps by order
  748. usort($customOrders, fn ($a, $b) => $a['order'] - $b['order']);
  749. // set default apps to sorted apps
  750. $defaultApps = array_map(fn ($entry) => $entry['app'], $customOrders);
  751. }
  752. }
  753. }
  754. if (empty($defaultApps) && $withFallbacks) {
  755. $defaultApps = ['dashboard','files'];
  756. }
  757. // Find the first app that is enabled for the current user
  758. foreach ($defaultApps as $defaultApp) {
  759. $defaultApp = \OC_App::cleanAppId(strip_tags($defaultApp));
  760. if ($this->isEnabledForUser($defaultApp, $user)) {
  761. $appId = $defaultApp;
  762. break;
  763. }
  764. }
  765. return $appId;
  766. }
  767. public function getDefaultApps(): array {
  768. return explode(',', $this->config->getSystemValueString('defaultapp', 'dashboard,files'));
  769. }
  770. public function setDefaultApps(array $defaultApps): void {
  771. foreach ($defaultApps as $app) {
  772. if (!$this->isInstalled($app)) {
  773. $this->logger->debug('Can not set not installed app as default app', ['missing_app' => $app]);
  774. throw new InvalidArgumentException('App is not installed');
  775. }
  776. }
  777. $this->config->setSystemValue('defaultapp', join(',', $defaultApps));
  778. }
  779. public function isBackendRequired(string $backend): bool {
  780. foreach ($this->appInfos as $appInfo) {
  781. foreach ($appInfo['dependencies']['backend'] as $appBackend) {
  782. if ($backend === $appBackend) {
  783. return true;
  784. }
  785. }
  786. }
  787. return false;
  788. }
  789. }