1
0

OC_App.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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. * search for an app in all app-directories
  233. *
  234. * @param string $appId
  235. * @param bool $ignoreCache ignore cache and rebuild it
  236. * @return false|string
  237. */
  238. public static function findAppInDirectories(string $appId, bool $ignoreCache = false) {
  239. $sanitizedAppId = self::cleanAppId($appId);
  240. if ($sanitizedAppId !== $appId) {
  241. return false;
  242. }
  243. static $app_dir = [];
  244. if (isset($app_dir[$appId]) && !$ignoreCache) {
  245. return $app_dir[$appId];
  246. }
  247. $possibleApps = [];
  248. foreach (OC::$APPSROOTS as $dir) {
  249. if (file_exists($dir['path'] . '/' . $appId)) {
  250. $possibleApps[] = $dir;
  251. }
  252. }
  253. if (empty($possibleApps)) {
  254. return false;
  255. } elseif (count($possibleApps) === 1) {
  256. $dir = array_shift($possibleApps);
  257. $app_dir[$appId] = $dir;
  258. return $dir;
  259. } else {
  260. $versionToLoad = [];
  261. foreach ($possibleApps as $possibleApp) {
  262. $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
  263. if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
  264. $versionToLoad = [
  265. 'dir' => $possibleApp,
  266. 'version' => $version,
  267. ];
  268. }
  269. }
  270. $app_dir[$appId] = $versionToLoad['dir'];
  271. return $versionToLoad['dir'];
  272. //TODO - write test
  273. }
  274. }
  275. /**
  276. * Get the directory for the given app.
  277. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  278. *
  279. * @psalm-taint-specialize
  280. *
  281. * @param string $appId
  282. * @param bool $refreshAppPath should be set to true only during install/upgrade
  283. * @return string|false
  284. * @deprecated 11.0.0 use \OCP\Server::get(IAppManager)->getAppPath()
  285. */
  286. public static function getAppPath(string $appId, bool $refreshAppPath = false) {
  287. if ($appId === null || trim($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 = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
  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 string $type
  353. * @return array
  354. */
  355. public static function getForms(string $type): array {
  356. $forms = [];
  357. switch ($type) {
  358. case 'admin':
  359. $source = self::$adminForms;
  360. break;
  361. case 'personal':
  362. $source = self::$personalForms;
  363. break;
  364. default:
  365. return [];
  366. }
  367. foreach ($source as $form) {
  368. $forms[] = include $form;
  369. }
  370. return $forms;
  371. }
  372. /**
  373. * @param array $entry
  374. * @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
  375. */
  376. public static function registerLogIn(array $entry) {
  377. \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');
  378. self::$altLogin[] = $entry;
  379. }
  380. /**
  381. * @return array
  382. */
  383. public static function getAlternativeLogIns(): array {
  384. /** @var Coordinator $bootstrapCoordinator */
  385. $bootstrapCoordinator = \OCP\Server::get(Coordinator::class);
  386. foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
  387. if (!in_array(IAlternativeLogin::class, class_implements($registration->getService()), true)) {
  388. \OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
  389. 'option' => $registration->getService(),
  390. 'interface' => IAlternativeLogin::class,
  391. 'app' => $registration->getAppId(),
  392. ]);
  393. continue;
  394. }
  395. try {
  396. /** @var IAlternativeLogin $provider */
  397. $provider = \OCP\Server::get($registration->getService());
  398. } catch (ContainerExceptionInterface $e) {
  399. \OC::$server->getLogger()->logException($e, [
  400. 'message' => 'Alternative login option {option} can not be initialised.',
  401. 'option' => $registration->getService(),
  402. 'app' => $registration->getAppId(),
  403. ]);
  404. }
  405. try {
  406. $provider->load();
  407. self::$altLogin[] = [
  408. 'name' => $provider->getLabel(),
  409. 'href' => $provider->getLink(),
  410. 'class' => $provider->getClass(),
  411. ];
  412. } catch (Throwable $e) {
  413. \OC::$server->getLogger()->logException($e, [
  414. 'message' => 'Alternative login option {option} had an error while loading.',
  415. 'option' => $registration->getService(),
  416. 'app' => $registration->getAppId(),
  417. ]);
  418. }
  419. }
  420. return self::$altLogin;
  421. }
  422. /**
  423. * get a list of all apps in the apps folder
  424. *
  425. * @return string[] an array of app names (string IDs)
  426. * @todo: change the name of this method to getInstalledApps, which is more accurate
  427. */
  428. public static function getAllApps(): array {
  429. $apps = [];
  430. foreach (OC::$APPSROOTS as $apps_dir) {
  431. if (!is_readable($apps_dir['path'])) {
  432. \OCP\Server::get(LoggerInterface::class)->warning('unable to read app folder : ' . $apps_dir['path'], ['app' => 'core']);
  433. continue;
  434. }
  435. $dh = opendir($apps_dir['path']);
  436. if (is_resource($dh)) {
  437. while (($file = readdir($dh)) !== false) {
  438. if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
  439. $apps[] = $file;
  440. }
  441. }
  442. }
  443. }
  444. $apps = array_unique($apps);
  445. return $apps;
  446. }
  447. /**
  448. * List all supported apps
  449. *
  450. * @return array
  451. */
  452. public function getSupportedApps(): array {
  453. /** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
  454. $subscriptionRegistry = \OCP\Server::get(\OCP\Support\Subscription\IRegistry::class);
  455. $supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
  456. return $supportedApps;
  457. }
  458. /**
  459. * List all apps, this is used in apps.php
  460. *
  461. * @return array
  462. */
  463. public function listAllApps(): array {
  464. $installedApps = OC_App::getAllApps();
  465. $appManager = \OC::$server->getAppManager();
  466. //we don't want to show configuration for these
  467. $blacklist = $appManager->getAlwaysEnabledApps();
  468. $appList = [];
  469. $langCode = \OC::$server->getL10N('core')->getLanguageCode();
  470. $urlGenerator = \OC::$server->getURLGenerator();
  471. $supportedApps = $this->getSupportedApps();
  472. foreach ($installedApps as $app) {
  473. if (!in_array($app, $blacklist)) {
  474. $info = $appManager->getAppInfo($app, false, $langCode);
  475. if (!is_array($info)) {
  476. \OCP\Server::get(LoggerInterface::class)->error('Could not read app info file for app "' . $app . '"', ['app' => 'core']);
  477. continue;
  478. }
  479. if (!isset($info['name'])) {
  480. \OCP\Server::get(LoggerInterface::class)->error('App id "' . $app . '" has no name in appinfo', ['app' => 'core']);
  481. continue;
  482. }
  483. $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
  484. $info['groups'] = null;
  485. if ($enabled === 'yes') {
  486. $active = true;
  487. } elseif ($enabled === 'no') {
  488. $active = false;
  489. } else {
  490. $active = true;
  491. $info['groups'] = $enabled;
  492. }
  493. $info['active'] = $active;
  494. if ($appManager->isShipped($app)) {
  495. $info['internal'] = true;
  496. $info['level'] = self::officialApp;
  497. $info['removable'] = false;
  498. } else {
  499. $info['internal'] = false;
  500. $info['removable'] = true;
  501. }
  502. if (in_array($app, $supportedApps)) {
  503. $info['level'] = self::supportedApp;
  504. }
  505. $appPath = self::getAppPath($app);
  506. if ($appPath !== false) {
  507. $appIcon = $appPath . '/img/' . $app . '.svg';
  508. if (file_exists($appIcon)) {
  509. $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
  510. $info['previewAsIcon'] = true;
  511. } else {
  512. $appIcon = $appPath . '/img/app.svg';
  513. if (file_exists($appIcon)) {
  514. $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
  515. $info['previewAsIcon'] = true;
  516. }
  517. }
  518. }
  519. // fix documentation
  520. if (isset($info['documentation']) && is_array($info['documentation'])) {
  521. foreach ($info['documentation'] as $key => $url) {
  522. // If it is not an absolute URL we assume it is a key
  523. // i.e. admin-ldap will get converted to go.php?to=admin-ldap
  524. if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
  525. $url = $urlGenerator->linkToDocs($url);
  526. }
  527. $info['documentation'][$key] = $url;
  528. }
  529. }
  530. $info['version'] = $appManager->getAppVersion($app);
  531. $appList[] = $info;
  532. }
  533. }
  534. return $appList;
  535. }
  536. public static function shouldUpgrade(string $app): bool {
  537. $versions = self::getAppVersions();
  538. $currentVersion = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($app);
  539. if ($currentVersion && isset($versions[$app])) {
  540. $installedVersion = $versions[$app];
  541. if (!version_compare($currentVersion, $installedVersion, '=')) {
  542. return true;
  543. }
  544. }
  545. return false;
  546. }
  547. /**
  548. * Adjust the number of version parts of $version1 to match
  549. * the number of version parts of $version2.
  550. *
  551. * @param string $version1 version to adjust
  552. * @param string $version2 version to take the number of parts from
  553. * @return string shortened $version1
  554. */
  555. private static function adjustVersionParts(string $version1, string $version2): string {
  556. $version1 = explode('.', $version1);
  557. $version2 = explode('.', $version2);
  558. // reduce $version1 to match the number of parts in $version2
  559. while (count($version1) > count($version2)) {
  560. array_pop($version1);
  561. }
  562. // if $version1 does not have enough parts, add some
  563. while (count($version1) < count($version2)) {
  564. $version1[] = '0';
  565. }
  566. return implode('.', $version1);
  567. }
  568. /**
  569. * Check whether the current ownCloud version matches the given
  570. * application's version requirements.
  571. *
  572. * The comparison is made based on the number of parts that the
  573. * app info version has. For example for ownCloud 6.0.3 if the
  574. * app info version is expecting version 6.0, the comparison is
  575. * made on the first two parts of the ownCloud version.
  576. * This means that it's possible to specify "requiremin" => 6
  577. * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
  578. *
  579. * @param string $ocVersion ownCloud version to check against
  580. * @param array $appInfo app info (from xml)
  581. *
  582. * @return boolean true if compatible, otherwise false
  583. */
  584. public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
  585. $requireMin = '';
  586. $requireMax = '';
  587. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
  588. $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
  589. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
  590. $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
  591. } elseif (isset($appInfo['requiremin'])) {
  592. $requireMin = $appInfo['requiremin'];
  593. } elseif (isset($appInfo['require'])) {
  594. $requireMin = $appInfo['require'];
  595. }
  596. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
  597. $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
  598. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
  599. $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
  600. } elseif (isset($appInfo['requiremax'])) {
  601. $requireMax = $appInfo['requiremax'];
  602. }
  603. if (!empty($requireMin)
  604. && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
  605. ) {
  606. return false;
  607. }
  608. if (!$ignoreMax && !empty($requireMax)
  609. && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
  610. ) {
  611. return false;
  612. }
  613. return true;
  614. }
  615. /**
  616. * get the installed version of all apps
  617. */
  618. public static function getAppVersions() {
  619. static $versions;
  620. if (!$versions) {
  621. /** @var IAppConfig $appConfig */
  622. $appConfig = \OCP\Server::get(IAppConfig::class);
  623. $versions = $appConfig->searchValues('installed_version');
  624. }
  625. return $versions;
  626. }
  627. /**
  628. * update the database for the app and call the update script
  629. *
  630. * @param string $appId
  631. * @return bool
  632. */
  633. public static function updateApp(string $appId): bool {
  634. // for apps distributed with core, we refresh app path in case the downloaded version
  635. // have been installed in custom apps and not in the default path
  636. $appPath = self::getAppPath($appId, true);
  637. if ($appPath === false) {
  638. return false;
  639. }
  640. if (is_file($appPath . '/appinfo/database.xml')) {
  641. \OC::$server->getLogger()->error('The appinfo/database.xml file is not longer supported. Used in ' . $appId);
  642. return false;
  643. }
  644. \OC::$server->getAppManager()->clearAppsCache();
  645. $l = \OC::$server->getL10N('core');
  646. $appData = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppInfo($appId, false, $l->getLanguageCode());
  647. $ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []);
  648. $ignoreMax = in_array($appId, $ignoreMaxApps, true);
  649. \OC_App::checkAppDependencies(
  650. \OC::$server->getConfig(),
  651. $l,
  652. $appData,
  653. $ignoreMax
  654. );
  655. self::registerAutoloading($appId, $appPath, true);
  656. self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
  657. $ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
  658. $ms->migrate();
  659. self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
  660. self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
  661. // update appversion in app manager
  662. \OC::$server->getAppManager()->clearAppsCache();
  663. \OC::$server->getAppManager()->getAppVersion($appId, false);
  664. self::setupBackgroundJobs($appData['background-jobs']);
  665. //set remote/public handlers
  666. if (array_key_exists('ocsid', $appData)) {
  667. \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
  668. } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
  669. \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
  670. }
  671. foreach ($appData['remote'] as $name => $path) {
  672. \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
  673. }
  674. foreach ($appData['public'] as $name => $path) {
  675. \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
  676. }
  677. self::setAppTypes($appId);
  678. $version = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($appId);
  679. \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
  680. \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new AppUpdateEvent($appId));
  681. \OC::$server->get(IEventDispatcher::class)->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
  682. ManagerEvent::EVENT_APP_UPDATE, $appId
  683. ));
  684. return true;
  685. }
  686. /**
  687. * @param string $appId
  688. * @param string[] $steps
  689. * @throws \OC\NeedsUpdateException
  690. */
  691. public static function executeRepairSteps(string $appId, array $steps) {
  692. if (empty($steps)) {
  693. return;
  694. }
  695. // load the app
  696. self::loadApp($appId);
  697. $dispatcher = Server::get(IEventDispatcher::class);
  698. // load the steps
  699. $r = Server::get(Repair::class);
  700. foreach ($steps as $step) {
  701. try {
  702. $r->addStep($step);
  703. } catch (Exception $ex) {
  704. $dispatcher->dispatchTyped(new RepairErrorEvent($ex->getMessage()));
  705. logger('core')->error('Failed to add app migration step ' . $step, ['exception' => $ex]);
  706. }
  707. }
  708. // run the steps
  709. $r->run();
  710. }
  711. public static function setupBackgroundJobs(array $jobs) {
  712. $queue = \OC::$server->getJobList();
  713. foreach ($jobs as $job) {
  714. $queue->add($job);
  715. }
  716. }
  717. /**
  718. * @param string $appId
  719. * @param string[] $steps
  720. */
  721. private static function setupLiveMigrations(string $appId, array $steps) {
  722. $queue = \OC::$server->getJobList();
  723. foreach ($steps as $step) {
  724. $queue->add('OC\Migration\BackgroundRepair', [
  725. 'app' => $appId,
  726. 'step' => $step]);
  727. }
  728. }
  729. /**
  730. * @param string $appId
  731. * @return \OC\Files\View|false
  732. */
  733. public static function getStorage(string $appId) {
  734. if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
  735. if (\OC::$server->getUserSession()->isLoggedIn()) {
  736. $view = new \OC\Files\View('/' . OC_User::getUser());
  737. if (!$view->file_exists($appId)) {
  738. $view->mkdir($appId);
  739. }
  740. return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
  741. } else {
  742. \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ', user not logged in', ['app' => 'core']);
  743. return false;
  744. }
  745. } else {
  746. \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ' not enabled', ['app' => 'core']);
  747. return false;
  748. }
  749. }
  750. protected static function findBestL10NOption(array $options, string $lang): string {
  751. // only a single option
  752. if (isset($options['@value'])) {
  753. return $options['@value'];
  754. }
  755. $fallback = $similarLangFallback = $englishFallback = false;
  756. $lang = strtolower($lang);
  757. $similarLang = $lang;
  758. if (strpos($similarLang, '_')) {
  759. // For "de_DE" we want to find "de" and the other way around
  760. $similarLang = substr($lang, 0, strpos($lang, '_'));
  761. }
  762. foreach ($options as $option) {
  763. if (is_array($option)) {
  764. if ($fallback === false) {
  765. $fallback = $option['@value'];
  766. }
  767. if (!isset($option['@attributes']['lang'])) {
  768. continue;
  769. }
  770. $attributeLang = strtolower($option['@attributes']['lang']);
  771. if ($attributeLang === $lang) {
  772. return $option['@value'];
  773. }
  774. if ($attributeLang === $similarLang) {
  775. $similarLangFallback = $option['@value'];
  776. } elseif (str_starts_with($attributeLang, $similarLang . '_')) {
  777. if ($similarLangFallback === false) {
  778. $similarLangFallback = $option['@value'];
  779. }
  780. }
  781. } else {
  782. $englishFallback = $option;
  783. }
  784. }
  785. if ($similarLangFallback !== false) {
  786. return $similarLangFallback;
  787. } elseif ($englishFallback !== false) {
  788. return $englishFallback;
  789. }
  790. return (string) $fallback;
  791. }
  792. /**
  793. * parses the app data array and enhanced the 'description' value
  794. *
  795. * @param array $data the app data
  796. * @param string $lang
  797. * @return array improved app data
  798. */
  799. public static function parseAppInfo(array $data, $lang = null): array {
  800. if ($lang && isset($data['name']) && is_array($data['name'])) {
  801. $data['name'] = self::findBestL10NOption($data['name'], $lang);
  802. }
  803. if ($lang && isset($data['summary']) && is_array($data['summary'])) {
  804. $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
  805. }
  806. if ($lang && isset($data['description']) && is_array($data['description'])) {
  807. $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
  808. } elseif (isset($data['description']) && is_string($data['description'])) {
  809. $data['description'] = trim($data['description']);
  810. } else {
  811. $data['description'] = '';
  812. }
  813. return $data;
  814. }
  815. /**
  816. * @param \OCP\IConfig $config
  817. * @param \OCP\IL10N $l
  818. * @param array $info
  819. * @throws \Exception
  820. */
  821. public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
  822. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
  823. $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
  824. if (!empty($missing)) {
  825. $missingMsg = implode(PHP_EOL, $missing);
  826. throw new \Exception(
  827. $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
  828. [$info['name'], $missingMsg]
  829. )
  830. );
  831. }
  832. }
  833. }