1
0

AppSettingsController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Settings\Controller;
  8. use OC\App\AppStore\Bundles\BundleFetcher;
  9. use OC\App\AppStore\Fetcher\AppDiscoverFetcher;
  10. use OC\App\AppStore\Fetcher\AppFetcher;
  11. use OC\App\AppStore\Fetcher\CategoryFetcher;
  12. use OC\App\AppStore\Version\VersionParser;
  13. use OC\App\DependencyAnalyzer;
  14. use OC\App\Platform;
  15. use OC\Installer;
  16. use OC_App;
  17. use OCP\App\AppPathNotFoundException;
  18. use OCP\App\IAppManager;
  19. use OCP\AppFramework\Controller;
  20. use OCP\AppFramework\Http;
  21. use OCP\AppFramework\Http\Attribute\OpenAPI;
  22. use OCP\AppFramework\Http\ContentSecurityPolicy;
  23. use OCP\AppFramework\Http\FileDisplayResponse;
  24. use OCP\AppFramework\Http\JSONResponse;
  25. use OCP\AppFramework\Http\NotFoundResponse;
  26. use OCP\AppFramework\Http\Response;
  27. use OCP\AppFramework\Http\TemplateResponse;
  28. use OCP\AppFramework\Services\IInitialState;
  29. use OCP\Files\AppData\IAppDataFactory;
  30. use OCP\Files\IAppData;
  31. use OCP\Files\NotFoundException;
  32. use OCP\Files\NotPermittedException;
  33. use OCP\Files\SimpleFS\ISimpleFile;
  34. use OCP\Files\SimpleFS\ISimpleFolder;
  35. use OCP\Http\Client\IClientService;
  36. use OCP\IConfig;
  37. use OCP\IL10N;
  38. use OCP\INavigationManager;
  39. use OCP\IRequest;
  40. use OCP\IURLGenerator;
  41. use OCP\L10N\IFactory;
  42. use Psr\Log\LoggerInterface;
  43. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  44. class AppSettingsController extends Controller {
  45. /** @var array */
  46. private $allApps = [];
  47. private IAppData $appData;
  48. public function __construct(
  49. string $appName,
  50. IRequest $request,
  51. IAppDataFactory $appDataFactory,
  52. private IL10N $l10n,
  53. private IConfig $config,
  54. private INavigationManager $navigationManager,
  55. private IAppManager $appManager,
  56. private CategoryFetcher $categoryFetcher,
  57. private AppFetcher $appFetcher,
  58. private IFactory $l10nFactory,
  59. private BundleFetcher $bundleFetcher,
  60. private Installer $installer,
  61. private IURLGenerator $urlGenerator,
  62. private LoggerInterface $logger,
  63. private IInitialState $initialState,
  64. private AppDiscoverFetcher $discoverFetcher,
  65. private IClientService $clientService,
  66. ) {
  67. parent::__construct($appName, $request);
  68. $this->appData = $appDataFactory->get('appstore');
  69. }
  70. /**
  71. * @NoCSRFRequired
  72. *
  73. * @return TemplateResponse
  74. */
  75. public function viewApps(): TemplateResponse {
  76. $this->navigationManager->setActiveEntry('core_apps');
  77. $this->initialState->provideInitialState('appstoreEnabled', $this->config->getSystemValueBool('appstoreenabled', true));
  78. $this->initialState->provideInitialState('appstoreBundles', $this->getBundles());
  79. $this->initialState->provideInitialState('appstoreDeveloperDocs', $this->urlGenerator->linkToDocs('developer-manual'));
  80. $this->initialState->provideInitialState('appstoreUpdateCount', count($this->getAppsWithUpdates()));
  81. $policy = new ContentSecurityPolicy();
  82. $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
  83. $templateResponse = new TemplateResponse('settings', 'settings/empty', ['pageTitle' => $this->l10n->t('Settings')]);
  84. $templateResponse->setContentSecurityPolicy($policy);
  85. \OCP\Util::addStyle('settings', 'settings');
  86. \OCP\Util::addScript('settings', 'vue-settings-apps-users-management');
  87. return $templateResponse;
  88. }
  89. /**
  90. * Get all active entries for the app discover section
  91. *
  92. * @NoCSRFRequired
  93. */
  94. public function getAppDiscoverJSON(): JSONResponse {
  95. $data = $this->discoverFetcher->get(true);
  96. return new JSONResponse($data);
  97. }
  98. /**
  99. * @PublicPage
  100. * @NoCSRFRequired
  101. *
  102. * Get a image for the app discover section - this is proxied for privacy and CSP reasons
  103. *
  104. * @param string $image
  105. * @throws \Exception
  106. */
  107. public function getAppDiscoverMedia(string $fileName): Response {
  108. $etag = $this->discoverFetcher->getETag() ?? date('Y-m');
  109. $folder = null;
  110. try {
  111. $folder = $this->appData->getFolder('app-discover-cache');
  112. $this->cleanUpImageCache($folder, $etag);
  113. } catch (\Throwable $e) {
  114. $folder = $this->appData->newFolder('app-discover-cache');
  115. }
  116. // Get the current cache folder
  117. try {
  118. $folder = $folder->getFolder($etag);
  119. } catch (NotFoundException $e) {
  120. $folder = $folder->newFolder($etag);
  121. }
  122. $info = pathinfo($fileName);
  123. $hashName = md5($fileName);
  124. $allFiles = $folder->getDirectoryListing();
  125. // Try to find the file
  126. $file = array_filter($allFiles, function (ISimpleFile $file) use ($hashName) {
  127. return str_starts_with($file->getName(), $hashName);
  128. });
  129. // Get the first entry
  130. $file = reset($file);
  131. // If not found request from Web
  132. if ($file === false) {
  133. try {
  134. $client = $this->clientService->newClient();
  135. $fileResponse = $client->get($fileName);
  136. $contentType = $fileResponse->getHeader('Content-Type');
  137. $extension = $info['extension'] ?? '';
  138. $file = $folder->newFile($hashName . '.' . base64_encode($contentType) . '.' . $extension, $fileResponse->getBody());
  139. } catch (\Throwable $e) {
  140. $this->logger->warning('Could not load media file for app discover section', ['media_src' => $fileName, 'exception' => $e]);
  141. return new NotFoundResponse();
  142. }
  143. } else {
  144. // File was found so we can get the content type from the file name
  145. $contentType = base64_decode(explode('.', $file->getName())[1] ?? '');
  146. }
  147. $response = new FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => $contentType]);
  148. // cache for 7 days
  149. $response->cacheFor(604800, false, true);
  150. return $response;
  151. }
  152. /**
  153. * Remove orphaned folders from the image cache that do not match the current etag
  154. * @param ISimpleFolder $folder The folder to clear
  155. * @param string $etag The etag (directory name) to keep
  156. */
  157. private function cleanUpImageCache(ISimpleFolder $folder, string $etag): void {
  158. // Cleanup old cache folders
  159. $allFiles = $folder->getDirectoryListing();
  160. foreach ($allFiles as $dir) {
  161. try {
  162. if ($dir->getName() !== $etag) {
  163. $dir->delete();
  164. }
  165. } catch (NotPermittedException $e) {
  166. // ignore folder for now
  167. }
  168. }
  169. }
  170. private function getAppsWithUpdates() {
  171. $appClass = new \OC_App();
  172. $apps = $appClass->listAllApps();
  173. foreach ($apps as $key => $app) {
  174. $newVersion = $this->installer->isUpdateAvailable($app['id']);
  175. if ($newVersion === false) {
  176. unset($apps[$key]);
  177. }
  178. }
  179. return $apps;
  180. }
  181. private function getBundles() {
  182. $result = [];
  183. $bundles = $this->bundleFetcher->getBundles();
  184. foreach ($bundles as $bundle) {
  185. $result[] = [
  186. 'name' => $bundle->getName(),
  187. 'id' => $bundle->getIdentifier(),
  188. 'appIdentifiers' => $bundle->getAppIdentifiers()
  189. ];
  190. }
  191. return $result;
  192. }
  193. /**
  194. * Get all available categories
  195. *
  196. * @return JSONResponse
  197. */
  198. public function listCategories(): JSONResponse {
  199. return new JSONResponse($this->getAllCategories());
  200. }
  201. private function getAllCategories() {
  202. $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
  203. $categories = $this->categoryFetcher->get();
  204. return array_map(fn ($category) => [
  205. 'id' => $category['id'],
  206. 'displayName' => $category['translations'][$currentLanguage]['name'] ?? $category['translations']['en']['name'],
  207. ], $categories);
  208. }
  209. private function fetchApps() {
  210. $appClass = new \OC_App();
  211. $apps = $appClass->listAllApps();
  212. foreach ($apps as $app) {
  213. $app['installed'] = true;
  214. $this->allApps[$app['id']] = $app;
  215. }
  216. $apps = $this->getAppsForCategory('');
  217. $supportedApps = $appClass->getSupportedApps();
  218. foreach ($apps as $app) {
  219. $app['appstore'] = true;
  220. if (!array_key_exists($app['id'], $this->allApps)) {
  221. $this->allApps[$app['id']] = $app;
  222. } else {
  223. $this->allApps[$app['id']] = array_merge($app, $this->allApps[$app['id']]);
  224. }
  225. if (in_array($app['id'], $supportedApps)) {
  226. $this->allApps[$app['id']]['level'] = \OC_App::supportedApp;
  227. }
  228. }
  229. // add bundle information
  230. $bundles = $this->bundleFetcher->getBundles();
  231. foreach ($bundles as $bundle) {
  232. foreach ($bundle->getAppIdentifiers() as $identifier) {
  233. foreach ($this->allApps as &$app) {
  234. if ($app['id'] === $identifier) {
  235. $app['bundleIds'][] = $bundle->getIdentifier();
  236. continue;
  237. }
  238. }
  239. }
  240. }
  241. }
  242. private function getAllApps() {
  243. return $this->allApps;
  244. }
  245. /**
  246. * Get all available apps in a category
  247. *
  248. * @return JSONResponse
  249. * @throws \Exception
  250. */
  251. public function listApps(): JSONResponse {
  252. $this->fetchApps();
  253. $apps = $this->getAllApps();
  254. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
  255. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  256. if (!is_array($ignoreMaxApps)) {
  257. $this->logger->warning('The value given for app_install_overwrite is not an array. Ignoring...');
  258. $ignoreMaxApps = [];
  259. }
  260. // Extend existing app details
  261. $apps = array_map(function (array $appData) use ($dependencyAnalyzer, $ignoreMaxApps) {
  262. if (isset($appData['appstoreData'])) {
  263. $appstoreData = $appData['appstoreData'];
  264. $appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/' . base64_encode($appstoreData['screenshots'][0]['url']) : '';
  265. $appData['category'] = $appstoreData['categories'];
  266. $appData['releases'] = $appstoreData['releases'];
  267. }
  268. $newVersion = $this->installer->isUpdateAvailable($appData['id']);
  269. if ($newVersion) {
  270. $appData['update'] = $newVersion;
  271. }
  272. // fix groups to be an array
  273. $groups = [];
  274. if (is_string($appData['groups'])) {
  275. $groups = json_decode($appData['groups']);
  276. }
  277. $appData['groups'] = $groups;
  278. $appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
  279. // fix licence vs license
  280. if (isset($appData['license']) && !isset($appData['licence'])) {
  281. $appData['licence'] = $appData['license'];
  282. }
  283. $ignoreMax = in_array($appData['id'], $ignoreMaxApps);
  284. // analyse dependencies
  285. $missing = $dependencyAnalyzer->analyze($appData, $ignoreMax);
  286. $appData['canInstall'] = empty($missing);
  287. $appData['missingDependencies'] = $missing;
  288. $appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
  289. $appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
  290. $appData['isCompatible'] = $dependencyAnalyzer->isMarkedCompatible($appData);
  291. return $appData;
  292. }, $apps);
  293. usort($apps, [$this, 'sortApps']);
  294. return new JSONResponse(['apps' => $apps, 'status' => 'success']);
  295. }
  296. /**
  297. * Get all apps for a category from the app store
  298. *
  299. * @param string $requestedCategory
  300. * @return array
  301. * @throws \Exception
  302. */
  303. private function getAppsForCategory($requestedCategory = ''): array {
  304. $versionParser = new VersionParser();
  305. $formattedApps = [];
  306. $apps = $this->appFetcher->get();
  307. foreach ($apps as $app) {
  308. // Skip all apps not in the requested category
  309. if ($requestedCategory !== '') {
  310. $isInCategory = false;
  311. foreach ($app['categories'] as $category) {
  312. if ($category === $requestedCategory) {
  313. $isInCategory = true;
  314. }
  315. }
  316. if (!$isInCategory) {
  317. continue;
  318. }
  319. }
  320. if (!isset($app['releases'][0]['rawPlatformVersionSpec'])) {
  321. continue;
  322. }
  323. $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
  324. $nextCloudVersionDependencies = [];
  325. if ($nextCloudVersion->getMinimumVersion() !== '') {
  326. $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
  327. }
  328. if ($nextCloudVersion->getMaximumVersion() !== '') {
  329. $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
  330. }
  331. $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
  332. try {
  333. $this->appManager->getAppPath($app['id']);
  334. $existsLocally = true;
  335. } catch (AppPathNotFoundException) {
  336. $existsLocally = false;
  337. }
  338. $phpDependencies = [];
  339. if ($phpVersion->getMinimumVersion() !== '') {
  340. $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
  341. }
  342. if ($phpVersion->getMaximumVersion() !== '') {
  343. $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
  344. }
  345. if (isset($app['releases'][0]['minIntSize'])) {
  346. $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
  347. }
  348. $authors = '';
  349. foreach ($app['authors'] as $key => $author) {
  350. $authors .= $author['name'];
  351. if ($key !== count($app['authors']) - 1) {
  352. $authors .= ', ';
  353. }
  354. }
  355. $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
  356. $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
  357. $groups = null;
  358. if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
  359. $groups = $enabledValue;
  360. }
  361. $currentVersion = '';
  362. if ($this->appManager->isInstalled($app['id'])) {
  363. $currentVersion = $this->appManager->getAppVersion($app['id']);
  364. } else {
  365. $currentVersion = $app['releases'][0]['version'];
  366. }
  367. $formattedApps[] = [
  368. 'id' => $app['id'],
  369. 'name' => $app['translations'][$currentLanguage]['name'] ?? $app['translations']['en']['name'],
  370. 'description' => $app['translations'][$currentLanguage]['description'] ?? $app['translations']['en']['description'],
  371. 'summary' => $app['translations'][$currentLanguage]['summary'] ?? $app['translations']['en']['summary'],
  372. 'license' => $app['releases'][0]['licenses'],
  373. 'author' => $authors,
  374. 'shipped' => false,
  375. 'version' => $currentVersion,
  376. 'default_enable' => '',
  377. 'types' => [],
  378. 'documentation' => [
  379. 'admin' => $app['adminDocs'],
  380. 'user' => $app['userDocs'],
  381. 'developer' => $app['developerDocs']
  382. ],
  383. 'website' => $app['website'],
  384. 'bugs' => $app['issueTracker'],
  385. 'detailpage' => $app['website'],
  386. 'dependencies' => array_merge(
  387. $nextCloudVersionDependencies,
  388. $phpDependencies
  389. ),
  390. 'level' => ($app['isFeatured'] === true) ? 200 : 100,
  391. 'missingMaxOwnCloudVersion' => false,
  392. 'missingMinOwnCloudVersion' => false,
  393. 'canInstall' => true,
  394. 'screenshot' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
  395. 'score' => $app['ratingOverall'],
  396. 'ratingNumOverall' => $app['ratingNumOverall'],
  397. 'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
  398. 'removable' => $existsLocally,
  399. 'active' => $this->appManager->isEnabledForUser($app['id']),
  400. 'needsDownload' => !$existsLocally,
  401. 'groups' => $groups,
  402. 'fromAppStore' => true,
  403. 'appstoreData' => $app,
  404. ];
  405. }
  406. return $formattedApps;
  407. }
  408. /**
  409. * @PasswordConfirmationRequired
  410. *
  411. * @param string $appId
  412. * @param array $groups
  413. * @return JSONResponse
  414. */
  415. public function enableApp(string $appId, array $groups = []): JSONResponse {
  416. return $this->enableApps([$appId], $groups);
  417. }
  418. /**
  419. * Enable one or more apps
  420. *
  421. * apps will be enabled for specific groups only if $groups is defined
  422. *
  423. * @PasswordConfirmationRequired
  424. * @param array $appIds
  425. * @param array $groups
  426. * @return JSONResponse
  427. */
  428. public function enableApps(array $appIds, array $groups = []): JSONResponse {
  429. try {
  430. $updateRequired = false;
  431. foreach ($appIds as $appId) {
  432. $appId = OC_App::cleanAppId($appId);
  433. // Check if app is already downloaded
  434. /** @var Installer $installer */
  435. $installer = \OC::$server->get(Installer::class);
  436. $isDownloaded = $installer->isDownloaded($appId);
  437. if (!$isDownloaded) {
  438. $installer->downloadApp($appId);
  439. }
  440. $installer->installApp($appId);
  441. if (count($groups) > 0) {
  442. $this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
  443. } else {
  444. $this->appManager->enableApp($appId);
  445. }
  446. if (\OC_App::shouldUpgrade($appId)) {
  447. $updateRequired = true;
  448. }
  449. }
  450. return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
  451. } catch (\Throwable $e) {
  452. $this->logger->error('could not enable apps', ['exception' => $e]);
  453. return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  454. }
  455. }
  456. private function getGroupList(array $groups) {
  457. $groupManager = \OC::$server->getGroupManager();
  458. $groupsList = [];
  459. foreach ($groups as $group) {
  460. $groupItem = $groupManager->get($group);
  461. if ($groupItem instanceof \OCP\IGroup) {
  462. $groupsList[] = $groupManager->get($group);
  463. }
  464. }
  465. return $groupsList;
  466. }
  467. /**
  468. * @PasswordConfirmationRequired
  469. *
  470. * @param string $appId
  471. * @return JSONResponse
  472. */
  473. public function disableApp(string $appId): JSONResponse {
  474. return $this->disableApps([$appId]);
  475. }
  476. /**
  477. * @PasswordConfirmationRequired
  478. *
  479. * @param array $appIds
  480. * @return JSONResponse
  481. */
  482. public function disableApps(array $appIds): JSONResponse {
  483. try {
  484. foreach ($appIds as $appId) {
  485. $appId = OC_App::cleanAppId($appId);
  486. $this->appManager->disableApp($appId);
  487. }
  488. return new JSONResponse([]);
  489. } catch (\Exception $e) {
  490. $this->logger->error('could not disable app', ['exception' => $e]);
  491. return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  492. }
  493. }
  494. /**
  495. * @PasswordConfirmationRequired
  496. *
  497. * @param string $appId
  498. * @return JSONResponse
  499. */
  500. public function uninstallApp(string $appId): JSONResponse {
  501. $appId = OC_App::cleanAppId($appId);
  502. $result = $this->installer->removeApp($appId);
  503. if ($result !== false) {
  504. $this->appManager->clearAppsCache();
  505. return new JSONResponse(['data' => ['appid' => $appId]]);
  506. }
  507. return new JSONResponse(['data' => ['message' => $this->l10n->t('Could not remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
  508. }
  509. /**
  510. * @param string $appId
  511. * @return JSONResponse
  512. */
  513. public function updateApp(string $appId): JSONResponse {
  514. $appId = OC_App::cleanAppId($appId);
  515. $this->config->setSystemValue('maintenance', true);
  516. try {
  517. $result = $this->installer->updateAppstoreApp($appId);
  518. $this->config->setSystemValue('maintenance', false);
  519. } catch (\Exception $ex) {
  520. $this->config->setSystemValue('maintenance', false);
  521. return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  522. }
  523. if ($result !== false) {
  524. return new JSONResponse(['data' => ['appid' => $appId]]);
  525. }
  526. return new JSONResponse(['data' => ['message' => $this->l10n->t('Could not update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
  527. }
  528. private function sortApps($a, $b) {
  529. $a = (string)$a['name'];
  530. $b = (string)$b['name'];
  531. if ($a === $b) {
  532. return 0;
  533. }
  534. return ($a < $b) ? -1 : 1;
  535. }
  536. public function force(string $appId): JSONResponse {
  537. $appId = OC_App::cleanAppId($appId);
  538. $this->appManager->ignoreNextcloudRequirementForApp($appId);
  539. return new JSONResponse();
  540. }
  541. }