OC_App.php 28 KB

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