AppManager.php 25 KB

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