app.php 32 KB

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