You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1180 lines
35 KiB

3 years ago
  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 <pvince81@owncloud.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\ServerNotAvailableException;
  58. use OCP\App\ManagerEvent;
  59. use OCP\AppFramework\QueryException;
  60. use OCP\Authentication\IAlternativeLogin;
  61. use OCP\ILogger;
  62. /**
  63. * This class manages the apps. It allows them to register and integrate in the
  64. * ownCloud ecosystem. Furthermore, this class is responsible for installing,
  65. * upgrading and removing apps.
  66. */
  67. class OC_App {
  68. private static $adminForms = [];
  69. private static $personalForms = [];
  70. private static $appTypes = [];
  71. private static $loadedApps = [];
  72. private static $altLogin = [];
  73. private static $alreadyRegistered = [];
  74. public const supportedApp = 300;
  75. public const officialApp = 200;
  76. /**
  77. * clean the appId
  78. *
  79. * @param string $app AppId that needs to be cleaned
  80. * @return string
  81. */
  82. public static function cleanAppId(string $app): string {
  83. return str_replace(['\0', '/', '\\', '..'], '', $app);
  84. }
  85. /**
  86. * Check if an app is loaded
  87. *
  88. * @param string $app
  89. * @return bool
  90. */
  91. public static function isAppLoaded(string $app): bool {
  92. return in_array($app, self::$loadedApps, true);
  93. }
  94. /**
  95. * loads all apps
  96. *
  97. * @param string[] $types
  98. * @return bool
  99. *
  100. * This function walks through the ownCloud directory and loads all apps
  101. * it can find. A directory contains an app if the file /appinfo/info.xml
  102. * exists.
  103. *
  104. * if $types is set to non-empty array, only apps of those types will be loaded
  105. */
  106. public static function loadApps(array $types = []): bool {
  107. if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
  108. return false;
  109. }
  110. // Load the enabled apps here
  111. $apps = self::getEnabledApps();
  112. // Add each apps' folder as allowed class path
  113. foreach ($apps as $app) {
  114. $path = self::getAppPath($app);
  115. if ($path !== false) {
  116. self::registerAutoloading($app, $path);
  117. }
  118. }
  119. // prevent app.php from printing output
  120. ob_start();
  121. foreach ($apps as $app) {
  122. if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
  123. self::loadApp($app);
  124. }
  125. }
  126. ob_end_clean();
  127. return true;
  128. }
  129. /**
  130. * load a single app
  131. *
  132. * @param string $app
  133. * @throws Exception
  134. */
  135. public static function loadApp(string $app) {
  136. self::$loadedApps[] = $app;
  137. $appPath = self::getAppPath($app);
  138. if ($appPath === false) {
  139. return;
  140. }
  141. // in case someone calls loadApp() directly
  142. self::registerAutoloading($app, $appPath);
  143. /** @var Coordinator $coordinator */
  144. $coordinator = \OC::$server->query(Coordinator::class);
  145. $isBootable = $coordinator->isBootable($app);
  146. $hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
  147. if ($isBootable && $hasAppPhpFile) {
  148. \OC::$server->getLogger()->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
  149. 'app' => $app,
  150. ]);
  151. } elseif ($hasAppPhpFile) {
  152. \OC::$server->getLogger()->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
  153. 'app' => $app,
  154. ]);
  155. \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
  156. try {
  157. self::requireAppFile($app);
  158. } catch (Throwable $ex) {
  159. if ($ex instanceof ServerNotAvailableException) {
  160. throw $ex;
  161. }
  162. if (!\OC::$server->getAppManager()->isShipped($app) && !self::isType($app, ['authentication'])) {
  163. \OC::$server->getLogger()->logException($ex, [
  164. 'message' => "App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(),
  165. ]);
  166. // Only disable apps which are not shipped and that are not authentication apps
  167. \OC::$server->getAppManager()->disableApp($app, true);
  168. } else {
  169. \OC::$server->getLogger()->logException($ex, [
  170. 'message' => "App $app threw an error during app.php load: " . $ex->getMessage(),
  171. ]);
  172. }
  173. }
  174. \OC::$server->getEventLogger()->end('load_app_' . $app);
  175. }
  176. $coordinator->bootApp($app);
  177. $info = self::getAppInfo($app);
  178. if (!empty($info['activity']['filters'])) {
  179. foreach ($info['activity']['filters'] as $filter) {
  180. \OC::$server->getActivityManager()->registerFilter($filter);
  181. }
  182. }
  183. if (!empty($info['activity']['settings'])) {
  184. foreach ($info['activity']['settings'] as $setting) {
  185. \OC::$server->getActivityManager()->registerSetting($setting);
  186. }
  187. }
  188. if (!empty($info['activity']['providers'])) {
  189. foreach ($info['activity']['providers'] as $provider) {
  190. \OC::$server->getActivityManager()->registerProvider($provider);
  191. }
  192. }
  193. if (!empty($info['settings']['admin'])) {
  194. foreach ($info['settings']['admin'] as $setting) {
  195. \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
  196. }
  197. }
  198. if (!empty($info['settings']['admin-section'])) {
  199. foreach ($info['settings']['admin-section'] as $section) {
  200. \OC::$server->getSettingsManager()->registerSection('admin', $section);
  201. }
  202. }
  203. if (!empty($info['settings']['personal'])) {
  204. foreach ($info['settings']['personal'] as $setting) {
  205. \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
  206. }
  207. }
  208. if (!empty($info['settings']['personal-section'])) {
  209. foreach ($info['settings']['personal-section'] as $section) {
  210. \OC::$server->getSettingsManager()->registerSection('personal', $section);
  211. }
  212. }
  213. if (!empty($info['collaboration']['plugins'])) {
  214. // deal with one or many plugin entries
  215. $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
  216. [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
  217. foreach ($plugins as $plugin) {
  218. if ($plugin['@attributes']['type'] === 'collaborator-search') {
  219. $pluginInfo = [
  220. 'shareType' => $plugin['@attributes']['share-type'],
  221. 'class' => $plugin['@value'],
  222. ];
  223. \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
  224. } elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
  225. \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
  226. }
  227. }
  228. }
  229. }
  230. /**
  231. * @internal
  232. * @param string $app
  233. * @param string $path
  234. * @param bool $force
  235. */
  236. public static function registerAutoloading(string $app, string $path, bool $force = false) {
  237. $key = $app . '-' . $path;
  238. if (!$force && isset(self::$alreadyRegistered[$key])) {
  239. return;
  240. }
  241. self::$alreadyRegistered[$key] = true;
  242. // Register on PSR-4 composer autoloader
  243. $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
  244. \OC::$server->registerNamespace($app, $appNamespace);
  245. if (file_exists($path . '/composer/autoload.php')) {
  246. require_once $path . '/composer/autoload.php';
  247. } else {
  248. \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
  249. // Register on legacy autoloader
  250. \OC::$loader->addValidRoot($path);
  251. }
  252. // Register Test namespace only when testing
  253. if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
  254. \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
  255. }
  256. }
  257. /**
  258. * Load app.php from the given app
  259. *
  260. * @param string $app app name
  261. * @throws Error
  262. */
  263. private static function requireAppFile(string $app) {
  264. // encapsulated here to avoid variable scope conflicts
  265. require_once $app . '/appinfo/app.php';
  266. }
  267. /**
  268. * check if an app is of a specific type
  269. *
  270. * @param string $app
  271. * @param array $types
  272. * @return bool
  273. */
  274. public static function isType(string $app, array $types): bool {
  275. $appTypes = self::getAppTypes($app);
  276. foreach ($types as $type) {
  277. if (array_search($type, $appTypes) !== false) {
  278. return true;
  279. }
  280. }
  281. return false;
  282. }
  283. /**
  284. * get the types of an app
  285. *
  286. * @param string $app
  287. * @return array
  288. */
  289. private static function getAppTypes(string $app): array {
  290. //load the cache
  291. if (count(self::$appTypes) == 0) {
  292. self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
  293. }
  294. if (isset(self::$appTypes[$app])) {
  295. return explode(',', self::$appTypes[$app]);
  296. }
  297. return [];
  298. }
  299. /**
  300. * read app types from info.xml and cache them in the database
  301. */
  302. public static function setAppTypes(string $app) {
  303. $appManager = \OC::$server->getAppManager();
  304. $appData = $appManager->getAppInfo($app);
  305. if (!is_array($appData)) {
  306. return;
  307. }
  308. if (isset($appData['types'])) {
  309. $appTypes = implode(',', $appData['types']);
  310. } else {
  311. $appTypes = '';
  312. $appData['types'] = [];
  313. }
  314. $config = \OC::$server->getConfig();
  315. $config->setAppValue($app, 'types', $appTypes);
  316. if ($appManager->hasProtectedAppType($appData['types'])) {
  317. $enabled = $config->getAppValue($app, 'enabled', 'yes');
  318. if ($enabled !== 'yes' && $enabled !== 'no') {
  319. $config->setAppValue($app, 'enabled', 'yes');
  320. }
  321. }
  322. }
  323. /**
  324. * Returns apps enabled for the current user.
  325. *
  326. * @param bool $forceRefresh whether to refresh the cache
  327. * @param bool $all whether to return apps for all users, not only the
  328. * currently logged in one
  329. * @return string[]
  330. */
  331. public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
  332. if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
  333. return [];
  334. }
  335. // in incognito mode or when logged out, $user will be false,
  336. // which is also the case during an upgrade
  337. $appManager = \OC::$server->getAppManager();
  338. if ($all) {
  339. $user = null;
  340. } else {
  341. $user = \OC::$server->getUserSession()->getUser();
  342. }
  343. if (is_null($user)) {
  344. $apps = $appManager->getInstalledApps();
  345. } else {
  346. $apps = $appManager->getEnabledAppsForUser($user);
  347. }
  348. $apps = array_filter($apps, function ($app) {
  349. return $app !== 'files';//we add this manually
  350. });
  351. sort($apps);
  352. array_unshift($apps, 'files');
  353. return $apps;
  354. }
  355. /**
  356. * checks whether or not an app is enabled
  357. *
  358. * @param string $app app
  359. * @return bool
  360. * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
  361. *
  362. * This function checks whether or not an app is enabled.
  363. */
  364. public static function isEnabled(string $app): bool {
  365. return \OC::$server->getAppManager()->isEnabledForUser($app);
  366. }
  367. /**
  368. * enables an app
  369. *
  370. * @param string $appId
  371. * @param array $groups (optional) when set, only these groups will have access to the app
  372. * @throws \Exception
  373. * @return void
  374. *
  375. * This function set an app as enabled in appconfig.
  376. */
  377. public function enable(string $appId,
  378. array $groups = []) {
  379. // Check if app is already downloaded
  380. /** @var Installer $installer */
  381. $installer = \OC::$server->query(Installer::class);
  382. $isDownloaded = $installer->isDownloaded($appId);
  383. if (!$isDownloaded) {
  384. $installer->downloadApp($appId);
  385. }
  386. $installer->installApp($appId);
  387. $appManager = \OC::$server->getAppManager();
  388. if ($groups !== []) {
  389. $groupManager = \OC::$server->getGroupManager();
  390. $groupsList = [];
  391. foreach ($groups as $group) {
  392. $groupItem = $groupManager->get($group);
  393. if ($groupItem instanceof \OCP\IGroup) {
  394. $groupsList[] = $groupManager->get($group);
  395. }
  396. }
  397. $appManager->enableAppForGroups($appId, $groupsList);
  398. } else {
  399. $appManager->enableApp($appId);
  400. }
  401. }
  402. /**
  403. * Get the path where to install apps
  404. *
  405. * @return string|false
  406. */
  407. public static function getInstallPath() {
  408. if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
  409. return false;
  410. }
  411. foreach (OC::$APPSROOTS as $dir) {
  412. if (isset($dir['writable']) && $dir['writable'] === true) {
  413. return $dir['path'];
  414. }
  415. }
  416. \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
  417. return null;
  418. }
  419. /**
  420. * search for an app in all app-directories
  421. *
  422. * @param string $appId
  423. * @return false|string
  424. */
  425. public static function findAppInDirectories(string $appId) {
  426. $sanitizedAppId = self::cleanAppId($appId);
  427. if ($sanitizedAppId !== $appId) {
  428. return false;
  429. }
  430. static $app_dir = [];
  431. if (isset($app_dir[$appId])) {
  432. return $app_dir[$appId];
  433. }
  434. $possibleApps = [];
  435. foreach (OC::$APPSROOTS as $dir) {
  436. if (file_exists($dir['path'] . '/' . $appId)) {
  437. $possibleApps[] = $dir;
  438. }
  439. }
  440. if (empty($possibleApps)) {
  441. return false;
  442. } elseif (count($possibleApps) === 1) {
  443. $dir = array_shift($possibleApps);
  444. $app_dir[$appId] = $dir;
  445. return $dir;
  446. } else {
  447. $versionToLoad = [];
  448. foreach ($possibleApps as $possibleApp) {
  449. $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
  450. if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
  451. $versionToLoad = [
  452. 'dir' => $possibleApp,
  453. 'version' => $version,
  454. ];
  455. }
  456. }
  457. $app_dir[$appId] = $versionToLoad['dir'];
  458. return $versionToLoad['dir'];
  459. //TODO - write test
  460. }
  461. }
  462. /**
  463. * Get the directory for the given app.
  464. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  465. *
  466. * @param string $appId
  467. * @return string|false
  468. * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
  469. */
  470. public static function getAppPath(string $appId) {
  471. if ($appId === null || trim($appId) === '') {
  472. return false;
  473. }
  474. if (($dir = self::findAppInDirectories($appId)) != false) {
  475. return $dir['path'] . '/' . $appId;
  476. }
  477. return false;
  478. }
  479. /**
  480. * Get the path for the given app on the access
  481. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  482. *
  483. * @param string $appId
  484. * @return string|false
  485. * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
  486. */
  487. public static function getAppWebPath(string $appId) {
  488. if (($dir = self::findAppInDirectories($appId)) != false) {
  489. return OC::$WEBROOT . $dir['url'] . '/' . $appId;
  490. }
  491. return false;
  492. }
  493. /**
  494. * get the last version of the app from appinfo/info.xml
  495. *
  496. * @param string $appId
  497. * @param bool $useCache
  498. * @return string
  499. * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
  500. */
  501. public static function getAppVersion(string $appId, bool $useCache = true): string {
  502. return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
  503. }
  504. /**
  505. * get app's version based on it's path
  506. *
  507. * @param string $path
  508. * @return string
  509. */
  510. public static function getAppVersionByPath(string $path): string {
  511. $infoFile = $path . '/appinfo/info.xml';
  512. $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
  513. return isset($appData['version']) ? $appData['version'] : '';
  514. }
  515. /**
  516. * Read all app metadata from the info.xml file
  517. *
  518. * @param string $appId id of the app or the path of the info.xml file
  519. * @param bool $path
  520. * @param string $lang
  521. * @return array|null
  522. * @note all data is read from info.xml, not just pre-defined fields
  523. * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
  524. */
  525. public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
  526. return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
  527. }
  528. /**
  529. * Returns the navigation
  530. *
  531. * @return array
  532. * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
  533. *
  534. * This function returns an array containing all entries added. The
  535. * entries are sorted by the key 'order' ascending. Additional to the keys
  536. * given for each app the following keys exist:
  537. * - active: boolean, signals if the user is on this navigation entry
  538. */
  539. public static function getNavigation(): array {
  540. return OC::$server->getNavigationManager()->getAll();
  541. }
  542. /**
  543. * Returns the Settings Navigation
  544. *
  545. * @return string[]
  546. * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
  547. *
  548. * This function returns an array containing all settings pages added. The
  549. * entries are sorted by the key 'order' ascending.
  550. */
  551. public static function getSettingsNavigation(): array {
  552. return OC::$server->getNavigationManager()->getAll('settings');
  553. }
  554. /**
  555. * get the id of loaded app
  556. *
  557. * @return string
  558. */
  559. public static function getCurrentApp(): string {
  560. $request = \OC::$server->getRequest();
  561. $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
  562. $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
  563. if (empty($topFolder)) {
  564. $path_info = $request->getPathInfo();
  565. if ($path_info) {
  566. $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
  567. }
  568. }
  569. if ($topFolder == 'apps') {
  570. $length = strlen($topFolder);
  571. return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
  572. } else {
  573. return $topFolder;
  574. }
  575. }
  576. /**
  577. * @param string $type
  578. * @return array
  579. */
  580. public static function getForms(string $type): array {
  581. $forms = [];
  582. switch ($type) {
  583. case 'admin':
  584. $source = self::$adminForms;
  585. break;
  586. case 'personal':
  587. $source = self::$personalForms;
  588. break;
  589. default:
  590. return [];
  591. }
  592. foreach ($source as $form) {
  593. $forms[] = include $form;
  594. }
  595. return $forms;
  596. }
  597. /**
  598. * register an admin form to be shown
  599. *
  600. * @param string $app
  601. * @param string $page
  602. */
  603. public static function registerAdmin(string $app, string $page) {
  604. self::$adminForms[] = $app . '/' . $page . '.php';
  605. }
  606. /**
  607. * register a personal form to be shown
  608. * @param string $app
  609. * @param string $page
  610. */
  611. public static function registerPersonal(string $app, string $page) {
  612. self::$personalForms[] = $app . '/' . $page . '.php';
  613. }
  614. /**
  615. * @param array $entry
  616. * @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
  617. */
  618. public static function registerLogIn(array $entry) {
  619. \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');
  620. self::$altLogin[] = $entry;
  621. }
  622. /**
  623. * @return array
  624. */
  625. public static function getAlternativeLogIns(): array {
  626. /** @var Coordinator $bootstrapCoordinator */
  627. $bootstrapCoordinator = \OC::$server->query(Coordinator::class);
  628. foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
  629. if (!in_array(IAlternativeLogin::class, class_implements($registration['class']), true)) {
  630. \OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
  631. 'option' => $registration['class'],
  632. 'interface' => IAlternativeLogin::class,
  633. 'app' => $registration['app'],
  634. ]);
  635. continue;
  636. }
  637. try {
  638. /** @var IAlternativeLogin $provider */
  639. $provider = \OC::$server->query($registration['class']);
  640. } catch (QueryException $e) {
  641. \OC::$server->getLogger()->logException($e, [
  642. 'message' => 'Alternative login option {option} can not be initialised.',
  643. 'option' => $registration['class'],
  644. 'app' => $registration['app'],
  645. ]);
  646. }
  647. try {
  648. $provider->load();
  649. self::$altLogin[] = [
  650. 'name' => $provider->getLabel(),
  651. 'href' => $provider->getLink(),
  652. 'style' => $provider->getClass(),
  653. ];
  654. } catch (Throwable $e) {
  655. \OC::$server->getLogger()->logException($e, [
  656. 'message' => 'Alternative login option {option} had an error while loading.',
  657. 'option' => $registration['class'],
  658. 'app' => $registration['app'],
  659. ]);
  660. }
  661. }
  662. return self::$altLogin;
  663. }
  664. /**
  665. * get a list of all apps in the apps folder
  666. *
  667. * @return string[] an array of app names (string IDs)
  668. * @todo: change the name of this method to getInstalledApps, which is more accurate
  669. */
  670. public static function getAllApps(): array {
  671. $apps = [];
  672. foreach (OC::$APPSROOTS as $apps_dir) {
  673. if (!is_readable($apps_dir['path'])) {
  674. \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
  675. continue;
  676. }
  677. $dh = opendir($apps_dir['path']);
  678. if (is_resource($dh)) {
  679. while (($file = readdir($dh)) !== false) {
  680. if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
  681. $apps[] = $file;
  682. }
  683. }
  684. }
  685. }
  686. $apps = array_unique($apps);
  687. return $apps;
  688. }
  689. /**
  690. * List all apps, this is used in apps.php
  691. *
  692. * @return array
  693. */
  694. public function listAllApps(): array {
  695. $installedApps = OC_App::getAllApps();
  696. $appManager = \OC::$server->getAppManager();
  697. //we don't want to show configuration for these
  698. $blacklist = $appManager->getAlwaysEnabledApps();
  699. $appList = [];
  700. $langCode = \OC::$server->getL10N('core')->getLanguageCode();
  701. $urlGenerator = \OC::$server->getURLGenerator();
  702. /** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
  703. $subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
  704. $supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
  705. foreach ($installedApps as $app) {
  706. if (array_search($app, $blacklist) === false) {
  707. $info = OC_App::getAppInfo($app, false, $langCode);
  708. if (!is_array($info)) {
  709. \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
  710. continue;
  711. }
  712. if (!isset($info['name'])) {
  713. \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
  714. continue;
  715. }
  716. $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
  717. $info['groups'] = null;
  718. if ($enabled === 'yes') {
  719. $active = true;
  720. } elseif ($enabled === 'no') {
  721. $active = false;
  722. } else {
  723. $active = true;
  724. $info['groups'] = $enabled;
  725. }
  726. $info['active'] = $active;
  727. if ($appManager->isShipped($app)) {
  728. $info['internal'] = true;
  729. $info['level'] = self::officialApp;
  730. $info['removable'] = false;
  731. } else {
  732. $info['internal'] = false;
  733. $info['removable'] = true;
  734. }
  735. if (in_array($app, $supportedApps)) {
  736. $info['level'] = self::supportedApp;
  737. }
  738. $appPath = self::getAppPath($app);
  739. if ($appPath !== false) {
  740. $appIcon = $appPath . '/img/' . $app . '.svg';
  741. if (file_exists($appIcon)) {
  742. $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
  743. $info['previewAsIcon'] = true;
  744. } else {
  745. $appIcon = $appPath . '/img/app.svg';
  746. if (file_exists($appIcon)) {
  747. $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
  748. $info['previewAsIcon'] = true;
  749. }
  750. }
  751. }
  752. // fix documentation
  753. if (isset($info['documentation']) && is_array($info['documentation'])) {
  754. foreach ($info['documentation'] as $key => $url) {
  755. // If it is not an absolute URL we assume it is a key
  756. // i.e. admin-ldap will get converted to go.php?to=admin-ldap
  757. if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
  758. $url = $urlGenerator->linkToDocs($url);
  759. }
  760. $info['documentation'][$key] = $url;
  761. }
  762. }
  763. $info['version'] = OC_App::getAppVersion($app);
  764. $appList[] = $info;
  765. }
  766. }
  767. return $appList;
  768. }
  769. public static function shouldUpgrade(string $app): bool {
  770. $versions = self::getAppVersions();
  771. $currentVersion = OC_App::getAppVersion($app);
  772. if ($currentVersion && isset($versions[$app])) {
  773. $installedVersion = $versions[$app];
  774. if (!version_compare($currentVersion, $installedVersion, '=')) {
  775. return true;
  776. }
  777. }
  778. return false;
  779. }
  780. /**
  781. * Adjust the number of version parts of $version1 to match
  782. * the number of version parts of $version2.
  783. *
  784. * @param string $version1 version to adjust
  785. * @param string $version2 version to take the number of parts from
  786. * @return string shortened $version1
  787. */
  788. private static function adjustVersionParts(string $version1, string $version2): string {
  789. $version1 = explode('.', $version1);
  790. $version2 = explode('.', $version2);
  791. // reduce $version1 to match the number of parts in $version2
  792. while (count($version1) > count($version2)) {
  793. array_pop($version1);
  794. }
  795. // if $version1 does not have enough parts, add some
  796. while (count($version1) < count($version2)) {
  797. $version1[] = '0';
  798. }
  799. return implode('.', $version1);
  800. }
  801. /**
  802. * Check whether the current ownCloud version matches the given
  803. * application's version requirements.
  804. *
  805. * The comparison is made based on the number of parts that the
  806. * app info version has. For example for ownCloud 6.0.3 if the
  807. * app info version is expecting version 6.0, the comparison is
  808. * made on the first two parts of the ownCloud version.
  809. * This means that it's possible to specify "requiremin" => 6
  810. * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
  811. *
  812. * @param string $ocVersion ownCloud version to check against
  813. * @param array $appInfo app info (from xml)
  814. *
  815. * @return boolean true if compatible, otherwise false
  816. */
  817. public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
  818. $requireMin = '';
  819. $requireMax = '';
  820. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
  821. $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
  822. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
  823. $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
  824. } elseif (isset($appInfo['requiremin'])) {
  825. $requireMin = $appInfo['requiremin'];
  826. } elseif (isset($appInfo['require'])) {
  827. $requireMin = $appInfo['require'];
  828. }
  829. if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
  830. $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
  831. } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
  832. $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
  833. } elseif (isset($appInfo['requiremax'])) {
  834. $requireMax = $appInfo['requiremax'];
  835. }
  836. if (!empty($requireMin)
  837. && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
  838. ) {
  839. return false;
  840. }
  841. if (!$ignoreMax && !empty($requireMax)
  842. && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
  843. ) {
  844. return false;
  845. }
  846. return true;
  847. }
  848. /**
  849. * get the installed version of all apps
  850. */
  851. public static function getAppVersions() {
  852. static $versions;
  853. if (!$versions) {
  854. $appConfig = \OC::$server->getAppConfig();
  855. $versions = $appConfig->getValues(false, 'installed_version');
  856. }
  857. return $versions;
  858. }
  859. /**
  860. * update the database for the app and call the update script
  861. *
  862. * @param string $appId
  863. * @return bool
  864. */
  865. public static function updateApp(string $appId): bool {
  866. $appPath = self::getAppPath($appId);
  867. if ($appPath === false) {
  868. return false;
  869. }
  870. \OC::$server->getAppManager()->clearAppsCache();
  871. $appData = self::getAppInfo($appId);
  872. self::registerAutoloading($appId, $appPath, true);
  873. self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
  874. if (file_exists($appPath . '/appinfo/database.xml')) {
  875. OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
  876. } else {
  877. $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
  878. $ms->migrate();
  879. }
  880. self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
  881. self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
  882. // update appversion in app manager
  883. \OC::$server->getAppManager()->clearAppsCache();
  884. \OC::$server->getAppManager()->getAppVersion($appId, false);
  885. // run upgrade code
  886. if (file_exists($appPath . '/appinfo/update.php')) {
  887. self::loadApp($appId);
  888. include $appPath . '/appinfo/update.php';
  889. }
  890. self::setupBackgroundJobs($appData['background-jobs']);
  891. //set remote/public handlers
  892. if (array_key_exists('ocsid', $appData)) {
  893. \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
  894. } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
  895. \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
  896. }
  897. foreach ($appData['remote'] as $name => $path) {
  898. \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
  899. }
  900. foreach ($appData['public'] as $name => $path) {
  901. \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
  902. }
  903. self::setAppTypes($appId);
  904. $version = \OC_App::getAppVersion($appId);
  905. \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
  906. \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
  907. ManagerEvent::EVENT_APP_UPDATE, $appId
  908. ));
  909. return true;
  910. }
  911. /**
  912. * @param string $appId
  913. * @param string[] $steps
  914. * @throws \OC\NeedsUpdateException
  915. */
  916. public static function executeRepairSteps(string $appId, array $steps) {
  917. if (empty($steps)) {
  918. return;
  919. }
  920. // load the app
  921. self::loadApp($appId);
  922. $dispatcher = OC::$server->getEventDispatcher();
  923. // load the steps
  924. $r = new Repair([], $dispatcher);
  925. foreach ($steps as $step) {
  926. try {
  927. $r->addStep($step);
  928. } catch (Exception $ex) {
  929. $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
  930. \OC::$server->getLogger()->logException($ex);
  931. }
  932. }
  933. // run the steps
  934. $r->run();
  935. }
  936. public static function setupBackgroundJobs(array $jobs) {
  937. $queue = \OC::$server->getJobList();
  938. foreach ($jobs as $job) {
  939. $queue->add($job);
  940. }
  941. }
  942. /**
  943. * @param string $appId
  944. * @param string[] $steps
  945. */
  946. private static function setupLiveMigrations(string $appId, array $steps) {
  947. $queue = \OC::$server->getJobList();
  948. foreach ($steps as $step) {
  949. $queue->add('OC\Migration\BackgroundRepair', [
  950. 'app' => $appId,
  951. 'step' => $step]);
  952. }
  953. }
  954. /**
  955. * @param string $appId
  956. * @return \OC\Files\View|false
  957. */
  958. public static function getStorage(string $appId) {
  959. if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
  960. if (\OC::$server->getUserSession()->isLoggedIn()) {
  961. $view = new \OC\Files\View('/' . OC_User::getUser());
  962. if (!$view->file_exists($appId)) {
  963. $view->mkdir($appId);
  964. }
  965. return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
  966. } else {
  967. \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
  968. return false;
  969. }
  970. } else {
  971. \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
  972. return false;
  973. }
  974. }
  975. protected static function findBestL10NOption(array $options, string $lang): string {
  976. // only a single option
  977. if (isset($options['@value'])) {
  978. return $options['@value'];
  979. }
  980. $fallback = $similarLangFallback = $englishFallback = false;
  981. $lang = strtolower($lang);
  982. $similarLang = $lang;
  983. if (strpos($similarLang, '_')) {
  984. // For "de_DE" we want to find "de" and the other way around
  985. $similarLang = substr($lang, 0, strpos($lang, '_'));
  986. }
  987. foreach ($options as $option) {
  988. if (is_array($option)) {
  989. if ($fallback === false) {
  990. $fallback = $option['@value'];
  991. }
  992. if (!isset($option['@attributes']['lang'])) {
  993. continue;
  994. }
  995. $attributeLang = strtolower($option['@attributes']['lang']);
  996. if ($attributeLang === $lang) {
  997. return $option['@value'];
  998. }
  999. if ($attributeLang === $similarLang) {
  1000. $similarLangFallback = $option['@value'];
  1001. } elseif (strpos($attributeLang, $similarLang . '_') === 0) {
  1002. if ($similarLangFallback === false) {
  1003. $similarLangFallback = $option['@value'];
  1004. }
  1005. }
  1006. } else {
  1007. $englishFallback = $option;
  1008. }
  1009. }
  1010. if ($similarLangFallback !== false) {
  1011. return $similarLangFallback;
  1012. } elseif ($englishFallback !== false) {
  1013. return $englishFallback;
  1014. }
  1015. return (string) $fallback;
  1016. }
  1017. /**
  1018. * parses the app data array and enhanced the 'description' value
  1019. *
  1020. * @param array $data the app data
  1021. * @param string $lang
  1022. * @return array improved app data
  1023. */
  1024. public static function parseAppInfo(array $data, $lang = null): array {
  1025. if ($lang && isset($data['name']) && is_array($data['name'])) {
  1026. $data['name'] = self::findBestL10NOption($data['name'], $lang);
  1027. }
  1028. if ($lang && isset($data['summary']) && is_array($data['summary'])) {
  1029. $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
  1030. }
  1031. if ($lang && isset($data['description']) && is_array($data['description'])) {
  1032. $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
  1033. } elseif (isset($data['description']) && is_string($data['description'])) {
  1034. $data['description'] = trim($data['description']);
  1035. } else {
  1036. $data['description'] = '';
  1037. }
  1038. return $data;
  1039. }
  1040. /**
  1041. * @param \OCP\IConfig $config
  1042. * @param \OCP\IL10N $l
  1043. * @param array $info
  1044. * @throws \Exception
  1045. */
  1046. public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
  1047. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
  1048. $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
  1049. if (!empty($missing)) {
  1050. $missingMsg = implode(PHP_EOL, $missing);
  1051. throw new \Exception(
  1052. $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
  1053. [$info['name'], $missingMsg]
  1054. )
  1055. );
  1056. }
  1057. }
  1058. }