AppSettingsController.php 17 KB

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