OC_App.php 27 KB

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