AppSettingsController.php 17 KB

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