Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

AppManager.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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], true);
  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. $previousSetting = $this->appConfig->getValue($appId, 'enabled', 'yes');
  344. if ($previousSetting !== 'yes' && $previousSetting !== 'no') {
  345. $previousSetting = json_decode($previousSetting, true);
  346. }
  347. $this->autoDisabledApps[$appId] = $previousSetting;
  348. }
  349. unset($this->installedAppsCache[$appId]);
  350. $this->appConfig->setValue($appId, 'enabled', 'no');
  351. // run uninstall steps
  352. $appData = $this->getAppInfo($appId);
  353. if (!is_null($appData)) {
  354. \OC_App::executeRepairSteps($appId, $appData['repair-steps']['uninstall']);
  355. }
  356. $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
  357. ManagerEvent::EVENT_APP_DISABLE, $appId
  358. ));
  359. $this->clearAppsCache();
  360. }
  361. /**
  362. * Get the directory for the given app.
  363. *
  364. * @param string $appId
  365. * @return string
  366. * @throws AppPathNotFoundException if app folder can't be found
  367. */
  368. public function getAppPath($appId) {
  369. $appPath = \OC_App::getAppPath($appId);
  370. if ($appPath === false) {
  371. throw new AppPathNotFoundException('Could not find path for ' . $appId);
  372. }
  373. return $appPath;
  374. }
  375. /**
  376. * Get the web path for the given app.
  377. *
  378. * @param string $appId
  379. * @return string
  380. * @throws AppPathNotFoundException if app path can't be found
  381. */
  382. public function getAppWebPath(string $appId): string {
  383. $appWebPath = \OC_App::getAppWebPath($appId);
  384. if ($appWebPath === false) {
  385. throw new AppPathNotFoundException('Could not find web path for ' . $appId);
  386. }
  387. return $appWebPath;
  388. }
  389. /**
  390. * Clear the cached list of apps when enabling/disabling an app
  391. */
  392. public function clearAppsCache() {
  393. $settingsMemCache = $this->memCacheFactory->createDistributed('settings');
  394. $settingsMemCache->clear('listApps');
  395. $this->appInfos = [];
  396. }
  397. /**
  398. * Returns a list of apps that need upgrade
  399. *
  400. * @param string $version Nextcloud version as array of version components
  401. * @return array list of app info from apps that need an upgrade
  402. *
  403. * @internal
  404. */
  405. public function getAppsNeedingUpgrade($version) {
  406. $appsToUpgrade = [];
  407. $apps = $this->getInstalledApps();
  408. foreach ($apps as $appId) {
  409. $appInfo = $this->getAppInfo($appId);
  410. $appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
  411. if ($appDbVersion
  412. && isset($appInfo['version'])
  413. && version_compare($appInfo['version'], $appDbVersion, '>')
  414. && \OC_App::isAppCompatible($version, $appInfo)
  415. ) {
  416. $appsToUpgrade[] = $appInfo;
  417. }
  418. }
  419. return $appsToUpgrade;
  420. }
  421. /**
  422. * Returns the app information from "appinfo/info.xml".
  423. *
  424. * @param string $appId app id
  425. *
  426. * @param bool $path
  427. * @param null $lang
  428. * @return array|null app info
  429. */
  430. public function getAppInfo(string $appId, bool $path = false, $lang = null) {
  431. if ($path) {
  432. $file = $appId;
  433. } else {
  434. if ($lang === null && isset($this->appInfos[$appId])) {
  435. return $this->appInfos[$appId];
  436. }
  437. try {
  438. $appPath = $this->getAppPath($appId);
  439. } catch (AppPathNotFoundException $e) {
  440. return null;
  441. }
  442. $file = $appPath . '/appinfo/info.xml';
  443. }
  444. $parser = new InfoParser($this->memCacheFactory->createLocal('core.appinfo'));
  445. $data = $parser->parse($file);
  446. if (is_array($data)) {
  447. $data = \OC_App::parseAppInfo($data, $lang);
  448. }
  449. if ($lang === null) {
  450. $this->appInfos[$appId] = $data;
  451. }
  452. return $data;
  453. }
  454. public function getAppVersion(string $appId, bool $useCache = true): string {
  455. if (!$useCache || !isset($this->appVersions[$appId])) {
  456. $appInfo = $this->getAppInfo($appId);
  457. $this->appVersions[$appId] = ($appInfo !== null && isset($appInfo['version'])) ? $appInfo['version'] : '0';
  458. }
  459. return $this->appVersions[$appId];
  460. }
  461. /**
  462. * Returns a list of apps incompatible with the given version
  463. *
  464. * @param string $version Nextcloud version as array of version components
  465. *
  466. * @return array list of app info from incompatible apps
  467. *
  468. * @internal
  469. */
  470. public function getIncompatibleApps(string $version): array {
  471. $apps = $this->getInstalledApps();
  472. $incompatibleApps = [];
  473. foreach ($apps as $appId) {
  474. $info = $this->getAppInfo($appId);
  475. if ($info === null) {
  476. $incompatibleApps[] = ['id' => $appId, 'name' => $appId];
  477. } elseif (!\OC_App::isAppCompatible($version, $info)) {
  478. $incompatibleApps[] = $info;
  479. }
  480. }
  481. return $incompatibleApps;
  482. }
  483. /**
  484. * @inheritdoc
  485. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::isShipped()
  486. */
  487. public function isShipped($appId) {
  488. $this->loadShippedJson();
  489. return in_array($appId, $this->shippedApps, true);
  490. }
  491. private function isAlwaysEnabled($appId) {
  492. $alwaysEnabled = $this->getAlwaysEnabledApps();
  493. return in_array($appId, $alwaysEnabled, true);
  494. }
  495. /**
  496. * In case you change this method, also change \OC\App\CodeChecker\InfoChecker::loadShippedJson()
  497. * @throws \Exception
  498. */
  499. private function loadShippedJson() {
  500. if ($this->shippedApps === null) {
  501. $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
  502. if (!file_exists($shippedJson)) {
  503. throw new \Exception("File not found: $shippedJson");
  504. }
  505. $content = json_decode(file_get_contents($shippedJson), true);
  506. $this->shippedApps = $content['shippedApps'];
  507. $this->alwaysEnabled = $content['alwaysEnabled'];
  508. }
  509. }
  510. /**
  511. * @inheritdoc
  512. */
  513. public function getAlwaysEnabledApps() {
  514. $this->loadShippedJson();
  515. return $this->alwaysEnabled;
  516. }
  517. }