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

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