OC_App.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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 OC\App\DependencyAnalyzer;
  52. use OC\App\Platform;
  53. use OC\AppFramework\Bootstrap\Coordinator;
  54. use OC\DB\MigrationService;
  55. use OC\Installer;
  56. use OC\Repair;
  57. use OC\Repair\Events\RepairErrorEvent;
  58. use OCP\App\Events\AppUpdateEvent;
  59. use OCP\App\IAppManager;
  60. use OCP\App\ManagerEvent;
  61. use OCP\Authentication\IAlternativeLogin;
  62. use OCP\EventDispatcher\IEventDispatcher;
  63. use OCP\IAppConfig;
  64. use Psr\Container\ContainerExceptionInterface;
  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. * @deprecated 29.0.0 use IAppManager::loadApps instead
  115. */
  116. public static function loadApps(array $types = []): bool {
  117. if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
  118. // This should be done before calling this method so that appmanager can be used
  119. return false;
  120. }
  121. return \OC::$server->get(IAppManager::class)->loadApps($types);
  122. }
  123. /**
  124. * load a single app
  125. *
  126. * @param string $app
  127. * @throws Exception
  128. * @deprecated 27.0.0 use IAppManager::loadApp
  129. */
  130. public static function loadApp(string $app): void {
  131. \OC::$server->get(IAppManager::class)->loadApp($app);
  132. }
  133. /**
  134. * @internal
  135. * @param string $app
  136. * @param string $path
  137. * @param bool $force
  138. */
  139. public static function registerAutoloading(string $app, string $path, bool $force = false) {
  140. $key = $app . '-' . $path;
  141. if (!$force && isset(self::$alreadyRegistered[$key])) {
  142. return;
  143. }
  144. self::$alreadyRegistered[$key] = true;
  145. // Register on PSR-4 composer autoloader
  146. $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
  147. \OC::$server->registerNamespace($app, $appNamespace);
  148. if (file_exists($path . '/composer/autoload.php')) {
  149. require_once $path . '/composer/autoload.php';
  150. } else {
  151. \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
  152. }
  153. // Register Test namespace only when testing
  154. if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
  155. \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
  156. }
  157. }
  158. /**
  159. * check if an app is of a specific type
  160. *
  161. * @param string $app
  162. * @param array $types
  163. * @return bool
  164. * @deprecated 27.0.0 use IAppManager::isType
  165. */
  166. public static function isType(string $app, array $types): bool {
  167. return \OC::$server->get(IAppManager::class)->isType($app, $types);
  168. }
  169. /**
  170. * read app types from info.xml and cache them in the database
  171. */
  172. public static function setAppTypes(string $app) {
  173. $appManager = \OC::$server->getAppManager();
  174. $appData = $appManager->getAppInfo($app);
  175. if (!is_array($appData)) {
  176. return;
  177. }
  178. if (isset($appData['types'])) {
  179. $appTypes = implode(',', $appData['types']);
  180. } else {
  181. $appTypes = '';
  182. $appData['types'] = [];
  183. }
  184. $config = \OC::$server->getConfig();
  185. $config->setAppValue($app, 'types', $appTypes);
  186. if ($appManager->hasProtectedAppType($appData['types'])) {
  187. $enabled = $config->getAppValue($app, 'enabled', 'yes');
  188. if ($enabled !== 'yes' && $enabled !== 'no') {
  189. $config->setAppValue($app, 'enabled', 'yes');
  190. }
  191. }
  192. }
  193. /**
  194. * Returns apps enabled for the current user.
  195. *
  196. * @param bool $forceRefresh whether to refresh the cache
  197. * @param bool $all whether to return apps for all users, not only the
  198. * currently logged in one
  199. * @return string[]
  200. */
  201. public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
  202. if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
  203. return [];
  204. }
  205. // in incognito mode or when logged out, $user will be false,
  206. // which is also the case during an upgrade
  207. $appManager = \OC::$server->getAppManager();
  208. if ($all) {
  209. $user = null;
  210. } else {
  211. $user = \OC::$server->getUserSession()->getUser();
  212. }
  213. if (is_null($user)) {
  214. $apps = $appManager->getInstalledApps();
  215. } else {
  216. $apps = $appManager->getEnabledAppsForUser($user);
  217. }
  218. $apps = array_filter($apps, function ($app) {
  219. return $app !== 'files';//we add this manually
  220. });
  221. sort($apps);
  222. array_unshift($apps, 'files');
  223. return $apps;
  224. }
  225. /**
  226. * enables an app
  227. *
  228. * @param string $appId
  229. * @param array $groups (optional) when set, only these groups will have access to the app
  230. * @throws \Exception
  231. * @return void
  232. *
  233. * This function set an app as enabled in appconfig.
  234. */
  235. public function enable(string $appId,
  236. array $groups = []) {
  237. // Check if app is already downloaded
  238. /** @var Installer $installer */
  239. $installer = \OCP\Server::get(Installer::class);
  240. $isDownloaded = $installer->isDownloaded($appId);
  241. if (!$isDownloaded) {
  242. $installer->downloadApp($appId);
  243. }
  244. $installer->installApp($appId);
  245. $appManager = \OC::$server->getAppManager();
  246. if ($groups !== []) {
  247. $groupManager = \OC::$server->getGroupManager();
  248. $groupsList = [];
  249. foreach ($groups as $group) {
  250. $groupItem = $groupManager->get($group);
  251. if ($groupItem instanceof \OCP\IGroup) {
  252. $groupsList[] = $groupManager->get($group);
  253. }
  254. }
  255. $appManager->enableAppForGroups($appId, $groupsList);
  256. } else {
  257. $appManager->enableApp($appId);
  258. }
  259. }
  260. /**
  261. * Get the path where to install apps
  262. */
  263. public static function getInstallPath(): string|null {
  264. foreach (OC::$APPSROOTS as $dir) {
  265. if (isset($dir['writable']) && $dir['writable'] === true) {
  266. return $dir['path'];
  267. }
  268. }
  269. \OCP\Server::get(LoggerInterface::class)->error('No application directories are marked as writable.', ['app' => 'core']);
  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 \OCP\Server::get(IAppManager)->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 $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 = \OCP\Server::get(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 = \OCP\Server::get($registration->getService());
  439. } catch (ContainerExceptionInterface $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\Server::get(LoggerInterface::class)->warning('unable to read app folder : ' . $apps_dir['path'], ['app' => 'core']);
  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 = \OCP\Server::get(\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 (!in_array($app, $blacklist)) {
  515. $info = $appManager->getAppInfo($app, false, $langCode);
  516. if (!is_array($info)) {
  517. \OCP\Server::get(LoggerInterface::class)->error('Could not read app info file for app "' . $app . '"', ['app' => 'core']);
  518. continue;
  519. }
  520. if (!isset($info['name'])) {
  521. \OCP\Server::get(LoggerInterface::class)->error('App id "' . $app . '" has no name in appinfo', ['app' => 'core']);
  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. /** @var IAppConfig $appConfig */
  663. $appConfig = \OCP\Server::get(IAppConfig::class);
  664. $versions = $appConfig->searchValues('installed_version');
  665. }
  666. return $versions;
  667. }
  668. /**
  669. * update the database for the app and call the update script
  670. *
  671. * @param string $appId
  672. * @return bool
  673. */
  674. public static function updateApp(string $appId): bool {
  675. // for apps distributed with core, we refresh app path in case the downloaded version
  676. // have been installed in custom apps and not in the default path
  677. $appPath = self::getAppPath($appId, true);
  678. if ($appPath === false) {
  679. return false;
  680. }
  681. if (is_file($appPath . '/appinfo/database.xml')) {
  682. \OC::$server->getLogger()->error('The appinfo/database.xml file is not longer supported. Used in ' . $appId);
  683. return false;
  684. }
  685. \OC::$server->getAppManager()->clearAppsCache();
  686. $l = \OC::$server->getL10N('core');
  687. $appData = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppInfo($appId, false, $l->getLanguageCode());
  688. $ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []);
  689. $ignoreMax = in_array($appId, $ignoreMaxApps, true);
  690. \OC_App::checkAppDependencies(
  691. \OC::$server->getConfig(),
  692. $l,
  693. $appData,
  694. $ignoreMax
  695. );
  696. self::registerAutoloading($appId, $appPath, true);
  697. self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
  698. $ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
  699. $ms->migrate();
  700. self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
  701. self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
  702. // update appversion in app manager
  703. \OC::$server->getAppManager()->clearAppsCache();
  704. \OC::$server->getAppManager()->getAppVersion($appId, false);
  705. self::setupBackgroundJobs($appData['background-jobs']);
  706. //set remote/public handlers
  707. if (array_key_exists('ocsid', $appData)) {
  708. \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
  709. } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
  710. \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
  711. }
  712. foreach ($appData['remote'] as $name => $path) {
  713. \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
  714. }
  715. foreach ($appData['public'] as $name => $path) {
  716. \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
  717. }
  718. self::setAppTypes($appId);
  719. $version = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($appId);
  720. \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
  721. \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new AppUpdateEvent($appId));
  722. \OC::$server->get(IEventDispatcher::class)->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
  723. ManagerEvent::EVENT_APP_UPDATE, $appId
  724. ));
  725. return true;
  726. }
  727. /**
  728. * @param string $appId
  729. * @param string[] $steps
  730. * @throws \OC\NeedsUpdateException
  731. */
  732. public static function executeRepairSteps(string $appId, array $steps) {
  733. if (empty($steps)) {
  734. return;
  735. }
  736. // load the app
  737. self::loadApp($appId);
  738. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  739. // load the steps
  740. $r = \OCP\Server::get(Repair::class);
  741. foreach ($steps as $step) {
  742. try {
  743. $r->addStep($step);
  744. } catch (Exception $ex) {
  745. $dispatcher->dispatchTyped(new RepairErrorEvent($ex->getMessage()));
  746. \OC::$server->getLogger()->logException($ex);
  747. }
  748. }
  749. // run the steps
  750. $r->run();
  751. }
  752. public static function setupBackgroundJobs(array $jobs) {
  753. $queue = \OC::$server->getJobList();
  754. foreach ($jobs as $job) {
  755. $queue->add($job);
  756. }
  757. }
  758. /**
  759. * @param string $appId
  760. * @param string[] $steps
  761. */
  762. private static function setupLiveMigrations(string $appId, array $steps) {
  763. $queue = \OC::$server->getJobList();
  764. foreach ($steps as $step) {
  765. $queue->add('OC\Migration\BackgroundRepair', [
  766. 'app' => $appId,
  767. 'step' => $step]);
  768. }
  769. }
  770. /**
  771. * @param string $appId
  772. * @return \OC\Files\View|false
  773. */
  774. public static function getStorage(string $appId) {
  775. if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
  776. if (\OC::$server->getUserSession()->isLoggedIn()) {
  777. $view = new \OC\Files\View('/' . OC_User::getUser());
  778. if (!$view->file_exists($appId)) {
  779. $view->mkdir($appId);
  780. }
  781. return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
  782. } else {
  783. \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ', user not logged in', ['app' => 'core']);
  784. return false;
  785. }
  786. } else {
  787. \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ' not enabled', ['app' => 'core']);
  788. return false;
  789. }
  790. }
  791. protected static function findBestL10NOption(array $options, string $lang): string {
  792. // only a single option
  793. if (isset($options['@value'])) {
  794. return $options['@value'];
  795. }
  796. $fallback = $similarLangFallback = $englishFallback = false;
  797. $lang = strtolower($lang);
  798. $similarLang = $lang;
  799. if (strpos($similarLang, '_')) {
  800. // For "de_DE" we want to find "de" and the other way around
  801. $similarLang = substr($lang, 0, strpos($lang, '_'));
  802. }
  803. foreach ($options as $option) {
  804. if (is_array($option)) {
  805. if ($fallback === false) {
  806. $fallback = $option['@value'];
  807. }
  808. if (!isset($option['@attributes']['lang'])) {
  809. continue;
  810. }
  811. $attributeLang = strtolower($option['@attributes']['lang']);
  812. if ($attributeLang === $lang) {
  813. return $option['@value'];
  814. }
  815. if ($attributeLang === $similarLang) {
  816. $similarLangFallback = $option['@value'];
  817. } elseif (str_starts_with($attributeLang, $similarLang . '_')) {
  818. if ($similarLangFallback === false) {
  819. $similarLangFallback = $option['@value'];
  820. }
  821. }
  822. } else {
  823. $englishFallback = $option;
  824. }
  825. }
  826. if ($similarLangFallback !== false) {
  827. return $similarLangFallback;
  828. } elseif ($englishFallback !== false) {
  829. return $englishFallback;
  830. }
  831. return (string) $fallback;
  832. }
  833. /**
  834. * parses the app data array and enhanced the 'description' value
  835. *
  836. * @param array $data the app data
  837. * @param string $lang
  838. * @return array improved app data
  839. */
  840. public static function parseAppInfo(array $data, $lang = null): array {
  841. if ($lang && isset($data['name']) && is_array($data['name'])) {
  842. $data['name'] = self::findBestL10NOption($data['name'], $lang);
  843. }
  844. if ($lang && isset($data['summary']) && is_array($data['summary'])) {
  845. $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
  846. }
  847. if ($lang && isset($data['description']) && is_array($data['description'])) {
  848. $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
  849. } elseif (isset($data['description']) && is_string($data['description'])) {
  850. $data['description'] = trim($data['description']);
  851. } else {
  852. $data['description'] = '';
  853. }
  854. return $data;
  855. }
  856. /**
  857. * @param \OCP\IConfig $config
  858. * @param \OCP\IL10N $l
  859. * @param array $info
  860. * @throws \Exception
  861. */
  862. public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
  863. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
  864. $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
  865. if (!empty($missing)) {
  866. $missingMsg = implode(PHP_EOL, $missing);
  867. throw new \Exception(
  868. $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
  869. [$info['name'], $missingMsg]
  870. )
  871. );
  872. }
  873. }
  874. }