OC_App.php 29 KB

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