OC_App.php 36 KB

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