OC_App.php 28 KB

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