1
0

AppSettingsController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Roeland Jago Douma <roeland@famdouma.nl>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Kate Döen <kate.doeen@nextcloud.com>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\Settings\Controller;
  34. use OC\App\AppStore\Bundles\BundleFetcher;
  35. use OC\App\AppStore\Fetcher\AppFetcher;
  36. use OC\App\AppStore\Fetcher\CategoryFetcher;
  37. use OC\App\AppStore\Version\VersionParser;
  38. use OC\App\DependencyAnalyzer;
  39. use OC\App\Platform;
  40. use OC\Installer;
  41. use OC_App;
  42. use OCP\App\IAppManager;
  43. use OCP\AppFramework\Controller;
  44. use OCP\AppFramework\Http;
  45. use OCP\AppFramework\Http\Attribute\OpenAPI;
  46. use OCP\AppFramework\Http\ContentSecurityPolicy;
  47. use OCP\AppFramework\Http\JSONResponse;
  48. use OCP\AppFramework\Http\TemplateResponse;
  49. use OCP\IConfig;
  50. use OCP\IL10N;
  51. use OCP\INavigationManager;
  52. use OCP\IRequest;
  53. use OCP\IURLGenerator;
  54. use OCP\L10N\IFactory;
  55. use Psr\Log\LoggerInterface;
  56. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  57. class AppSettingsController extends Controller {
  58. /** @var \OCP\IL10N */
  59. private $l10n;
  60. /** @var IConfig */
  61. private $config;
  62. /** @var INavigationManager */
  63. private $navigationManager;
  64. /** @var IAppManager */
  65. private $appManager;
  66. /** @var CategoryFetcher */
  67. private $categoryFetcher;
  68. /** @var AppFetcher */
  69. private $appFetcher;
  70. /** @var IFactory */
  71. private $l10nFactory;
  72. /** @var BundleFetcher */
  73. private $bundleFetcher;
  74. /** @var Installer */
  75. private $installer;
  76. /** @var IURLGenerator */
  77. private $urlGenerator;
  78. /** @var LoggerInterface */
  79. private $logger;
  80. /** @var array */
  81. private $allApps = [];
  82. /**
  83. * @param string $appName
  84. * @param IRequest $request
  85. * @param IL10N $l10n
  86. * @param IConfig $config
  87. * @param INavigationManager $navigationManager
  88. * @param IAppManager $appManager
  89. * @param CategoryFetcher $categoryFetcher
  90. * @param AppFetcher $appFetcher
  91. * @param IFactory $l10nFactory
  92. * @param BundleFetcher $bundleFetcher
  93. * @param Installer $installer
  94. * @param IURLGenerator $urlGenerator
  95. * @param LoggerInterface $logger
  96. */
  97. public function __construct(string $appName,
  98. IRequest $request,
  99. IL10N $l10n,
  100. IConfig $config,
  101. INavigationManager $navigationManager,
  102. IAppManager $appManager,
  103. CategoryFetcher $categoryFetcher,
  104. AppFetcher $appFetcher,
  105. IFactory $l10nFactory,
  106. BundleFetcher $bundleFetcher,
  107. Installer $installer,
  108. IURLGenerator $urlGenerator,
  109. LoggerInterface $logger) {
  110. parent::__construct($appName, $request);
  111. $this->l10n = $l10n;
  112. $this->config = $config;
  113. $this->navigationManager = $navigationManager;
  114. $this->appManager = $appManager;
  115. $this->categoryFetcher = $categoryFetcher;
  116. $this->appFetcher = $appFetcher;
  117. $this->l10nFactory = $l10nFactory;
  118. $this->bundleFetcher = $bundleFetcher;
  119. $this->installer = $installer;
  120. $this->urlGenerator = $urlGenerator;
  121. $this->logger = $logger;
  122. }
  123. /**
  124. * @NoCSRFRequired
  125. *
  126. * @return TemplateResponse
  127. */
  128. public function viewApps(): TemplateResponse {
  129. $params = [];
  130. $params['appstoreEnabled'] = $this->config->getSystemValueBool('appstoreenabled', true);
  131. $params['updateCount'] = count($this->getAppsWithUpdates());
  132. $params['developerDocumentation'] = $this->urlGenerator->linkToDocs('developer-manual');
  133. $params['bundles'] = $this->getBundles();
  134. $this->navigationManager->setActiveEntry('core_apps');
  135. $templateResponse = new TemplateResponse('settings', 'settings-vue', ['serverData' => $params, 'pageTitle' => $this->l10n->t('Apps')]);
  136. $policy = new ContentSecurityPolicy();
  137. $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
  138. $templateResponse->setContentSecurityPolicy($policy);
  139. return $templateResponse;
  140. }
  141. private function getAppsWithUpdates() {
  142. $appClass = new \OC_App();
  143. $apps = $appClass->listAllApps();
  144. foreach ($apps as $key => $app) {
  145. $newVersion = $this->installer->isUpdateAvailable($app['id']);
  146. if ($newVersion === false) {
  147. unset($apps[$key]);
  148. }
  149. }
  150. return $apps;
  151. }
  152. private function getBundles() {
  153. $result = [];
  154. $bundles = $this->bundleFetcher->getBundles();
  155. foreach ($bundles as $bundle) {
  156. $result[] = [
  157. 'name' => $bundle->getName(),
  158. 'id' => $bundle->getIdentifier(),
  159. 'appIdentifiers' => $bundle->getAppIdentifiers()
  160. ];
  161. }
  162. return $result;
  163. }
  164. /**
  165. * Get all available categories
  166. *
  167. * @return JSONResponse
  168. */
  169. public function listCategories(): JSONResponse {
  170. return new JSONResponse($this->getAllCategories());
  171. }
  172. private function getAllCategories() {
  173. $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
  174. $formattedCategories = [];
  175. $categories = $this->categoryFetcher->get();
  176. foreach ($categories as $category) {
  177. $formattedCategories[] = [
  178. 'id' => $category['id'],
  179. 'ident' => $category['id'],
  180. 'displayName' => $category['translations'][$currentLanguage]['name'] ?? $category['translations']['en']['name'],
  181. ];
  182. }
  183. return $formattedCategories;
  184. }
  185. private function fetchApps() {
  186. $appClass = new \OC_App();
  187. $apps = $appClass->listAllApps();
  188. foreach ($apps as $app) {
  189. $app['installed'] = true;
  190. $this->allApps[$app['id']] = $app;
  191. }
  192. $apps = $this->getAppsForCategory('');
  193. $supportedApps = $appClass->getSupportedApps();
  194. foreach ($apps as $app) {
  195. $app['appstore'] = true;
  196. if (!array_key_exists($app['id'], $this->allApps)) {
  197. $this->allApps[$app['id']] = $app;
  198. } else {
  199. $this->allApps[$app['id']] = array_merge($app, $this->allApps[$app['id']]);
  200. }
  201. if (in_array($app['id'], $supportedApps)) {
  202. $this->allApps[$app['id']]['level'] = \OC_App::supportedApp;
  203. }
  204. }
  205. // add bundle information
  206. $bundles = $this->bundleFetcher->getBundles();
  207. foreach ($bundles as $bundle) {
  208. foreach ($bundle->getAppIdentifiers() as $identifier) {
  209. foreach ($this->allApps as &$app) {
  210. if ($app['id'] === $identifier) {
  211. $app['bundleIds'][] = $bundle->getIdentifier();
  212. continue;
  213. }
  214. }
  215. }
  216. }
  217. }
  218. private function getAllApps() {
  219. return $this->allApps;
  220. }
  221. /**
  222. * Get all available apps in a category
  223. *
  224. * @return JSONResponse
  225. * @throws \Exception
  226. */
  227. public function listApps(): JSONResponse {
  228. $this->fetchApps();
  229. $apps = $this->getAllApps();
  230. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
  231. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  232. if (!is_array($ignoreMaxApps)) {
  233. $this->logger->warning('The value given for app_install_overwrite is not an array. Ignoring...');
  234. $ignoreMaxApps = [];
  235. }
  236. // Extend existing app details
  237. $apps = array_map(function (array $appData) use ($dependencyAnalyzer, $ignoreMaxApps) {
  238. if (isset($appData['appstoreData'])) {
  239. $appstoreData = $appData['appstoreData'];
  240. $appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/' . base64_encode($appstoreData['screenshots'][0]['url']) : '';
  241. $appData['category'] = $appstoreData['categories'];
  242. $appData['releases'] = $appstoreData['releases'];
  243. }
  244. $newVersion = $this->installer->isUpdateAvailable($appData['id']);
  245. if ($newVersion) {
  246. $appData['update'] = $newVersion;
  247. }
  248. // fix groups to be an array
  249. $groups = [];
  250. if (is_string($appData['groups'])) {
  251. $groups = json_decode($appData['groups']);
  252. }
  253. $appData['groups'] = $groups;
  254. $appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
  255. // fix licence vs license
  256. if (isset($appData['license']) && !isset($appData['licence'])) {
  257. $appData['licence'] = $appData['license'];
  258. }
  259. $ignoreMax = in_array($appData['id'], $ignoreMaxApps);
  260. // analyse dependencies
  261. $missing = $dependencyAnalyzer->analyze($appData, $ignoreMax);
  262. $appData['canInstall'] = empty($missing);
  263. $appData['missingDependencies'] = $missing;
  264. $appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
  265. $appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
  266. $appData['isCompatible'] = $dependencyAnalyzer->isMarkedCompatible($appData);
  267. return $appData;
  268. }, $apps);
  269. usort($apps, [$this, 'sortApps']);
  270. return new JSONResponse(['apps' => $apps, 'status' => 'success']);
  271. }
  272. /**
  273. * Get all apps for a category from the app store
  274. *
  275. * @param string $requestedCategory
  276. * @return array
  277. * @throws \Exception
  278. */
  279. private function getAppsForCategory($requestedCategory = ''): array {
  280. $versionParser = new VersionParser();
  281. $formattedApps = [];
  282. $apps = $this->appFetcher->get();
  283. foreach ($apps as $app) {
  284. // Skip all apps not in the requested category
  285. if ($requestedCategory !== '') {
  286. $isInCategory = false;
  287. foreach ($app['categories'] as $category) {
  288. if ($category === $requestedCategory) {
  289. $isInCategory = true;
  290. }
  291. }
  292. if (!$isInCategory) {
  293. continue;
  294. }
  295. }
  296. if (!isset($app['releases'][0]['rawPlatformVersionSpec'])) {
  297. continue;
  298. }
  299. $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
  300. $nextCloudVersionDependencies = [];
  301. if ($nextCloudVersion->getMinimumVersion() !== '') {
  302. $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
  303. }
  304. if ($nextCloudVersion->getMaximumVersion() !== '') {
  305. $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
  306. }
  307. $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
  308. $existsLocally = \OC_App::getAppPath($app['id']) !== false;
  309. $phpDependencies = [];
  310. if ($phpVersion->getMinimumVersion() !== '') {
  311. $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
  312. }
  313. if ($phpVersion->getMaximumVersion() !== '') {
  314. $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
  315. }
  316. if (isset($app['releases'][0]['minIntSize'])) {
  317. $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
  318. }
  319. $authors = '';
  320. foreach ($app['authors'] as $key => $author) {
  321. $authors .= $author['name'];
  322. if ($key !== count($app['authors']) - 1) {
  323. $authors .= ', ';
  324. }
  325. }
  326. $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
  327. $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
  328. $groups = null;
  329. if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
  330. $groups = $enabledValue;
  331. }
  332. $currentVersion = '';
  333. if ($this->appManager->isInstalled($app['id'])) {
  334. $currentVersion = $this->appManager->getAppVersion($app['id']);
  335. } else {
  336. $currentVersion = $app['releases'][0]['version'];
  337. }
  338. $formattedApps[] = [
  339. 'id' => $app['id'],
  340. 'name' => $app['translations'][$currentLanguage]['name'] ?? $app['translations']['en']['name'],
  341. 'description' => $app['translations'][$currentLanguage]['description'] ?? $app['translations']['en']['description'],
  342. 'summary' => $app['translations'][$currentLanguage]['summary'] ?? $app['translations']['en']['summary'],
  343. 'license' => $app['releases'][0]['licenses'],
  344. 'author' => $authors,
  345. 'shipped' => false,
  346. 'version' => $currentVersion,
  347. 'default_enable' => '',
  348. 'types' => [],
  349. 'documentation' => [
  350. 'admin' => $app['adminDocs'],
  351. 'user' => $app['userDocs'],
  352. 'developer' => $app['developerDocs']
  353. ],
  354. 'website' => $app['website'],
  355. 'bugs' => $app['issueTracker'],
  356. 'detailpage' => $app['website'],
  357. 'dependencies' => array_merge(
  358. $nextCloudVersionDependencies,
  359. $phpDependencies
  360. ),
  361. 'level' => ($app['isFeatured'] === true) ? 200 : 100,
  362. 'missingMaxOwnCloudVersion' => false,
  363. 'missingMinOwnCloudVersion' => false,
  364. 'canInstall' => true,
  365. 'screenshot' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
  366. 'score' => $app['ratingOverall'],
  367. 'ratingNumOverall' => $app['ratingNumOverall'],
  368. 'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
  369. 'removable' => $existsLocally,
  370. 'active' => $this->appManager->isEnabledForUser($app['id']),
  371. 'needsDownload' => !$existsLocally,
  372. 'groups' => $groups,
  373. 'fromAppStore' => true,
  374. 'appstoreData' => $app,
  375. ];
  376. }
  377. return $formattedApps;
  378. }
  379. /**
  380. * @PasswordConfirmationRequired
  381. *
  382. * @param string $appId
  383. * @param array $groups
  384. * @return JSONResponse
  385. */
  386. public function enableApp(string $appId, array $groups = []): JSONResponse {
  387. return $this->enableApps([$appId], $groups);
  388. }
  389. /**
  390. * Enable one or more apps
  391. *
  392. * apps will be enabled for specific groups only if $groups is defined
  393. *
  394. * @PasswordConfirmationRequired
  395. * @param array $appIds
  396. * @param array $groups
  397. * @return JSONResponse
  398. */
  399. public function enableApps(array $appIds, array $groups = []): JSONResponse {
  400. try {
  401. $updateRequired = false;
  402. foreach ($appIds as $appId) {
  403. $appId = OC_App::cleanAppId($appId);
  404. // Check if app is already downloaded
  405. /** @var Installer $installer */
  406. $installer = \OC::$server->query(Installer::class);
  407. $isDownloaded = $installer->isDownloaded($appId);
  408. if (!$isDownloaded) {
  409. $installer->downloadApp($appId);
  410. }
  411. $installer->installApp($appId);
  412. if (count($groups) > 0) {
  413. $this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
  414. } else {
  415. $this->appManager->enableApp($appId);
  416. }
  417. if (\OC_App::shouldUpgrade($appId)) {
  418. $updateRequired = true;
  419. }
  420. }
  421. return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
  422. } catch (\Exception $e) {
  423. $this->logger->error('could not enable apps', ['exception' => $e]);
  424. return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  425. }
  426. }
  427. private function getGroupList(array $groups) {
  428. $groupManager = \OC::$server->getGroupManager();
  429. $groupsList = [];
  430. foreach ($groups as $group) {
  431. $groupItem = $groupManager->get($group);
  432. if ($groupItem instanceof \OCP\IGroup) {
  433. $groupsList[] = $groupManager->get($group);
  434. }
  435. }
  436. return $groupsList;
  437. }
  438. /**
  439. * @PasswordConfirmationRequired
  440. *
  441. * @param string $appId
  442. * @return JSONResponse
  443. */
  444. public function disableApp(string $appId): JSONResponse {
  445. return $this->disableApps([$appId]);
  446. }
  447. /**
  448. * @PasswordConfirmationRequired
  449. *
  450. * @param array $appIds
  451. * @return JSONResponse
  452. */
  453. public function disableApps(array $appIds): JSONResponse {
  454. try {
  455. foreach ($appIds as $appId) {
  456. $appId = OC_App::cleanAppId($appId);
  457. $this->appManager->disableApp($appId);
  458. }
  459. return new JSONResponse([]);
  460. } catch (\Exception $e) {
  461. $this->logger->error('could not disable app', ['exception' => $e]);
  462. return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  463. }
  464. }
  465. /**
  466. * @PasswordConfirmationRequired
  467. *
  468. * @param string $appId
  469. * @return JSONResponse
  470. */
  471. public function uninstallApp(string $appId): JSONResponse {
  472. $appId = OC_App::cleanAppId($appId);
  473. $result = $this->installer->removeApp($appId);
  474. if ($result !== false) {
  475. $this->appManager->clearAppsCache();
  476. return new JSONResponse(['data' => ['appid' => $appId]]);
  477. }
  478. return new JSONResponse(['data' => ['message' => $this->l10n->t('Could not remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
  479. }
  480. /**
  481. * @param string $appId
  482. * @return JSONResponse
  483. */
  484. public function updateApp(string $appId): JSONResponse {
  485. $appId = OC_App::cleanAppId($appId);
  486. $this->config->setSystemValue('maintenance', true);
  487. try {
  488. $result = $this->installer->updateAppstoreApp($appId);
  489. $this->config->setSystemValue('maintenance', false);
  490. } catch (\Exception $ex) {
  491. $this->config->setSystemValue('maintenance', false);
  492. return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  493. }
  494. if ($result !== false) {
  495. return new JSONResponse(['data' => ['appid' => $appId]]);
  496. }
  497. return new JSONResponse(['data' => ['message' => $this->l10n->t('Could not update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
  498. }
  499. private function sortApps($a, $b) {
  500. $a = (string)$a['name'];
  501. $b = (string)$b['name'];
  502. if ($a === $b) {
  503. return 0;
  504. }
  505. return ($a < $b) ? -1 : 1;
  506. }
  507. public function force(string $appId): JSONResponse {
  508. $appId = OC_App::cleanAppId($appId);
  509. $this->appManager->ignoreNextcloudRequirementForApp($appId);
  510. return new JSONResponse();
  511. }
  512. }