You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppManager.php 25KB

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