AppManager.php 25 KB

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