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.

OC_App.php 36KB

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