AppSettingsController.php 17 KB

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