AppManager.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 OCP\App\AppPathNotFoundException;
  42. use OCP\App\IAppManager;
  43. use OCP\App\ManagerEvent;
  44. use OCP\ICacheFactory;
  45. use OCP\IConfig;
  46. use OCP\IGroup;
  47. use OCP\IGroupManager;
  48. use OCP\IUser;
  49. use OCP\IUserSession;
  50. use Psr\Log\LoggerInterface;
  51. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  52. class AppManager implements IAppManager {
  53. /**
  54. * Apps with these types can not be enabled for certain groups only
  55. * @var string[]
  56. */
  57. protected $protectedAppTypes = [
  58. 'filesystem',
  59. 'prelogin',
  60. 'authentication',
  61. 'logging',
  62. 'prevent_group_restriction',
  63. ];
  64. /** @var IUserSession */
  65. private $userSession;
  66. /** @var IConfig */
  67. private $config;
  68. /** @var AppConfig */
  69. private $appConfig;
  70. /** @var IGroupManager */
  71. private $groupManager;
  72. /** @var ICacheFactory */
  73. private $memCacheFactory;
  74. /** @var EventDispatcherInterface */
  75. private $dispatcher;
  76. /** @var LoggerInterface */
  77. private $logger;
  78. /** @var string[] $appId => $enabled */
  79. private $installedAppsCache;
  80. /** @var string[] */
  81. private $shippedApps;
  82. private array $alwaysEnabled = [];
  83. private array $defaultEnabled = [];
  84. /** @var array */
  85. private $appInfos = [];
  86. /** @var array */
  87. private $appVersions = [];
  88. /** @var array */
  89. private $autoDisabledApps = [];
  90. public function __construct(IUserSession $userSession,
  91. IConfig $config,
  92. AppConfig $appConfig,
  93. IGroupManager $groupManager,
  94. ICacheFactory $memCacheFactory,
  95. EventDispatcherInterface $dispatcher,
  96. LoggerInterface $logger) {
  97. $this->userSession = $userSession;
  98. $this->config = $config;
  99. $this->appConfig = $appConfig;
  100. $this->groupManager = $groupManager;
  101. $this->memCacheFactory = $memCacheFactory;
  102. $this->dispatcher = $dispatcher;
  103. $this->logger = $logger;
  104. }
  105. /**
  106. * @return string[] $appId => $enabled
  107. */
  108. private function getInstalledAppsValues() {
  109. if (!$this->installedAppsCache) {
  110. $values = $this->appConfig->getValues(false, 'enabled');
  111. $alwaysEnabledApps = $this->getAlwaysEnabledApps();
  112. foreach ($alwaysEnabledApps as $appId) {
  113. $values[$appId] = 'yes';
  114. }
  115. $this->installedAppsCache = array_filter($values, function ($value) {
  116. return $value !== 'no';
  117. });
  118. ksort($this->installedAppsCache);
  119. }
  120. return $this->installedAppsCache;
  121. }
  122. /**
  123. * List all installed apps
  124. *
  125. * @return string[]
  126. */
  127. public function getInstalledApps() {
  128. return array_keys($this->getInstalledAppsValues());
  129. }
  130. /**
  131. * List all apps enabled for a user
  132. *
  133. * @param \OCP\IUser $user
  134. * @return string[]
  135. */
  136. public function getEnabledAppsForUser(IUser $user) {
  137. $apps = $this->getInstalledAppsValues();
  138. $appsForUser = array_filter($apps, function ($enabled) use ($user) {
  139. return $this->checkAppForUser($enabled, $user);
  140. });
  141. return array_keys($appsForUser);
  142. }
  143. /**
  144. * @param \OCP\IGroup $group
  145. * @return array
  146. */
  147. public function getEnabledAppsForGroup(IGroup $group): array {
  148. $apps = $this->getInstalledAppsValues();
  149. $appsForGroups = array_filter($apps, function ($enabled) use ($group) {
  150. return $this->checkAppForGroups($enabled, $group);
  151. });
  152. return array_keys($appsForGroups);
  153. }
  154. /**
  155. * @return array
  156. */
  157. public function getAutoDisabledApps(): array {
  158. return $this->autoDisabledApps;
  159. }
  160. /**
  161. * @param string $appId
  162. * @return array
  163. */
  164. public function getAppRestriction(string $appId): array {
  165. $values = $this->getInstalledAppsValues();
  166. if (!isset($values[$appId])) {
  167. return [];
  168. }
  169. if ($values[$appId] === 'yes' || $values[$appId] === 'no') {
  170. return [];
  171. }
  172. return json_decode($values[$appId], true);
  173. }
  174. /**
  175. * Check if an app is enabled for user
  176. *
  177. * @param string $appId
  178. * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
  179. * @return bool
  180. */
  181. public function isEnabledForUser($appId, $user = null) {
  182. if ($this->isAlwaysEnabled($appId)) {
  183. return true;
  184. }
  185. if ($user === null) {
  186. $user = $this->userSession->getUser();
  187. }
  188. $installedApps = $this->getInstalledAppsValues();
  189. if (isset($installedApps[$appId])) {
  190. return $this->checkAppForUser($installedApps[$appId], $user);
  191. } else {
  192. return false;
  193. }
  194. }
  195. /**
  196. * @param string $enabled
  197. * @param IUser $user
  198. * @return bool
  199. */
  200. private function checkAppForUser($enabled, $user) {
  201. if ($enabled === 'yes') {
  202. return true;
  203. } elseif ($user === null) {
  204. return false;
  205. } else {
  206. if (empty($enabled)) {
  207. return false;
  208. }
  209. $groupIds = json_decode($enabled);
  210. if (!is_array($groupIds)) {
  211. $jsonError = json_last_error();
  212. $this->logger->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError);
  213. return false;
  214. }
  215. $userGroups = $this->groupManager->getUserGroupIds($user);
  216. foreach ($userGroups as $groupId) {
  217. if (in_array($groupId, $groupIds, true)) {
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. }
  224. /**
  225. * @param string $enabled
  226. * @param IGroup $group
  227. * @return bool
  228. */
  229. private function checkAppForGroups(string $enabled, IGroup $group): bool {
  230. if ($enabled === 'yes') {
  231. return true;
  232. } elseif ($group === null) {
  233. return false;
  234. } else {
  235. if (empty($enabled)) {
  236. return false;
  237. }
  238. $groupIds = json_decode($enabled);
  239. if (!is_array($groupIds)) {
  240. $jsonError = json_last_error();
  241. $this->logger->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError);
  242. return false;
  243. }
  244. return in_array($group->getGID(), $groupIds);
  245. }
  246. }
  247. /**
  248. * Check if an app is enabled in the instance
  249. *
  250. * Notice: This actually checks if the app is enabled and not only if it is installed.
  251. *
  252. * @param string $appId
  253. * @param \OCP\IGroup[]|String[] $groups
  254. * @return bool
  255. */
  256. public function isInstalled($appId) {
  257. $installedApps = $this->getInstalledAppsValues();
  258. return isset($installedApps[$appId]);
  259. }
  260. public function ignoreNextcloudRequirementForApp(string $appId): void {
  261. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  262. if (!in_array($appId, $ignoreMaxApps, true)) {
  263. $ignoreMaxApps[] = $appId;
  264. $this->config->setSystemValue('app_install_overwrite', $ignoreMaxApps);
  265. }
  266. }
  267. /**
  268. * Enable an app for every user
  269. *
  270. * @param string $appId
  271. * @param bool $forceEnable
  272. * @throws AppPathNotFoundException
  273. */
  274. public function enableApp(string $appId, bool $forceEnable = false): void {
  275. // Check if app exists
  276. $this->getAppPath($appId);
  277. if ($forceEnable) {
  278. $this->ignoreNextcloudRequirementForApp($appId);
  279. }
  280. $this->installedAppsCache[$appId] = 'yes';
  281. $this->appConfig->setValue($appId, 'enabled', 'yes');
  282. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
  283. ManagerEvent::EVENT_APP_ENABLE, $appId
  284. ));
  285. $this->clearAppsCache();
  286. }
  287. /**
  288. * Whether a list of types contains a protected app type
  289. *
  290. * @param string[] $types
  291. * @return bool
  292. */
  293. public function hasProtectedAppType($types) {
  294. if (empty($types)) {
  295. return false;
  296. }
  297. $protectedTypes = array_intersect($this->protectedAppTypes, $types);
  298. return !empty($protectedTypes);
  299. }
  300. /**
  301. * Enable an app only for specific groups
  302. *
  303. * @param string $appId
  304. * @param \OCP\IGroup[] $groups
  305. * @param bool $forceEnable
  306. * @throws \InvalidArgumentException if app can't be enabled for groups
  307. * @throws AppPathNotFoundException
  308. */
  309. public function enableAppForGroups(string $appId, array $groups, bool $forceEnable = false): void {
  310. // Check if app exists
  311. $this->getAppPath($appId);
  312. $info = $this->getAppInfo($appId);
  313. if (!empty($info['types']) && $this->hasProtectedAppType($info['types'])) {
  314. throw new \InvalidArgumentException("$appId can't be enabled for groups.");
  315. }
  316. if ($forceEnable) {
  317. $this->ignoreNextcloudRequirementForApp($appId);
  318. }
  319. $groupIds = array_map(function ($group) {
  320. /** @var \OCP\IGroup $group */
  321. return ($group instanceof IGroup)
  322. ? $group->getGID()
  323. : $group;
  324. }, $groups);
  325. $this->installedAppsCache[$appId] = json_encode($groupIds);
  326. $this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
  327. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
  328. ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
  329. ));
  330. $this->clearAppsCache();
  331. }
  332. /**
  333. * Disable an app for every user
  334. *
  335. * @param string $appId
  336. * @param bool $automaticDisabled
  337. * @throws \Exception if app can't be disabled
  338. */
  339. public function disableApp($appId, $automaticDisabled = false) {
  340. if ($this->isAlwaysEnabled($appId)) {
  341. throw new \Exception("$appId can't be disabled.");
  342. }
  343. if ($automaticDisabled) {
  344. $previousSetting = $this->appConfig->getValue($appId, 'enabled', 'yes');
  345. if ($previousSetting !== 'yes' && $previousSetting !== 'no') {
  346. $previousSetting = json_decode($previousSetting, true);
  347. }
  348. $this->autoDisabledApps[$appId] = $previousSetting;
  349. }
  350. unset($this->installedAppsCache[$appId]);
  351. $this->appConfig->setValue($appId, 'enabled', 'no');
  352. // run uninstall steps
  353. $appData = $this->getAppInfo($appId);
  354. if (!is_null($appData)) {
  355. \OC_App::executeRepairSteps($appId, $appData['repair-steps']['uninstall']);
  356. }
  357. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
  358. ManagerEvent::EVENT_APP_DISABLE, $appId
  359. ));
  360. $this->clearAppsCache();
  361. }
  362. /**
  363. * Get the directory for the given app.
  364. *
  365. * @param string $appId
  366. * @return string
  367. * @throws AppPathNotFoundException if app folder can't be found
  368. */
  369. public function getAppPath($appId) {
  370. $appPath = \OC_App::getAppPath($appId);
  371. if ($appPath === false) {
  372. throw new AppPathNotFoundException('Could not find path for ' . $appId);
  373. }
  374. return $appPath;
  375. }
  376. /**
  377. * Get the web path for the given app.
  378. *
  379. * @param string $appId
  380. * @return string
  381. * @throws AppPathNotFoundException if app path can't be found
  382. */
  383. public function getAppWebPath(string $appId): string {
  384. $appWebPath = \OC_App::getAppWebPath($appId);
  385. if ($appWebPath === false) {
  386. throw new AppPathNotFoundException('Could not find web path for ' . $appId);
  387. }
  388. return $appWebPath;
  389. }
  390. /**
  391. * Clear the cached list of apps when enabling/disabling an app
  392. */
  393. public function clearAppsCache() {
  394. $settingsMemCache = $this->memCacheFactory->createDistributed('settings');
  395. $settingsMemCache->clear('listApps');
  396. $this->appInfos = [];
  397. }
  398. /**
  399. * Returns a list of apps that need upgrade
  400. *
  401. * @param string $version Nextcloud version as array of version components
  402. * @return array list of app info from apps that need an upgrade
  403. *
  404. * @internal
  405. */
  406. public function getAppsNeedingUpgrade($version) {
  407. $appsToUpgrade = [];
  408. $apps = $this->getInstalledApps();
  409. foreach ($apps as $appId) {
  410. $appInfo = $this->getAppInfo($appId);
  411. $appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
  412. if ($appDbVersion
  413. && isset($appInfo['version'])
  414. && version_compare($appInfo['version'], $appDbVersion, '>')
  415. && \OC_App::isAppCompatible($version, $appInfo)
  416. ) {
  417. $appsToUpgrade[] = $appInfo;
  418. }
  419. }
  420. return $appsToUpgrade;
  421. }
  422. /**
  423. * Returns the app information from "appinfo/info.xml".
  424. *
  425. * @param string $appId app id
  426. *
  427. * @param bool $path
  428. * @param null $lang
  429. * @return array|null app info
  430. */
  431. public function getAppInfo(string $appId, bool $path = false, $lang = null) {
  432. if ($path) {
  433. $file = $appId;
  434. } else {
  435. if ($lang === null && isset($this->appInfos[$appId])) {
  436. return $this->appInfos[$appId];
  437. }
  438. try {
  439. $appPath = $this->getAppPath($appId);
  440. } catch (AppPathNotFoundException $e) {
  441. return null;
  442. }
  443. $file = $appPath . '/appinfo/info.xml';
  444. }
  445. $parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
  446. $data = $parser->parse($file);
  447. if (is_array($data)) {
  448. $data = \OC_App::parseAppInfo($data, $lang);
  449. }
  450. if ($lang === null) {
  451. $this->appInfos[$appId] = $data;
  452. }
  453. return $data;
  454. }
  455. public function getAppVersion(string $appId, bool $useCache = true): string {
  456. if (!$useCache || !isset($this->appVersions[$appId])) {
  457. $appInfo = $this->getAppInfo($appId);
  458. $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0';
  459. }
  460. return $this->appVersions[$appId];
  461. }
  462. /**
  463. * Returns a list of apps incompatible with the given version
  464. *
  465. * @param string $version Nextcloud version as array of version components
  466. *
  467. * @return array list of app info from incompatible apps
  468. *
  469. * @internal
  470. */
  471. public function getIncompatibleApps(string $version): array {
  472. $apps = $this->getInstalledApps();
  473. $incompatibleApps = [];
  474. foreach ($apps as $appId) {
  475. $info = $this->getAppInfo($appId);
  476. if ($info === null) {
  477. $incompatibleApps[] = ['id' => $appId, 'name' => $appId];
  478. } elseif (!\OC_App::isAppCompatible($version, $info)) {
  479. $incompatibleApps[] = $info;
  480. }
  481. }
  482. return $incompatibleApps;
  483. }
  484. /**
  485. * @inheritdoc
  486. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::isShipped()
  487. */
  488. public function isShipped($appId) {
  489. $this->loadShippedJson();
  490. return in_array($appId, $this->shippedApps, true);
  491. }
  492. private function isAlwaysEnabled($appId) {
  493. $alwaysEnabled = $this->getAlwaysEnabledApps();
  494. return in_array($appId, $alwaysEnabled, true);
  495. }
  496. /**
  497. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::loadShippedJson()
  498. * @throws \Exception
  499. */
  500. private function loadShippedJson() {
  501. if ($this->shippedApps === null) {
  502. $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
  503. if (!file_exists($shippedJson)) {
  504. throw new \Exception("File not found: $shippedJson");
  505. }
  506. $content = json_decode(file_get_contents($shippedJson), true);
  507. $this->shippedApps = $content['shippedApps'];
  508. $this->alwaysEnabled = $content['alwaysEnabled'];
  509. $this->defaultEnabled = $content['defaultEnabled'];
  510. }
  511. }
  512. /**
  513. * @inheritdoc
  514. */
  515. public function getAlwaysEnabledApps() {
  516. $this->loadShippedJson();
  517. return $this->alwaysEnabled;
  518. }
  519. /**
  520. * @inheritdoc
  521. */
  522. public function isDefaultEnabled(string $appId): bool {
  523. return (in_array($appId, $this->getDefaultEnabledApps()));
  524. }
  525. /**
  526. * @inheritdoc
  527. */
  528. public function getDefaultEnabledApps():array {
  529. $this->loadShippedJson();
  530. return $this->defaultEnabled;
  531. }
  532. }