AppManager.php 15 KB

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