OC_App.php 27 KB

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