You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppSettingsController.php 17KB

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