AppManager.php 24 KB

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