app.php 31 KB

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