OC_App.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. * checks whether or not an app is enabled
  225. *
  226. * @param string $app app
  227. * @return bool
  228. * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
  229. *
  230. * This function checks whether or not an app is enabled.
  231. */
  232. public static function isEnabled(string $app): bool {
  233. return \OC::$server->getAppManager()->isEnabledForUser($app);
  234. }
  235. /**
  236. * enables an app
  237. *
  238. * @param string $appId
  239. * @param array $groups (optional) when set, only these groups will have access to the app
  240. * @throws \Exception
  241. * @return void
  242. *
  243. * This function set an app as enabled in appconfig.
  244. */
  245. public function enable(string $appId,
  246. array $groups = []) {
  247. // Check if app is already downloaded
  248. /** @var Installer $installer */
  249. $installer = \OC::$server->query(Installer::class);
  250. $isDownloaded = $installer->isDownloaded($appId);
  251. if (!$isDownloaded) {
  252. $installer->downloadApp($appId);
  253. }
  254. $installer->installApp($appId);
  255. $appManager = \OC::$server->getAppManager();
  256. if ($groups !== []) {
  257. $groupManager = \OC::$server->getGroupManager();
  258. $groupsList = [];
  259. foreach ($groups as $group) {
  260. $groupItem = $groupManager->get($group);
  261. if ($groupItem instanceof \OCP\IGroup) {
  262. $groupsList[] = $groupManager->get($group);
  263. }
  264. }
  265. $appManager->enableAppForGroups($appId, $groupsList);
  266. } else {
  267. $appManager->enableApp($appId);
  268. }
  269. }
  270. /**
  271. * Get the path where to install apps
  272. *
  273. * @return string|false
  274. */
  275. public static function getInstallPath() {
  276. foreach (OC::$APPSROOTS as $dir) {
  277. if (isset($dir['writable']) && $dir['writable'] === true) {
  278. return $dir['path'];
  279. }
  280. }
  281. \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
  282. return null;
  283. }
  284. /**
  285. * search for an app in all app-directories
  286. *
  287. * @param string $appId
  288. * @param bool $ignoreCache ignore cache and rebuild it
  289. * @return false|string
  290. */
  291. public static function findAppInDirectories(string $appId, bool $ignoreCache = false) {
  292. $sanitizedAppId = self::cleanAppId($appId);
  293. if ($sanitizedAppId !== $appId) {
  294. return false;
  295. }
  296. static $app_dir = [];
  297. if (isset($app_dir[$appId]) && !$ignoreCache) {
  298. return $app_dir[$appId];
  299. }
  300. $possibleApps = [];
  301. foreach (OC::$APPSROOTS as $dir) {
  302. if (file_exists($dir['path'] . '/' . $appId)) {
  303. $possibleApps[] = $dir;
  304. }
  305. }
  306. if (empty($possibleApps)) {
  307. return false;
  308. } elseif (count($possibleApps) === 1) {
  309. $dir = array_shift($possibleApps);
  310. $app_dir[$appId] = $dir;
  311. return $dir;
  312. } else {
  313. $versionToLoad = [];
  314. foreach ($possibleApps as $possibleApp) {
  315. $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
  316. if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
  317. $versionToLoad = [
  318. 'dir' => $possibleApp,
  319. 'version' => $version,
  320. ];
  321. }
  322. }
  323. $app_dir[$appId] = $versionToLoad['dir'];
  324. return $versionToLoad['dir'];
  325. //TODO - write test
  326. }
  327. }
  328. /**
  329. * Get the directory for the given app.
  330. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  331. *
  332. * @psalm-taint-specialize
  333. *
  334. * @param string $appId
  335. * @param bool $refreshAppPath should be set to true only during install/upgrade
  336. * @return string|false
  337. * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
  338. */
  339. public static function getAppPath(string $appId, bool $refreshAppPath = false) {
  340. if ($appId === null || trim($appId) === '') {
  341. return false;
  342. }
  343. if (($dir = self::findAppInDirectories($appId, $refreshAppPath)) != false) {
  344. return $dir['path'] . '/' . $appId;
  345. }
  346. return false;
  347. }
  348. /**
  349. * Get the path for the given app on the access
  350. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  351. *
  352. * @param string $appId
  353. * @return string|false
  354. * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
  355. */
  356. public static function getAppWebPath(string $appId) {
  357. if (($dir = self::findAppInDirectories($appId)) != false) {
  358. return OC::$WEBROOT . $dir['url'] . '/' . $appId;
  359. }
  360. return false;
  361. }
  362. /**
  363. * get the last version of the app from appinfo/info.xml
  364. *
  365. * @param string $appId
  366. * @param bool $useCache
  367. * @return string
  368. * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
  369. */
  370. public static function getAppVersion(string $appId, bool $useCache = true): string {
  371. return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
  372. }
  373. /**
  374. * get app's version based on it's path
  375. *
  376. * @param string $path
  377. * @return string
  378. */
  379. public static function getAppVersionByPath(string $path): string {
  380. $infoFile = $path . '/appinfo/info.xml';
  381. $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
  382. return isset($appData['version']) ? $appData['version'] : '';
  383. }
  384. /**
  385. * Read all app metadata from the info.xml file
  386. *
  387. * @param string $appId id of the app or the path of the info.xml file
  388. * @param bool $path
  389. * @param string $lang
  390. * @return array|null
  391. * @note all data is read from info.xml, not just pre-defined fields
  392. * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
  393. */
  394. public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
  395. return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
  396. }
  397. /**
  398. * Returns the navigation
  399. *
  400. * @return array
  401. * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
  402. *
  403. * This function returns an array containing all entries added. The
  404. * entries are sorted by the key 'order' ascending. Additional to the keys
  405. * given for each app the following keys exist:
  406. * - active: boolean, signals if the user is on this navigation entry
  407. */
  408. public static function getNavigation(): array {
  409. return OC::$server->getNavigationManager()->getAll();
  410. }
  411. /**
  412. * Returns the Settings Navigation
  413. *
  414. * @return string[]
  415. * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
  416. *
  417. * This function returns an array containing all settings pages added. The
  418. * entries are sorted by the key 'order' ascending.
  419. */
  420. public static function getSettingsNavigation(): array {
  421. return OC::$server->getNavigationManager()->getAll('settings');
  422. }
  423. /**
  424. * get the id of loaded app
  425. *
  426. * @return string
  427. */
  428. public static function getCurrentApp(): string {
  429. if (\OC::$CLI) {
  430. return '';
  431. }
  432. $request = \OC::$server->getRequest();
  433. $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
  434. $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
  435. if (empty($topFolder)) {
  436. try {
  437. $path_info = $request->getPathInfo();
  438. } catch (Exception $e) {
  439. // Can happen from unit tests because the script name is `./vendor/bin/phpunit` or something a like then.
  440. \OC::$server->get(LoggerInterface::class)->error('Failed to detect current app from script path', ['exception' => $e]);
  441. return '';
  442. }
  443. if ($path_info) {
  444. $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
  445. }
  446. }
  447. if ($topFolder == 'apps') {
  448. $length = strlen($topFolder);
  449. return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
  450. } else {
  451. return $topFolder;
  452. }
  453. }
  454. /**
  455. * @param string $type
  456. * @return array
  457. */
  458. public static function getForms(string $type): array {
  459. $forms = [];
  460. switch ($type) {
  461. case 'admin':
  462. $source = self::$adminForms;
  463. break;
  464. case 'personal':
  465. $source = self::$personalForms;
  466. break;
  467. default:
  468. return [];
  469. }
  470. foreach ($source as $form) {
  471. $forms[] = include $form;
  472. }
  473. return $forms;
  474. }
  475. /**
  476. * @param array $entry
  477. * @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
  478. */
  479. public static function registerLogIn(array $entry) {
  480. \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');
  481. self::$altLogin[] = $entry;
  482. }
  483. /**
  484. * @return array
  485. */
  486. public static function getAlternativeLogIns(): array {
  487. /** @var Coordinator $bootstrapCoordinator */
  488. $bootstrapCoordinator = \OC::$server->query(Coordinator::class);
  489. foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
  490. if (!in_array(IAlternativeLogin::class, class_implements($registration->getService()), true)) {
  491. \OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
  492. 'option' => $registration->getService(),
  493. 'interface' => IAlternativeLogin::class,
  494. 'app' => $registration->getAppId(),
  495. ]);
  496. continue;
  497. }
  498. try {
  499. /** @var IAlternativeLogin $provider */
  500. $provider = \OC::$server->query($registration->getService());
  501. } catch (QueryException $e) {
  502. \OC::$server->getLogger()->logException($e, [
  503. 'message' => 'Alternative login option {option} can not be initialised.',
  504. 'option' => $registration->getService(),
  505. 'app' => $registration->getAppId(),
  506. ]);
  507. }
  508. try {
  509. $provider->load();
  510. self::$altLogin[] = [
  511. 'name' => $provider->getLabel(),
  512. 'href' => $provider->getLink(),
  513. 'class' => $provider->getClass(),
  514. ];
  515. } catch (Throwable $e) {
  516. \OC::$server->getLogger()->logException($e, [
  517. 'message' => 'Alternative login option {option} had an error while loading.',
  518. 'option' => $registration->getService(),
  519. 'app' => $registration->getAppId(),
  520. ]);
  521. }
  522. }
  523. return self::$altLogin;
  524. }
  525. /**
  526. * get a list of all apps in the apps folder
  527. *
  528. * @return string[] an array of app names (string IDs)
  529. * @todo: change the name of this method to getInstalledApps, which is more accurate
  530. */
  531. public static function getAllApps(): array {
  532. $apps = [];
  533. foreach (OC::$APPSROOTS as $apps_dir) {
  534. if (!is_readable($apps_dir['path'])) {
  535. \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
  536. continue;
  537. }
  538. $dh = opendir($apps_dir['path']);
  539. if (is_resource($dh)) {
  540. while (($file = readdir($dh)) !== false) {
  541. if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
  542. $apps[] = $file;
  543. }
  544. }
  545. }
  546. }
  547. $apps = array_unique($apps);
  548. return $apps;
  549. }
  550. /**
  551. * List all supported apps
  552. *
  553. * @return array
  554. */
  555. public function getSupportedApps(): array {
  556. /** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
  557. $subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
  558. $supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
  559. return $supportedApps;
  560. }
  561. /**
  562. * List all apps, this is used in apps.php
  563. *
  564. * @return array
  565. */
  566. public function listAllApps(): array {
  567. $installedApps = OC_App::getAllApps();
  568. $appManager = \OC::$server->getAppManager();
  569. //we don't want to show configuration for these
  570. $blacklist = $appManager->getAlwaysEnabledApps();
  571. $appList = [];
  572. $langCode = \OC::$server->getL10N('core')->getLanguageCode();
  573. $urlGenerator = \OC::$server->getURLGenerator();
  574. $supportedApps = $this->getSupportedApps();
  575. foreach ($installedApps as $app) {
  576. if (array_search($app, $blacklist) === false) {
  577. $info = OC_App::getAppInfo($app, false, $langCode);
  578. if (!is_array($info)) {
  579. \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
  580. continue;
  581. }
  582. if (!isset($info['name'])) {
  583. \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
  584. continue;
  585. }
  586. $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
  587. $info['groups'] = null;
  588. if ($enabled === 'yes') {
  589. $active = true;
  590. } elseif ($enabled === 'no') {
  591. $active = false;
  592. } else {
  593. $active = true;
  594. $info['groups'] = $enabled;
  595. }
  596. $info['active'] = $active;
  597. if ($appManager->isShipped($app)) {
  598. $info['internal'] = true;
  599. $info['level'] = self::officialApp;
  600. $info['removable'] = false;
  601. } else {
  602. $info['internal'] = false;
  603. $info['removable'] = true;
  604. }
  605. if (in_array($app, $supportedApps)) {
  606. $info['level'] = self::supportedApp;
  607. }
  608. $appPath = self::getAppPath($app);
  609. if ($appPath !== false) {
  610. $appIcon = $appPath . '/img/' . $app . '.svg';
  611. if (file_exists($appIcon)) {
  612. $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
  613. $info['previewAsIcon'] = true;
  614. } else {
  615. $appIcon = $appPath . '/img/app.svg';
  616. if (file_exists($appIcon)) {
  617. $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
  618. $info['previewAsIcon'] = true;
  619. }
  620. }
  621. }
  622. // fix documentation
  623. if (isset($info['documentation']) && is_array($info['documentation'])) {
  624. foreach ($info['documentation'] as $key => $url) {
  625. // If it is not an absolute URL we assume it is a key
  626. // i.e. admin-ldap will get converted to go.php?to=admin-ldap
  627. if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
  628. $url = $urlGenerator->linkToDocs($url);
  629. }
  630. $info['documentation'][$key] = $url;
  631. }
  632. }
  633. $info['version'] = OC_App::getAppVersion($app);
  634. $appList[] = $info;
  635. }
  636. }
  637. return $appList;
  638. }
  639. public static function shouldUpgrade(string $app): bool {
  640. $versions = self::getAppVersions();
  641. $currentVersion = OC_App::getAppVersion($app);
  642. if ($currentVersion && isset($versions[$app])) {
  643. $installedVersion = $versions[$app];
  644. if (!version_compare($currentVersion, $installedVersion, '=')) {
  645. return true;
  646. }
  647. }
  648. return false;
  649. }
  650. /**
  651. * Adjust the number of version parts of $version1 to match
  652. * the number of version parts of $version2.
  653. *
  654. * @param string $version1 version to adjust
  655. * @param string $version2 version to take the number of parts from
  656. * @return string shortened $version1
  657. */
  658. private static function adjustVersionParts(string $version1, string $version2): string {
  659. $version1 = explode('.', $version1);
  660. $version2 = explode('.', $version2);
  661. // reduce $version1 to match the number of parts in $version2
  662. while (count($version1) > count($version2)) {
  663. array_pop($version1);
  664. }
  665. // if $version1 does not have enough parts, add some
  666. while (count($version1) < count($version2)) {
  667. $version1[] = '0';
  668. }
  669. return implode('.', $version1);
  670. }
  671. /**
  672. * Check whether the current ownCloud version matches the given
  673. * application's version requirements.
  674. *
  675. * The comparison is made based on the number of parts that the
  676. * app info version has. For example for ownCloud 6.0.3 if the
  677. * app info version is expecting version 6.0, the comparison is
  678. * made on the first two parts of the ownCloud version.
  679. * This means that it's possible to specify "requiremin" => 6
  680. * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
  681. *
  682. * @param string $ocVersion ownCloud version to check against
  683. * @param array $appInfo app info (from xml)
  684. *
  685. * @return boolean true if compatible, otherwise false
  686. */
  687. public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
  688. $requireMin = '';
  689. $requireMax = '';
  690. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
  691. $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
  692. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
  693. $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
  694. } elseif (isset($appInfo['requiremin'])) {
  695. $requireMin = $appInfo['requiremin'];
  696. } elseif (isset($appInfo['require'])) {
  697. $requireMin = $appInfo['require'];
  698. }
  699. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
  700. $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
  701. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
  702. $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
  703. } elseif (isset($appInfo['requiremax'])) {
  704. $requireMax = $appInfo['requiremax'];
  705. }
  706. if (!empty($requireMin)
  707. && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
  708. ) {
  709. return false;
  710. }
  711. if (!$ignoreMax && !empty($requireMax)
  712. && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
  713. ) {
  714. return false;
  715. }
  716. return true;
  717. }
  718. /**
  719. * get the installed version of all apps
  720. */
  721. public static function getAppVersions() {
  722. static $versions;
  723. if (!$versions) {
  724. $appConfig = \OC::$server->getAppConfig();
  725. $versions = $appConfig->getValues(false, 'installed_version');
  726. }
  727. return $versions;
  728. }
  729. /**
  730. * update the database for the app and call the update script
  731. *
  732. * @param string $appId
  733. * @return bool
  734. */
  735. public static function updateApp(string $appId): bool {
  736. // for apps distributed with core, we refresh app path in case the downloaded version
  737. // have been installed in custom apps and not in the default path
  738. $appPath = self::getAppPath($appId, true);
  739. if ($appPath === false) {
  740. return false;
  741. }
  742. if (is_file($appPath . '/appinfo/database.xml')) {
  743. \OC::$server->getLogger()->error('The appinfo/database.xml file is not longer supported. Used in ' . $appId);
  744. return false;
  745. }
  746. \OC::$server->getAppManager()->clearAppsCache();
  747. $l = \OC::$server->getL10N('core');
  748. $appData = self::getAppInfo($appId, false, $l->getLanguageCode());
  749. $ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []);
  750. $ignoreMax = in_array($appId, $ignoreMaxApps, true);
  751. \OC_App::checkAppDependencies(
  752. \OC::$server->getConfig(),
  753. $l,
  754. $appData,
  755. $ignoreMax
  756. );
  757. self::registerAutoloading($appId, $appPath, true);
  758. self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
  759. $ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
  760. $ms->migrate();
  761. self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
  762. self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
  763. // update appversion in app manager
  764. \OC::$server->getAppManager()->clearAppsCache();
  765. \OC::$server->getAppManager()->getAppVersion($appId, false);
  766. self::setupBackgroundJobs($appData['background-jobs']);
  767. //set remote/public handlers
  768. if (array_key_exists('ocsid', $appData)) {
  769. \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
  770. } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
  771. \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
  772. }
  773. foreach ($appData['remote'] as $name => $path) {
  774. \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
  775. }
  776. foreach ($appData['public'] as $name => $path) {
  777. \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
  778. }
  779. self::setAppTypes($appId);
  780. $version = \OC_App::getAppVersion($appId);
  781. \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
  782. \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new AppUpdateEvent($appId));
  783. \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
  784. ManagerEvent::EVENT_APP_UPDATE, $appId
  785. ));
  786. return true;
  787. }
  788. /**
  789. * @param string $appId
  790. * @param string[] $steps
  791. * @throws \OC\NeedsUpdateException
  792. */
  793. public static function executeRepairSteps(string $appId, array $steps) {
  794. if (empty($steps)) {
  795. return;
  796. }
  797. // load the app
  798. self::loadApp($appId);
  799. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  800. // load the steps
  801. $r = new Repair([], $dispatcher, \OC::$server->get(LoggerInterface::class));
  802. foreach ($steps as $step) {
  803. try {
  804. $r->addStep($step);
  805. } catch (Exception $ex) {
  806. $dispatcher->dispatchTyped(new RepairErrorEvent($ex->getMessage()));
  807. \OC::$server->getLogger()->logException($ex);
  808. }
  809. }
  810. // run the steps
  811. $r->run();
  812. }
  813. public static function setupBackgroundJobs(array $jobs) {
  814. $queue = \OC::$server->getJobList();
  815. foreach ($jobs as $job) {
  816. $queue->add($job);
  817. }
  818. }
  819. /**
  820. * @param string $appId
  821. * @param string[] $steps
  822. */
  823. private static function setupLiveMigrations(string $appId, array $steps) {
  824. $queue = \OC::$server->getJobList();
  825. foreach ($steps as $step) {
  826. $queue->add('OC\Migration\BackgroundRepair', [
  827. 'app' => $appId,
  828. 'step' => $step]);
  829. }
  830. }
  831. /**
  832. * @param string $appId
  833. * @return \OC\Files\View|false
  834. */
  835. public static function getStorage(string $appId) {
  836. if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
  837. if (\OC::$server->getUserSession()->isLoggedIn()) {
  838. $view = new \OC\Files\View('/' . OC_User::getUser());
  839. if (!$view->file_exists($appId)) {
  840. $view->mkdir($appId);
  841. }
  842. return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
  843. } else {
  844. \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
  845. return false;
  846. }
  847. } else {
  848. \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
  849. return false;
  850. }
  851. }
  852. protected static function findBestL10NOption(array $options, string $lang): string {
  853. // only a single option
  854. if (isset($options['@value'])) {
  855. return $options['@value'];
  856. }
  857. $fallback = $similarLangFallback = $englishFallback = false;
  858. $lang = strtolower($lang);
  859. $similarLang = $lang;
  860. if (strpos($similarLang, '_')) {
  861. // For "de_DE" we want to find "de" and the other way around
  862. $similarLang = substr($lang, 0, strpos($lang, '_'));
  863. }
  864. foreach ($options as $option) {
  865. if (is_array($option)) {
  866. if ($fallback === false) {
  867. $fallback = $option['@value'];
  868. }
  869. if (!isset($option['@attributes']['lang'])) {
  870. continue;
  871. }
  872. $attributeLang = strtolower($option['@attributes']['lang']);
  873. if ($attributeLang === $lang) {
  874. return $option['@value'];
  875. }
  876. if ($attributeLang === $similarLang) {
  877. $similarLangFallback = $option['@value'];
  878. } elseif (strpos($attributeLang, $similarLang . '_') === 0) {
  879. if ($similarLangFallback === false) {
  880. $similarLangFallback = $option['@value'];
  881. }
  882. }
  883. } else {
  884. $englishFallback = $option;
  885. }
  886. }
  887. if ($similarLangFallback !== false) {
  888. return $similarLangFallback;
  889. } elseif ($englishFallback !== false) {
  890. return $englishFallback;
  891. }
  892. return (string) $fallback;
  893. }
  894. /**
  895. * parses the app data array and enhanced the 'description' value
  896. *
  897. * @param array $data the app data
  898. * @param string $lang
  899. * @return array improved app data
  900. */
  901. public static function parseAppInfo(array $data, $lang = null): array {
  902. if ($lang && isset($data['name']) && is_array($data['name'])) {
  903. $data['name'] = self::findBestL10NOption($data['name'], $lang);
  904. }
  905. if ($lang && isset($data['summary']) && is_array($data['summary'])) {
  906. $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
  907. }
  908. if ($lang && isset($data['description']) && is_array($data['description'])) {
  909. $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
  910. } elseif (isset($data['description']) && is_string($data['description'])) {
  911. $data['description'] = trim($data['description']);
  912. } else {
  913. $data['description'] = '';
  914. }
  915. return $data;
  916. }
  917. /**
  918. * @param \OCP\IConfig $config
  919. * @param \OCP\IL10N $l
  920. * @param array $info
  921. * @throws \Exception
  922. */
  923. public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
  924. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
  925. $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
  926. if (!empty($missing)) {
  927. $missingMsg = implode(PHP_EOL, $missing);
  928. throw new \Exception(
  929. $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
  930. [$info['name'], $missingMsg]
  931. )
  932. );
  933. }
  934. }
  935. }