1
0

OC_App.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  6. *
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  10. * @author Borjan Tchakaloff <borjan@tchakaloff.fr>
  11. * @author Brice Maron <brice@bmaron.net>
  12. * @author Christopher Schäpers <kondou@ts.unde.re>
  13. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  14. * @author Daniel Rudolf <github.com@daniel-rudolf.de>
  15. * @author Frank Karlitschek <frank@karlitschek.de>
  16. * @author Georg Ehrke <oc.list@georgehrke.com>
  17. * @author Jakob Sack <mail@jakobsack.de>
  18. * @author Joas Schilling <coding@schilljs.com>
  19. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  20. * @author Julius Haertl <jus@bitgrid.net>
  21. * @author Julius Härtl <jus@bitgrid.net>
  22. * @author Kamil Domanski <kdomanski@kdemail.net>
  23. * @author Lukas Reschke <lukas@statuscode.ch>
  24. * @author Markus Goetz <markus@woboq.com>
  25. * @author Morris Jobke <hey@morrisjobke.de>
  26. * @author RealRancor <Fisch.666@gmx.de>
  27. * @author Robin Appelman <robin@icewind.nl>
  28. * @author Robin McCorkell <robin@mccorkell.me.uk>
  29. * @author Roeland Jago Douma <roeland@famdouma.nl>
  30. * @author Sam Tuke <mail@samtuke.com>
  31. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  32. * @author Thomas Müller <thomas.mueller@tmit.eu>
  33. * @author Thomas Tanghus <thomas@tanghus.net>
  34. * @author Vincent Petry <vincent@nextcloud.com>
  35. *
  36. * @license AGPL-3.0
  37. *
  38. * This code is free software: you can redistribute it and/or modify
  39. * it under the terms of the GNU Affero General Public License, version 3,
  40. * as published by the Free Software Foundation.
  41. *
  42. * This program is distributed in the hope that it will be useful,
  43. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  44. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  45. * GNU Affero General Public License for more details.
  46. *
  47. * You should have received a copy of the GNU Affero General Public License, version 3,
  48. * along with this program. If not, see <http://www.gnu.org/licenses/>
  49. *
  50. */
  51. use OCP\App\Events\AppUpdateEvent;
  52. use OCP\App\IAppManager;
  53. use OCP\App\ManagerEvent;
  54. use OCP\Authentication\IAlternativeLogin;
  55. use OCP\EventDispatcher\IEventDispatcher;
  56. use OC\AppFramework\Bootstrap\Coordinator;
  57. use OC\App\DependencyAnalyzer;
  58. use OC\App\Platform;
  59. use OC\DB\MigrationService;
  60. use OC\Installer;
  61. use OC\Repair;
  62. use OC\Repair\Events\RepairErrorEvent;
  63. use Psr\Container\ContainerExceptionInterface;
  64. use Psr\Log\LoggerInterface;
  65. /**
  66. * This class manages the apps. It allows them to register and integrate in the
  67. * ownCloud ecosystem. Furthermore, this class is responsible for installing,
  68. * upgrading and removing apps.
  69. */
  70. class OC_App {
  71. private static $adminForms = [];
  72. private static $personalForms = [];
  73. private static $altLogin = [];
  74. private static $alreadyRegistered = [];
  75. public const supportedApp = 300;
  76. public const officialApp = 200;
  77. /**
  78. * clean the appId
  79. *
  80. * @psalm-taint-escape file
  81. * @psalm-taint-escape include
  82. * @psalm-taint-escape html
  83. * @psalm-taint-escape has_quotes
  84. *
  85. * @param string $app AppId that needs to be cleaned
  86. * @return string
  87. */
  88. public static function cleanAppId(string $app): string {
  89. return str_replace(['<', '>', '"', "'", '\0', '/', '\\', '..'], '', $app);
  90. }
  91. /**
  92. * Check if an app is loaded
  93. *
  94. * @param string $app
  95. * @return bool
  96. * @deprecated 27.0.0 use IAppManager::isAppLoaded
  97. */
  98. public static function isAppLoaded(string $app): bool {
  99. return \OC::$server->get(IAppManager::class)->isAppLoaded($app);
  100. }
  101. /**
  102. * loads all apps
  103. *
  104. * @param string[] $types
  105. * @return bool
  106. *
  107. * This function walks through the ownCloud directory and loads all apps
  108. * it can find. A directory contains an app if the file /appinfo/info.xml
  109. * exists.
  110. *
  111. * if $types is set to non-empty array, only apps of those types will be loaded
  112. */
  113. public static function loadApps(array $types = []): bool {
  114. if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
  115. // This should be done before calling this method so that appmanager can be used
  116. return false;
  117. }
  118. return \OC::$server->get(IAppManager::class)->loadApps($types);
  119. }
  120. /**
  121. * load a single app
  122. *
  123. * @param string $app
  124. * @throws Exception
  125. * @deprecated 27.0.0 use IAppManager::loadApp
  126. */
  127. public static function loadApp(string $app): void {
  128. \OC::$server->get(IAppManager::class)->loadApp($app);
  129. }
  130. /**
  131. * @internal
  132. * @param string $app
  133. * @param string $path
  134. * @param bool $force
  135. */
  136. public static function registerAutoloading(string $app, string $path, bool $force = false) {
  137. $key = $app . '-' . $path;
  138. if (!$force && isset(self::$alreadyRegistered[$key])) {
  139. return;
  140. }
  141. self::$alreadyRegistered[$key] = true;
  142. // Register on PSR-4 composer autoloader
  143. $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
  144. \OC::$server->registerNamespace($app, $appNamespace);
  145. if (file_exists($path . '/composer/autoload.php')) {
  146. require_once $path . '/composer/autoload.php';
  147. } else {
  148. \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
  149. }
  150. // Register Test namespace only when testing
  151. if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
  152. \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
  153. }
  154. }
  155. /**
  156. * check if an app is of a specific type
  157. *
  158. * @param string $app
  159. * @param array $types
  160. * @return bool
  161. * @deprecated 27.0.0 use IAppManager::isType
  162. */
  163. public static function isType(string $app, array $types): bool {
  164. return \OC::$server->get(IAppManager::class)->isType($app, $types);
  165. }
  166. /**
  167. * read app types from info.xml and cache them in the database
  168. */
  169. public static function setAppTypes(string $app) {
  170. $appManager = \OC::$server->getAppManager();
  171. $appData = $appManager->getAppInfo($app);
  172. if (!is_array($appData)) {
  173. return;
  174. }
  175. if (isset($appData['types'])) {
  176. $appTypes = implode(',', $appData['types']);
  177. } else {
  178. $appTypes = '';
  179. $appData['types'] = [];
  180. }
  181. $config = \OC::$server->getConfig();
  182. $config->setAppValue($app, 'types', $appTypes);
  183. if ($appManager->hasProtectedAppType($appData['types'])) {
  184. $enabled = $config->getAppValue($app, 'enabled', 'yes');
  185. if ($enabled !== 'yes' && $enabled !== 'no') {
  186. $config->setAppValue($app, 'enabled', 'yes');
  187. }
  188. }
  189. }
  190. /**
  191. * Returns apps enabled for the current user.
  192. *
  193. * @param bool $forceRefresh whether to refresh the cache
  194. * @param bool $all whether to return apps for all users, not only the
  195. * currently logged in one
  196. * @return string[]
  197. */
  198. public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
  199. if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
  200. return [];
  201. }
  202. // in incognito mode or when logged out, $user will be false,
  203. // which is also the case during an upgrade
  204. $appManager = \OC::$server->getAppManager();
  205. if ($all) {
  206. $user = null;
  207. } else {
  208. $user = \OC::$server->getUserSession()->getUser();
  209. }
  210. if (is_null($user)) {
  211. $apps = $appManager->getInstalledApps();
  212. } else {
  213. $apps = $appManager->getEnabledAppsForUser($user);
  214. }
  215. $apps = array_filter($apps, function ($app) {
  216. return $app !== 'files';//we add this manually
  217. });
  218. sort($apps);
  219. array_unshift($apps, 'files');
  220. return $apps;
  221. }
  222. /**
  223. * enables an app
  224. *
  225. * @param string $appId
  226. * @param array $groups (optional) when set, only these groups will have access to the app
  227. * @throws \Exception
  228. * @return void
  229. *
  230. * This function set an app as enabled in appconfig.
  231. */
  232. public function enable(string $appId,
  233. array $groups = []) {
  234. // Check if app is already downloaded
  235. /** @var Installer $installer */
  236. $installer = \OCP\Server::get(Installer::class);
  237. $isDownloaded = $installer->isDownloaded($appId);
  238. if (!$isDownloaded) {
  239. $installer->downloadApp($appId);
  240. }
  241. $installer->installApp($appId);
  242. $appManager = \OC::$server->getAppManager();
  243. if ($groups !== []) {
  244. $groupManager = \OC::$server->getGroupManager();
  245. $groupsList = [];
  246. foreach ($groups as $group) {
  247. $groupItem = $groupManager->get($group);
  248. if ($groupItem instanceof \OCP\IGroup) {
  249. $groupsList[] = $groupManager->get($group);
  250. }
  251. }
  252. $appManager->enableAppForGroups($appId, $groupsList);
  253. } else {
  254. $appManager->enableApp($appId);
  255. }
  256. }
  257. /**
  258. * Get the path where to install apps
  259. *
  260. * @return string|false
  261. */
  262. public static function getInstallPath() {
  263. foreach (OC::$APPSROOTS as $dir) {
  264. if (isset($dir['writable']) && $dir['writable'] === true) {
  265. return $dir['path'];
  266. }
  267. }
  268. \OCP\Server::get(LoggerInterface::class)->error('No application directories are marked as writable.', ['app' => 'core']);
  269. return null;
  270. }
  271. /**
  272. * search for an app in all app-directories
  273. *
  274. * @param string $appId
  275. * @param bool $ignoreCache ignore cache and rebuild it
  276. * @return false|string
  277. */
  278. public static function findAppInDirectories(string $appId, bool $ignoreCache = false) {
  279. $sanitizedAppId = self::cleanAppId($appId);
  280. if ($sanitizedAppId !== $appId) {
  281. return false;
  282. }
  283. static $app_dir = [];
  284. if (isset($app_dir[$appId]) && !$ignoreCache) {
  285. return $app_dir[$appId];
  286. }
  287. $possibleApps = [];
  288. foreach (OC::$APPSROOTS as $dir) {
  289. if (file_exists($dir['path'] . '/' . $appId)) {
  290. $possibleApps[] = $dir;
  291. }
  292. }
  293. if (empty($possibleApps)) {
  294. return false;
  295. } elseif (count($possibleApps) === 1) {
  296. $dir = array_shift($possibleApps);
  297. $app_dir[$appId] = $dir;
  298. return $dir;
  299. } else {
  300. $versionToLoad = [];
  301. foreach ($possibleApps as $possibleApp) {
  302. $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
  303. if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
  304. $versionToLoad = [
  305. 'dir' => $possibleApp,
  306. 'version' => $version,
  307. ];
  308. }
  309. }
  310. $app_dir[$appId] = $versionToLoad['dir'];
  311. return $versionToLoad['dir'];
  312. //TODO - write test
  313. }
  314. }
  315. /**
  316. * Get the directory for the given app.
  317. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  318. *
  319. * @psalm-taint-specialize
  320. *
  321. * @param string $appId
  322. * @param bool $refreshAppPath should be set to true only during install/upgrade
  323. * @return string|false
  324. * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
  325. */
  326. public static function getAppPath(string $appId, bool $refreshAppPath = false) {
  327. if ($appId === null || trim($appId) === '') {
  328. return false;
  329. }
  330. if (($dir = self::findAppInDirectories($appId, $refreshAppPath)) != false) {
  331. return $dir['path'] . '/' . $appId;
  332. }
  333. return false;
  334. }
  335. /**
  336. * Get the path for the given app on the access
  337. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  338. *
  339. * @param string $appId
  340. * @return string|false
  341. * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
  342. */
  343. public static function getAppWebPath(string $appId) {
  344. if (($dir = self::findAppInDirectories($appId)) != false) {
  345. return OC::$WEBROOT . $dir['url'] . '/' . $appId;
  346. }
  347. return false;
  348. }
  349. /**
  350. * get app's version based on it's path
  351. *
  352. * @param string $path
  353. * @return string
  354. */
  355. public static function getAppVersionByPath(string $path): string {
  356. $infoFile = $path . '/appinfo/info.xml';
  357. $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
  358. return $appData['version'] ?? '';
  359. }
  360. /**
  361. * get the id of loaded app
  362. *
  363. * @return string
  364. */
  365. public static function getCurrentApp(): string {
  366. if (\OC::$CLI) {
  367. return '';
  368. }
  369. $request = \OC::$server->getRequest();
  370. $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
  371. $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
  372. if (empty($topFolder)) {
  373. try {
  374. $path_info = $request->getPathInfo();
  375. } catch (Exception $e) {
  376. // Can happen from unit tests because the script name is `./vendor/bin/phpunit` or something a like then.
  377. \OC::$server->get(LoggerInterface::class)->error('Failed to detect current app from script path', ['exception' => $e]);
  378. return '';
  379. }
  380. if ($path_info) {
  381. $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
  382. }
  383. }
  384. if ($topFolder == 'apps') {
  385. $length = strlen($topFolder);
  386. return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
  387. } else {
  388. return $topFolder;
  389. }
  390. }
  391. /**
  392. * @param string $type
  393. * @return array
  394. */
  395. public static function getForms(string $type): array {
  396. $forms = [];
  397. switch ($type) {
  398. case 'admin':
  399. $source = self::$adminForms;
  400. break;
  401. case 'personal':
  402. $source = self::$personalForms;
  403. break;
  404. default:
  405. return [];
  406. }
  407. foreach ($source as $form) {
  408. $forms[] = include $form;
  409. }
  410. return $forms;
  411. }
  412. /**
  413. * @param array $entry
  414. * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface
  415. */
  416. public static function registerLogIn(array $entry) {
  417. \OC::$server->getLogger()->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface');
  418. self::$altLogin[] = $entry;
  419. }
  420. /**
  421. * @return array
  422. */
  423. public static function getAlternativeLogIns(): array {
  424. /** @var Coordinator $bootstrapCoordinator */
  425. $bootstrapCoordinator = \OCP\Server::get(Coordinator::class);
  426. foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
  427. if (!in_array(IAlternativeLogin::class, class_implements($registration->getService()), true)) {
  428. \OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
  429. 'option' => $registration->getService(),
  430. 'interface' => IAlternativeLogin::class,
  431. 'app' => $registration->getAppId(),
  432. ]);
  433. continue;
  434. }
  435. try {
  436. /** @var IAlternativeLogin $provider */
  437. $provider = \OCP\Server::get($registration->getService());
  438. } catch (ContainerExceptionInterface $e) {
  439. \OC::$server->getLogger()->logException($e, [
  440. 'message' => 'Alternative login option {option} can not be initialised.',
  441. 'option' => $registration->getService(),
  442. 'app' => $registration->getAppId(),
  443. ]);
  444. }
  445. try {
  446. $provider->load();
  447. self::$altLogin[] = [
  448. 'name' => $provider->getLabel(),
  449. 'href' => $provider->getLink(),
  450. 'class' => $provider->getClass(),
  451. ];
  452. } catch (Throwable $e) {
  453. \OC::$server->getLogger()->logException($e, [
  454. 'message' => 'Alternative login option {option} had an error while loading.',
  455. 'option' => $registration->getService(),
  456. 'app' => $registration->getAppId(),
  457. ]);
  458. }
  459. }
  460. return self::$altLogin;
  461. }
  462. /**
  463. * get a list of all apps in the apps folder
  464. *
  465. * @return string[] an array of app names (string IDs)
  466. * @todo: change the name of this method to getInstalledApps, which is more accurate
  467. */
  468. public static function getAllApps(): array {
  469. $apps = [];
  470. foreach (OC::$APPSROOTS as $apps_dir) {
  471. if (!is_readable($apps_dir['path'])) {
  472. \OCP\Server::get(LoggerInterface::class)->warning('unable to read app folder : ' . $apps_dir['path'], ['app' => 'core']);
  473. continue;
  474. }
  475. $dh = opendir($apps_dir['path']);
  476. if (is_resource($dh)) {
  477. while (($file = readdir($dh)) !== false) {
  478. if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
  479. $apps[] = $file;
  480. }
  481. }
  482. }
  483. }
  484. $apps = array_unique($apps);
  485. return $apps;
  486. }
  487. /**
  488. * List all supported apps
  489. *
  490. * @return array
  491. */
  492. public function getSupportedApps(): array {
  493. /** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
  494. $subscriptionRegistry = \OCP\Server::get(\OCP\Support\Subscription\IRegistry::class);
  495. $supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
  496. return $supportedApps;
  497. }
  498. /**
  499. * List all apps, this is used in apps.php
  500. *
  501. * @return array
  502. */
  503. public function listAllApps(): array {
  504. $installedApps = OC_App::getAllApps();
  505. $appManager = \OC::$server->getAppManager();
  506. //we don't want to show configuration for these
  507. $blacklist = $appManager->getAlwaysEnabledApps();
  508. $appList = [];
  509. $langCode = \OC::$server->getL10N('core')->getLanguageCode();
  510. $urlGenerator = \OC::$server->getURLGenerator();
  511. $supportedApps = $this->getSupportedApps();
  512. foreach ($installedApps as $app) {
  513. if (array_search($app, $blacklist) === false) {
  514. $info = $appManager->getAppInfo($app, false, $langCode);
  515. if (!is_array($info)) {
  516. \OCP\Server::get(LoggerInterface::class)->error('Could not read app info file for app "' . $app . '"', ['app' => 'core']);
  517. continue;
  518. }
  519. if (!isset($info['name'])) {
  520. \OCP\Server::get(LoggerInterface::class)->error('App id "' . $app . '" has no name in appinfo', ['app' => 'core']);
  521. continue;
  522. }
  523. $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
  524. $info['groups'] = null;
  525. if ($enabled === 'yes') {
  526. $active = true;
  527. } elseif ($enabled === 'no') {
  528. $active = false;
  529. } else {
  530. $active = true;
  531. $info['groups'] = $enabled;
  532. }
  533. $info['active'] = $active;
  534. if ($appManager->isShipped($app)) {
  535. $info['internal'] = true;
  536. $info['level'] = self::officialApp;
  537. $info['removable'] = false;
  538. } else {
  539. $info['internal'] = false;
  540. $info['removable'] = true;
  541. }
  542. if (in_array($app, $supportedApps)) {
  543. $info['level'] = self::supportedApp;
  544. }
  545. $appPath = self::getAppPath($app);
  546. if ($appPath !== false) {
  547. $appIcon = $appPath . '/img/' . $app . '.svg';
  548. if (file_exists($appIcon)) {
  549. $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
  550. $info['previewAsIcon'] = true;
  551. } else {
  552. $appIcon = $appPath . '/img/app.svg';
  553. if (file_exists($appIcon)) {
  554. $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
  555. $info['previewAsIcon'] = true;
  556. }
  557. }
  558. }
  559. // fix documentation
  560. if (isset($info['documentation']) && is_array($info['documentation'])) {
  561. foreach ($info['documentation'] as $key => $url) {
  562. // If it is not an absolute URL we assume it is a key
  563. // i.e. admin-ldap will get converted to go.php?to=admin-ldap
  564. if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
  565. $url = $urlGenerator->linkToDocs($url);
  566. }
  567. $info['documentation'][$key] = $url;
  568. }
  569. }
  570. $info['version'] = $appManager->getAppVersion($app);
  571. $appList[] = $info;
  572. }
  573. }
  574. return $appList;
  575. }
  576. public static function shouldUpgrade(string $app): bool {
  577. $versions = self::getAppVersions();
  578. $currentVersion = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($app);
  579. if ($currentVersion && isset($versions[$app])) {
  580. $installedVersion = $versions[$app];
  581. if (!version_compare($currentVersion, $installedVersion, '=')) {
  582. return true;
  583. }
  584. }
  585. return false;
  586. }
  587. /**
  588. * Adjust the number of version parts of $version1 to match
  589. * the number of version parts of $version2.
  590. *
  591. * @param string $version1 version to adjust
  592. * @param string $version2 version to take the number of parts from
  593. * @return string shortened $version1
  594. */
  595. private static function adjustVersionParts(string $version1, string $version2): string {
  596. $version1 = explode('.', $version1);
  597. $version2 = explode('.', $version2);
  598. // reduce $version1 to match the number of parts in $version2
  599. while (count($version1) > count($version2)) {
  600. array_pop($version1);
  601. }
  602. // if $version1 does not have enough parts, add some
  603. while (count($version1) < count($version2)) {
  604. $version1[] = '0';
  605. }
  606. return implode('.', $version1);
  607. }
  608. /**
  609. * Check whether the current ownCloud version matches the given
  610. * application's version requirements.
  611. *
  612. * The comparison is made based on the number of parts that the
  613. * app info version has. For example for ownCloud 6.0.3 if the
  614. * app info version is expecting version 6.0, the comparison is
  615. * made on the first two parts of the ownCloud version.
  616. * This means that it's possible to specify "requiremin" => 6
  617. * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
  618. *
  619. * @param string $ocVersion ownCloud version to check against
  620. * @param array $appInfo app info (from xml)
  621. *
  622. * @return boolean true if compatible, otherwise false
  623. */
  624. public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
  625. $requireMin = '';
  626. $requireMax = '';
  627. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
  628. $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
  629. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
  630. $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
  631. } elseif (isset($appInfo['requiremin'])) {
  632. $requireMin = $appInfo['requiremin'];
  633. } elseif (isset($appInfo['require'])) {
  634. $requireMin = $appInfo['require'];
  635. }
  636. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
  637. $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
  638. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
  639. $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
  640. } elseif (isset($appInfo['requiremax'])) {
  641. $requireMax = $appInfo['requiremax'];
  642. }
  643. if (!empty($requireMin)
  644. && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
  645. ) {
  646. return false;
  647. }
  648. if (!$ignoreMax && !empty($requireMax)
  649. && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
  650. ) {
  651. return false;
  652. }
  653. return true;
  654. }
  655. /**
  656. * get the installed version of all apps
  657. */
  658. public static function getAppVersions() {
  659. static $versions;
  660. if (!$versions) {
  661. $appConfig = \OC::$server->getAppConfig();
  662. $versions = $appConfig->getValues(false, 'installed_version');
  663. }
  664. return $versions;
  665. }
  666. /**
  667. * update the database for the app and call the update script
  668. *
  669. * @param string $appId
  670. * @return bool
  671. */
  672. public static function updateApp(string $appId): bool {
  673. // for apps distributed with core, we refresh app path in case the downloaded version
  674. // have been installed in custom apps and not in the default path
  675. $appPath = self::getAppPath($appId, true);
  676. if ($appPath === false) {
  677. return false;
  678. }
  679. if (is_file($appPath . '/appinfo/database.xml')) {
  680. \OC::$server->getLogger()->error('The appinfo/database.xml file is not longer supported. Used in ' . $appId);
  681. return false;
  682. }
  683. \OC::$server->getAppManager()->clearAppsCache();
  684. $l = \OC::$server->getL10N('core');
  685. $appData = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppInfo($appId, false, $l->getLanguageCode());
  686. $ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []);
  687. $ignoreMax = in_array($appId, $ignoreMaxApps, true);
  688. \OC_App::checkAppDependencies(
  689. \OC::$server->getConfig(),
  690. $l,
  691. $appData,
  692. $ignoreMax
  693. );
  694. self::registerAutoloading($appId, $appPath, true);
  695. self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
  696. $ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
  697. $ms->migrate();
  698. self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
  699. self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
  700. // update appversion in app manager
  701. \OC::$server->getAppManager()->clearAppsCache();
  702. \OC::$server->getAppManager()->getAppVersion($appId, false);
  703. self::setupBackgroundJobs($appData['background-jobs']);
  704. //set remote/public handlers
  705. if (array_key_exists('ocsid', $appData)) {
  706. \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
  707. } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
  708. \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
  709. }
  710. foreach ($appData['remote'] as $name => $path) {
  711. \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
  712. }
  713. foreach ($appData['public'] as $name => $path) {
  714. \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
  715. }
  716. self::setAppTypes($appId);
  717. $version = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($appId);
  718. \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
  719. \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new AppUpdateEvent($appId));
  720. \OC::$server->get(IEventDispatcher::class)->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
  721. ManagerEvent::EVENT_APP_UPDATE, $appId
  722. ));
  723. return true;
  724. }
  725. /**
  726. * @param string $appId
  727. * @param string[] $steps
  728. * @throws \OC\NeedsUpdateException
  729. */
  730. public static function executeRepairSteps(string $appId, array $steps) {
  731. if (empty($steps)) {
  732. return;
  733. }
  734. // load the app
  735. self::loadApp($appId);
  736. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  737. // load the steps
  738. $r = new Repair([], $dispatcher, \OC::$server->get(LoggerInterface::class));
  739. foreach ($steps as $step) {
  740. try {
  741. $r->addStep($step);
  742. } catch (Exception $ex) {
  743. $dispatcher->dispatchTyped(new RepairErrorEvent($ex->getMessage()));
  744. \OC::$server->getLogger()->logException($ex);
  745. }
  746. }
  747. // run the steps
  748. $r->run();
  749. }
  750. public static function setupBackgroundJobs(array $jobs) {
  751. $queue = \OC::$server->getJobList();
  752. foreach ($jobs as $job) {
  753. $queue->add($job);
  754. }
  755. }
  756. /**
  757. * @param string $appId
  758. * @param string[] $steps
  759. */
  760. private static function setupLiveMigrations(string $appId, array $steps) {
  761. $queue = \OC::$server->getJobList();
  762. foreach ($steps as $step) {
  763. $queue->add('OC\Migration\BackgroundRepair', [
  764. 'app' => $appId,
  765. 'step' => $step]);
  766. }
  767. }
  768. /**
  769. * @param string $appId
  770. * @return \OC\Files\View|false
  771. */
  772. public static function getStorage(string $appId) {
  773. if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
  774. if (\OC::$server->getUserSession()->isLoggedIn()) {
  775. $view = new \OC\Files\View('/' . OC_User::getUser());
  776. if (!$view->file_exists($appId)) {
  777. $view->mkdir($appId);
  778. }
  779. return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
  780. } else {
  781. \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ', user not logged in', ['app' => 'core']);
  782. return false;
  783. }
  784. } else {
  785. \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ' not enabled', ['app' => 'core']);
  786. return false;
  787. }
  788. }
  789. protected static function findBestL10NOption(array $options, string $lang): string {
  790. // only a single option
  791. if (isset($options['@value'])) {
  792. return $options['@value'];
  793. }
  794. $fallback = $similarLangFallback = $englishFallback = false;
  795. $lang = strtolower($lang);
  796. $similarLang = $lang;
  797. if (strpos($similarLang, '_')) {
  798. // For "de_DE" we want to find "de" and the other way around
  799. $similarLang = substr($lang, 0, strpos($lang, '_'));
  800. }
  801. foreach ($options as $option) {
  802. if (is_array($option)) {
  803. if ($fallback === false) {
  804. $fallback = $option['@value'];
  805. }
  806. if (!isset($option['@attributes']['lang'])) {
  807. continue;
  808. }
  809. $attributeLang = strtolower($option['@attributes']['lang']);
  810. if ($attributeLang === $lang) {
  811. return $option['@value'];
  812. }
  813. if ($attributeLang === $similarLang) {
  814. $similarLangFallback = $option['@value'];
  815. } elseif (str_starts_with($attributeLang, $similarLang . '_')) {
  816. if ($similarLangFallback === false) {
  817. $similarLangFallback = $option['@value'];
  818. }
  819. }
  820. } else {
  821. $englishFallback = $option;
  822. }
  823. }
  824. if ($similarLangFallback !== false) {
  825. return $similarLangFallback;
  826. } elseif ($englishFallback !== false) {
  827. return $englishFallback;
  828. }
  829. return (string) $fallback;
  830. }
  831. /**
  832. * parses the app data array and enhanced the 'description' value
  833. *
  834. * @param array $data the app data
  835. * @param string $lang
  836. * @return array improved app data
  837. */
  838. public static function parseAppInfo(array $data, $lang = null): array {
  839. if ($lang && isset($data['name']) && is_array($data['name'])) {
  840. $data['name'] = self::findBestL10NOption($data['name'], $lang);
  841. }
  842. if ($lang && isset($data['summary']) && is_array($data['summary'])) {
  843. $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
  844. }
  845. if ($lang && isset($data['description']) && is_array($data['description'])) {
  846. $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
  847. } elseif (isset($data['description']) && is_string($data['description'])) {
  848. $data['description'] = trim($data['description']);
  849. } else {
  850. $data['description'] = '';
  851. }
  852. return $data;
  853. }
  854. /**
  855. * @param \OCP\IConfig $config
  856. * @param \OCP\IL10N $l
  857. * @param array $info
  858. * @throws \Exception
  859. */
  860. public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
  861. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
  862. $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
  863. if (!empty($missing)) {
  864. $missingMsg = implode(PHP_EOL, $missing);
  865. throw new \Exception(
  866. $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
  867. [$info['name'], $missingMsg]
  868. )
  869. );
  870. }
  871. }
  872. }