AppManager.php 26 KB

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