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.

592 lines
15 KiB

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