1
0

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