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

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