AppSettingsController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  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. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  502. if (!in_array($appId, $ignoreMaxApps, true)) {
  503. $ignoreMaxApps[] = $appId;
  504. $this->config->setSystemValue('app_install_overwrite', $ignoreMaxApps);
  505. }
  506. return new JSONResponse();
  507. }
  508. }