1
0

app.php 31 KB

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