AppSettingsController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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) <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\ILogger;
  50. use OCP\INavigationManager;
  51. use OCP\IRequest;
  52. use OCP\IURLGenerator;
  53. use OCP\L10N\IFactory;
  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 ILogger */
  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 ILogger $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. ILogger $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. \OC_Util::addScript('settings', 'apps');
  127. $params = [];
  128. $params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
  129. $params['updateCount'] = count($this->getAppsWithUpdates());
  130. $params['developerDocumentation'] = $this->urlGenerator->linkToDocs('developer-manual');
  131. $params['bundles'] = $this->getBundles();
  132. $this->navigationManager->setActiveEntry('core_apps');
  133. $templateResponse = new TemplateResponse('settings', 'settings-vue', ['serverData' => $params]);
  134. $policy = new ContentSecurityPolicy();
  135. $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
  136. $templateResponse->setContentSecurityPolicy($policy);
  137. return $templateResponse;
  138. }
  139. private function getAppsWithUpdates() {
  140. $appClass = new \OC_App();
  141. $apps = $appClass->listAllApps();
  142. foreach ($apps as $key => $app) {
  143. $newVersion = $this->installer->isUpdateAvailable($app['id']);
  144. if ($newVersion === false) {
  145. unset($apps[$key]);
  146. }
  147. }
  148. return $apps;
  149. }
  150. private function getBundles() {
  151. $result = [];
  152. $bundles = $this->bundleFetcher->getBundles();
  153. foreach ($bundles as $bundle) {
  154. $result[] = [
  155. 'name' => $bundle->getName(),
  156. 'id' => $bundle->getIdentifier(),
  157. 'appIdentifiers' => $bundle->getAppIdentifiers()
  158. ];
  159. }
  160. return $result;
  161. }
  162. /**
  163. * Get all available categories
  164. *
  165. * @return JSONResponse
  166. */
  167. public function listCategories(): JSONResponse {
  168. return new JSONResponse($this->getAllCategories());
  169. }
  170. private function getAllCategories() {
  171. $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
  172. $formattedCategories = [];
  173. $categories = $this->categoryFetcher->get();
  174. foreach ($categories as $category) {
  175. $formattedCategories[] = [
  176. 'id' => $category['id'],
  177. 'ident' => $category['id'],
  178. 'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
  179. ];
  180. }
  181. return $formattedCategories;
  182. }
  183. private function fetchApps() {
  184. $appClass = new \OC_App();
  185. $apps = $appClass->listAllApps();
  186. foreach ($apps as $app) {
  187. $app['installed'] = true;
  188. $this->allApps[$app['id']] = $app;
  189. }
  190. $apps = $this->getAppsForCategory('');
  191. $supportedApps = $appClass->getSupportedApps();
  192. foreach ($apps as $app) {
  193. $app['appstore'] = true;
  194. if (!array_key_exists($app['id'], $this->allApps)) {
  195. $this->allApps[$app['id']] = $app;
  196. } else {
  197. $this->allApps[$app['id']] = array_merge($app, $this->allApps[$app['id']]);
  198. }
  199. if (in_array($app['id'], $supportedApps)) {
  200. $this->allApps[$app['id']]['level'] = \OC_App::supportedApp;
  201. }
  202. }
  203. // add bundle information
  204. $bundles = $this->bundleFetcher->getBundles();
  205. foreach ($bundles as $bundle) {
  206. foreach ($bundle->getAppIdentifiers() as $identifier) {
  207. foreach ($this->allApps as &$app) {
  208. if ($app['id'] === $identifier) {
  209. $app['bundleIds'][] = $bundle->getIdentifier();
  210. continue;
  211. }
  212. }
  213. }
  214. }
  215. }
  216. private function getAllApps() {
  217. return $this->allApps;
  218. }
  219. /**
  220. * Get all available apps in a category
  221. *
  222. * @param string $category
  223. * @return JSONResponse
  224. * @throws \Exception
  225. */
  226. public function listApps(): JSONResponse {
  227. $this->fetchApps();
  228. $apps = $this->getAllApps();
  229. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
  230. // Extend existing app details
  231. $apps = array_map(function ($appData) use ($dependencyAnalyzer) {
  232. if (isset($appData['appstoreData'])) {
  233. $appstoreData = $appData['appstoreData'];
  234. $appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/' . base64_encode($appstoreData['screenshots'][0]['url']) : '';
  235. $appData['category'] = $appstoreData['categories'];
  236. $appData['releases'] = $appstoreData['releases'];
  237. }
  238. $newVersion = $this->installer->isUpdateAvailable($appData['id']);
  239. if ($newVersion) {
  240. $appData['update'] = $newVersion;
  241. }
  242. // fix groups to be an array
  243. $groups = [];
  244. if (is_string($appData['groups'])) {
  245. $groups = json_decode($appData['groups']);
  246. }
  247. $appData['groups'] = $groups;
  248. $appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
  249. // fix licence vs license
  250. if (isset($appData['license']) && !isset($appData['licence'])) {
  251. $appData['licence'] = $appData['license'];
  252. }
  253. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  254. if (!is_array($ignoreMaxApps)) {
  255. $this->logger->warning('The value given for app_install_overwrite is not an array. Ignoring...');
  256. $ignoreMaxApps = [];
  257. }
  258. $ignoreMax = in_array($appData['id'], $ignoreMaxApps);
  259. // analyse dependencies
  260. $missing = $dependencyAnalyzer->analyze($appData, $ignoreMax);
  261. $appData['canInstall'] = empty($missing);
  262. $appData['missingDependencies'] = $missing;
  263. $appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
  264. $appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
  265. $appData['isCompatible'] = $dependencyAnalyzer->isMarkedCompatible($appData);
  266. return $appData;
  267. }, $apps);
  268. usort($apps, [$this, 'sortApps']);
  269. return new JSONResponse(['apps' => $apps, 'status' => 'success']);
  270. }
  271. /**
  272. * Get all apps for a category from the app store
  273. *
  274. * @param string $requestedCategory
  275. * @return array
  276. * @throws \Exception
  277. */
  278. private function getAppsForCategory($requestedCategory = ''): array {
  279. $versionParser = new VersionParser();
  280. $formattedApps = [];
  281. $apps = $this->appFetcher->get();
  282. foreach ($apps as $app) {
  283. // Skip all apps not in the requested category
  284. if ($requestedCategory !== '') {
  285. $isInCategory = false;
  286. foreach ($app['categories'] as $category) {
  287. if ($category === $requestedCategory) {
  288. $isInCategory = true;
  289. }
  290. }
  291. if (!$isInCategory) {
  292. continue;
  293. }
  294. }
  295. if (!isset($app['releases'][0]['rawPlatformVersionSpec'])) {
  296. continue;
  297. }
  298. $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
  299. $nextCloudVersionDependencies = [];
  300. if ($nextCloudVersion->getMinimumVersion() !== '') {
  301. $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
  302. }
  303. if ($nextCloudVersion->getMaximumVersion() !== '') {
  304. $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
  305. }
  306. $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
  307. $existsLocally = \OC_App::getAppPath($app['id']) !== false;
  308. $phpDependencies = [];
  309. if ($phpVersion->getMinimumVersion() !== '') {
  310. $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
  311. }
  312. if ($phpVersion->getMaximumVersion() !== '') {
  313. $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
  314. }
  315. if (isset($app['releases'][0]['minIntSize'])) {
  316. $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
  317. }
  318. $authors = '';
  319. foreach ($app['authors'] as $key => $author) {
  320. $authors .= $author['name'];
  321. if ($key !== count($app['authors']) - 1) {
  322. $authors .= ', ';
  323. }
  324. }
  325. $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
  326. $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
  327. $groups = null;
  328. if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
  329. $groups = $enabledValue;
  330. }
  331. $currentVersion = '';
  332. if ($this->appManager->isInstalled($app['id'])) {
  333. $currentVersion = $this->appManager->getAppVersion($app['id']);
  334. } else {
  335. $currentLanguage = $app['releases'][0]['version'];
  336. }
  337. $formattedApps[] = [
  338. 'id' => $app['id'],
  339. 'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
  340. 'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
  341. 'summary' => isset($app['translations'][$currentLanguage]['summary']) ? $app['translations'][$currentLanguage]['summary'] : $app['translations']['en']['summary'],
  342. 'license' => $app['releases'][0]['licenses'],
  343. 'author' => $authors,
  344. 'shipped' => false,
  345. 'version' => $currentVersion,
  346. 'default_enable' => '',
  347. 'types' => [],
  348. 'documentation' => [
  349. 'admin' => $app['adminDocs'],
  350. 'user' => $app['userDocs'],
  351. 'developer' => $app['developerDocs']
  352. ],
  353. 'website' => $app['website'],
  354. 'bugs' => $app['issueTracker'],
  355. 'detailpage' => $app['website'],
  356. 'dependencies' => array_merge(
  357. $nextCloudVersionDependencies,
  358. $phpDependencies
  359. ),
  360. 'level' => ($app['isFeatured'] === true) ? 200 : 100,
  361. 'missingMaxOwnCloudVersion' => false,
  362. 'missingMinOwnCloudVersion' => false,
  363. 'canInstall' => true,
  364. 'screenshot' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
  365. 'score' => $app['ratingOverall'],
  366. 'ratingNumOverall' => $app['ratingNumOverall'],
  367. 'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
  368. 'removable' => $existsLocally,
  369. 'active' => $this->appManager->isEnabledForUser($app['id']),
  370. 'needsDownload' => !$existsLocally,
  371. 'groups' => $groups,
  372. 'fromAppStore' => true,
  373. 'appstoreData' => $app,
  374. ];
  375. }
  376. return $formattedApps;
  377. }
  378. /**
  379. * @PasswordConfirmationRequired
  380. *
  381. * @param string $appId
  382. * @param array $groups
  383. * @return JSONResponse
  384. */
  385. public function enableApp(string $appId, array $groups = []): JSONResponse {
  386. return $this->enableApps([$appId], $groups);
  387. }
  388. /**
  389. * Enable one or more apps
  390. *
  391. * apps will be enabled for specific groups only if $groups is defined
  392. *
  393. * @PasswordConfirmationRequired
  394. * @param array $appIds
  395. * @param array $groups
  396. * @return JSONResponse
  397. */
  398. public function enableApps(array $appIds, array $groups = []): JSONResponse {
  399. try {
  400. $updateRequired = false;
  401. foreach ($appIds as $appId) {
  402. $appId = OC_App::cleanAppId($appId);
  403. // Check if app is already downloaded
  404. /** @var Installer $installer */
  405. $installer = \OC::$server->query(Installer::class);
  406. $isDownloaded = $installer->isDownloaded($appId);
  407. if (!$isDownloaded) {
  408. $installer->downloadApp($appId);
  409. }
  410. $installer->installApp($appId);
  411. if (count($groups) > 0) {
  412. $this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
  413. } else {
  414. $this->appManager->enableApp($appId);
  415. }
  416. if (\OC_App::shouldUpgrade($appId)) {
  417. $updateRequired = true;
  418. }
  419. }
  420. return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
  421. } catch (\Exception $e) {
  422. $this->logger->logException($e);
  423. return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  424. }
  425. }
  426. private function getGroupList(array $groups) {
  427. $groupManager = \OC::$server->getGroupManager();
  428. $groupsList = [];
  429. foreach ($groups as $group) {
  430. $groupItem = $groupManager->get($group);
  431. if ($groupItem instanceof \OCP\IGroup) {
  432. $groupsList[] = $groupManager->get($group);
  433. }
  434. }
  435. return $groupsList;
  436. }
  437. /**
  438. * @PasswordConfirmationRequired
  439. *
  440. * @param string $appId
  441. * @return JSONResponse
  442. */
  443. public function disableApp(string $appId): JSONResponse {
  444. return $this->disableApps([$appId]);
  445. }
  446. /**
  447. * @PasswordConfirmationRequired
  448. *
  449. * @param array $appIds
  450. * @return JSONResponse
  451. */
  452. public function disableApps(array $appIds): JSONResponse {
  453. try {
  454. foreach ($appIds as $appId) {
  455. $appId = OC_App::cleanAppId($appId);
  456. $this->appManager->disableApp($appId);
  457. }
  458. return new JSONResponse([]);
  459. } catch (\Exception $e) {
  460. $this->logger->logException($e);
  461. return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  462. }
  463. }
  464. /**
  465. * @PasswordConfirmationRequired
  466. *
  467. * @param string $appId
  468. * @return JSONResponse
  469. */
  470. public function uninstallApp(string $appId): JSONResponse {
  471. $appId = OC_App::cleanAppId($appId);
  472. $result = $this->installer->removeApp($appId);
  473. if ($result !== false) {
  474. $this->appManager->clearAppsCache();
  475. return new JSONResponse(['data' => ['appid' => $appId]]);
  476. }
  477. return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
  478. }
  479. /**
  480. * @param string $appId
  481. * @return JSONResponse
  482. */
  483. public function updateApp(string $appId): JSONResponse {
  484. $appId = OC_App::cleanAppId($appId);
  485. $this->config->setSystemValue('maintenance', true);
  486. try {
  487. $result = $this->installer->updateAppstoreApp($appId);
  488. $this->config->setSystemValue('maintenance', false);
  489. } catch (\Exception $ex) {
  490. $this->config->setSystemValue('maintenance', false);
  491. return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
  492. }
  493. if ($result !== false) {
  494. return new JSONResponse(['data' => ['appid' => $appId]]);
  495. }
  496. return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
  497. }
  498. private function sortApps($a, $b) {
  499. $a = (string)$a['name'];
  500. $b = (string)$b['name'];
  501. if ($a === $b) {
  502. return 0;
  503. }
  504. return ($a < $b) ? -1 : 1;
  505. }
  506. public function force(string $appId): JSONResponse {
  507. $appId = OC_App::cleanAppId($appId);
  508. $this->appManager->ignoreNextcloudRequirementForApp($appId);
  509. return new JSONResponse();
  510. }
  511. }