app.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Borjan Tchakaloff <borjan@tchakaloff.fr>
  10. * @author Brice Maron <brice@bmaron.net>
  11. * @author Christopher Schäpers <kondou@ts.unde.re>
  12. * @author Felix Moeller <mail@felixmoeller.de>
  13. * @author Frank Karlitschek <frank@karlitschek.de>
  14. * @author Georg Ehrke <georg@owncloud.com>
  15. * @author Jakob Sack <mail@jakobsack.de>
  16. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  17. * @author Joas Schilling <coding@schilljs.com>
  18. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  19. * @author Kamil Domanski <kdomanski@kdemail.net>
  20. * @author Klaas Freitag <freitag@owncloud.com>
  21. * @author Lukas Reschke <lukas@statuscode.ch>
  22. * @author Markus Goetz <markus@woboq.com>
  23. * @author Morris Jobke <hey@morrisjobke.de>
  24. * @author RealRancor <Fisch.666@gmx.de>
  25. * @author Robin Appelman <robin@icewind.nl>
  26. * @author Robin McCorkell <robin@mccorkell.me.uk>
  27. * @author Roeland Jago Douma <roeland@famdouma.nl>
  28. * @author Sam Tuke <mail@samtuke.com>
  29. * @author Thomas Müller <thomas.mueller@tmit.eu>
  30. * @author Thomas Tanghus <thomas@tanghus.net>
  31. * @author Tom Needham <tom@owncloud.com>
  32. * @author Vincent Petry <pvince81@owncloud.com>
  33. *
  34. * @license AGPL-3.0
  35. *
  36. * This code is free software: you can redistribute it and/or modify
  37. * it under the terms of the GNU Affero General Public License, version 3,
  38. * as published by the Free Software Foundation.
  39. *
  40. * This program is distributed in the hope that it will be useful,
  41. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  42. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  43. * GNU Affero General Public License for more details.
  44. *
  45. * You should have received a copy of the GNU Affero General Public License, version 3,
  46. * along with this program. If not, see <http://www.gnu.org/licenses/>
  47. *
  48. */
  49. use OC\App\DependencyAnalyzer;
  50. use OC\App\Platform;
  51. use OC\Installer;
  52. use OC\OCSClient;
  53. use OC\Repair;
  54. use OCP\App\ManagerEvent;
  55. /**
  56. * This class manages the apps. It allows them to register and integrate in the
  57. * ownCloud ecosystem. Furthermore, this class is responsible for installing,
  58. * upgrading and removing apps.
  59. */
  60. class OC_App {
  61. static private $appVersion = [];
  62. static private $adminForms = array();
  63. static private $personalForms = array();
  64. static private $appInfo = array();
  65. static private $appTypes = array();
  66. static private $loadedApps = array();
  67. static private $altLogin = array();
  68. static private $alreadyRegistered = [];
  69. const officialApp = 200;
  70. /**
  71. * clean the appId
  72. *
  73. * @param string|boolean $app AppId that needs to be cleaned
  74. * @return string
  75. */
  76. public static function cleanAppId($app) {
  77. return str_replace(array('\0', '/', '\\', '..'), '', $app);
  78. }
  79. /**
  80. * Check if an app is loaded
  81. *
  82. * @param string $app
  83. * @return bool
  84. */
  85. public static function isAppLoaded($app) {
  86. return in_array($app, self::$loadedApps, true);
  87. }
  88. /**
  89. * loads all apps
  90. *
  91. * @param string[] | string | null $types
  92. * @return bool
  93. *
  94. * This function walks through the ownCloud directory and loads all apps
  95. * it can find. A directory contains an app if the file /appinfo/info.xml
  96. * exists.
  97. *
  98. * if $types is set, only apps of those types will be loaded
  99. */
  100. public static function loadApps($types = null) {
  101. if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
  102. return false;
  103. }
  104. // Load the enabled apps here
  105. $apps = self::getEnabledApps();
  106. // Add each apps' folder as allowed class path
  107. foreach($apps as $app) {
  108. $path = self::getAppPath($app);
  109. if($path !== false) {
  110. self::registerAutoloading($app, $path);
  111. }
  112. }
  113. // prevent app.php from printing output
  114. ob_start();
  115. foreach ($apps as $app) {
  116. if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
  117. self::loadApp($app);
  118. }
  119. }
  120. ob_end_clean();
  121. return true;
  122. }
  123. /**
  124. * load a single app
  125. *
  126. * @param string $app
  127. * @param bool $checkUpgrade whether an upgrade check should be done
  128. * @throws \OC\NeedsUpdateException
  129. */
  130. public static function loadApp($app, $checkUpgrade = true) {
  131. self::$loadedApps[] = $app;
  132. $appPath = self::getAppPath($app);
  133. if($appPath === false) {
  134. return;
  135. }
  136. // in case someone calls loadApp() directly
  137. self::registerAutoloading($app, $appPath);
  138. if (is_file($appPath . '/appinfo/app.php')) {
  139. \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
  140. if ($checkUpgrade and self::shouldUpgrade($app)) {
  141. throw new \OC\NeedsUpdateException();
  142. }
  143. self::requireAppFile($app);
  144. if (self::isType($app, array('authentication'))) {
  145. // since authentication apps affect the "is app enabled for group" check,
  146. // the enabled apps cache needs to be cleared to make sure that the
  147. // next time getEnableApps() is called it will also include apps that were
  148. // enabled for groups
  149. self::$enabledAppsCache = array();
  150. }
  151. \OC::$server->getEventLogger()->end('load_app_' . $app);
  152. }
  153. }
  154. /**
  155. * @internal
  156. * @param string $app
  157. * @param string $path
  158. */
  159. public static function registerAutoloading($app, $path) {
  160. $key = $app . '-' . $path;
  161. if(isset(self::$alreadyRegistered[$key])) {
  162. return;
  163. }
  164. self::$alreadyRegistered[$key] = true;
  165. // Register on PSR-4 composer autoloader
  166. $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
  167. \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
  168. if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
  169. \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
  170. }
  171. // Register on legacy autoloader
  172. \OC::$loader->addValidRoot($path);
  173. }
  174. /**
  175. * Load app.php from the given app
  176. *
  177. * @param string $app app name
  178. */
  179. private static function requireAppFile($app) {
  180. try {
  181. // encapsulated here to avoid variable scope conflicts
  182. require_once $app . '/appinfo/app.php';
  183. } catch (Error $ex) {
  184. \OC::$server->getLogger()->logException($ex);
  185. $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
  186. if (!in_array($app, $blacklist)) {
  187. self::disable($app);
  188. }
  189. }
  190. }
  191. /**
  192. * check if an app is of a specific type
  193. *
  194. * @param string $app
  195. * @param string|array $types
  196. * @return bool
  197. */
  198. public static function isType($app, $types) {
  199. if (is_string($types)) {
  200. $types = array($types);
  201. }
  202. $appTypes = self::getAppTypes($app);
  203. foreach ($types as $type) {
  204. if (array_search($type, $appTypes) !== false) {
  205. return true;
  206. }
  207. }
  208. return false;
  209. }
  210. /**
  211. * get the types of an app
  212. *
  213. * @param string $app
  214. * @return array
  215. */
  216. private static function getAppTypes($app) {
  217. //load the cache
  218. if (count(self::$appTypes) == 0) {
  219. self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
  220. }
  221. if (isset(self::$appTypes[$app])) {
  222. return explode(',', self::$appTypes[$app]);
  223. } else {
  224. return array();
  225. }
  226. }
  227. /**
  228. * read app types from info.xml and cache them in the database
  229. */
  230. public static function setAppTypes($app) {
  231. $appData = self::getAppInfo($app);
  232. if(!is_array($appData)) {
  233. return;
  234. }
  235. if (isset($appData['types'])) {
  236. $appTypes = implode(',', $appData['types']);
  237. } else {
  238. $appTypes = '';
  239. }
  240. \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
  241. }
  242. /**
  243. * check if app is shipped
  244. *
  245. * @param string $appId the id of the app to check
  246. * @return bool
  247. *
  248. * Check if an app that is installed is a shipped app or installed from the appstore.
  249. */
  250. public static function isShipped($appId) {
  251. return \OC::$server->getAppManager()->isShipped($appId);
  252. }
  253. /**
  254. * get all enabled apps
  255. */
  256. protected static $enabledAppsCache = array();
  257. /**
  258. * Returns apps enabled for the current user.
  259. *
  260. * @param bool $forceRefresh whether to refresh the cache
  261. * @param bool $all whether to return apps for all users, not only the
  262. * currently logged in one
  263. * @return string[]
  264. */
  265. public static function getEnabledApps($forceRefresh = false, $all = false) {
  266. if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
  267. return array();
  268. }
  269. // in incognito mode or when logged out, $user will be false,
  270. // which is also the case during an upgrade
  271. $appManager = \OC::$server->getAppManager();
  272. if ($all) {
  273. $user = null;
  274. } else {
  275. $user = \OC::$server->getUserSession()->getUser();
  276. }
  277. if (is_null($user)) {
  278. $apps = $appManager->getInstalledApps();
  279. } else {
  280. $apps = $appManager->getEnabledAppsForUser($user);
  281. }
  282. $apps = array_filter($apps, function ($app) {
  283. return $app !== 'files';//we add this manually
  284. });
  285. sort($apps);
  286. array_unshift($apps, 'files');
  287. return $apps;
  288. }
  289. /**
  290. * checks whether or not an app is enabled
  291. *
  292. * @param string $app app
  293. * @return bool
  294. *
  295. * This function checks whether or not an app is enabled.
  296. */
  297. public static function isEnabled($app) {
  298. return \OC::$server->getAppManager()->isEnabledForUser($app);
  299. }
  300. /**
  301. * enables an app
  302. *
  303. * @param mixed $app app
  304. * @param array $groups (optional) when set, only these groups will have access to the app
  305. * @throws \Exception
  306. * @return void
  307. *
  308. * This function set an app as enabled in appconfig.
  309. */
  310. public static function enable($app, $groups = null) {
  311. self::$enabledAppsCache = array(); // flush
  312. if (!Installer::isInstalled($app)) {
  313. $app = self::installApp($app);
  314. }
  315. $appManager = \OC::$server->getAppManager();
  316. if (!is_null($groups)) {
  317. $groupManager = \OC::$server->getGroupManager();
  318. $groupsList = [];
  319. foreach ($groups as $group) {
  320. $groupItem = $groupManager->get($group);
  321. if ($groupItem instanceof \OCP\IGroup) {
  322. $groupsList[] = $groupManager->get($group);
  323. }
  324. }
  325. $appManager->enableAppForGroups($app, $groupsList);
  326. } else {
  327. $appManager->enableApp($app);
  328. }
  329. $info = self::getAppInfo($app);
  330. if(isset($info['settings']) && is_array($info['settings'])) {
  331. $appPath = self::getAppPath($app);
  332. self::registerAutoloading($app, $appPath);
  333. \OC::$server->getSettingsManager()->setupSettings($info['settings']);
  334. }
  335. }
  336. /**
  337. * @param string $app
  338. * @return int
  339. */
  340. private static function downloadApp($app) {
  341. $ocsClient = new OCSClient(
  342. \OC::$server->getHTTPClientService(),
  343. \OC::$server->getConfig(),
  344. \OC::$server->getLogger()
  345. );
  346. $appData = $ocsClient->getApplication($app, \OCP\Util::getVersion());
  347. $download = $ocsClient->getApplicationDownload($app, \OCP\Util::getVersion());
  348. if(isset($download['downloadlink']) and $download['downloadlink']!='') {
  349. // Replace spaces in download link without encoding entire URL
  350. $download['downloadlink'] = str_replace(' ', '%20', $download['downloadlink']);
  351. $info = array('source' => 'http', 'href' => $download['downloadlink'], 'appdata' => $appData);
  352. $app = Installer::installApp($info);
  353. }
  354. return $app;
  355. }
  356. /**
  357. * @param string $app
  358. * @return bool
  359. */
  360. public static function removeApp($app) {
  361. if (self::isShipped($app)) {
  362. return false;
  363. }
  364. return Installer::removeApp($app);
  365. }
  366. /**
  367. * This function set an app as disabled in appconfig.
  368. *
  369. * @param string $app app
  370. * @throws Exception
  371. */
  372. public static function disable($app) {
  373. // Convert OCS ID to regular application identifier
  374. if(self::getInternalAppIdByOcs($app) !== false) {
  375. $app = self::getInternalAppIdByOcs($app);
  376. }
  377. // flush
  378. self::$enabledAppsCache = array();
  379. // run uninstall steps
  380. $appData = OC_App::getAppInfo($app);
  381. if (!is_null($appData)) {
  382. OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
  383. }
  384. // emit disable hook - needed anymore ?
  385. \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
  386. // finally disable it
  387. $appManager = \OC::$server->getAppManager();
  388. $appManager->disableApp($app);
  389. }
  390. /**
  391. * Returns the Settings Navigation
  392. *
  393. * @return string[]
  394. *
  395. * This function returns an array containing all settings pages added. The
  396. * entries are sorted by the key 'order' ascending.
  397. */
  398. public static function getSettingsNavigation() {
  399. $l = \OC::$server->getL10N('lib');
  400. $urlGenerator = \OC::$server->getURLGenerator();
  401. $settings = array();
  402. // by default, settings only contain the help menu
  403. if (\OC::$server->getSystemConfig()->getValue('knowledgebaseenabled', true)) {
  404. $settings = array(
  405. array(
  406. "id" => "help",
  407. "order" => 4,
  408. "href" => $urlGenerator->linkToRoute('settings_help'),
  409. "name" => $l->t("Help"),
  410. "icon" => $urlGenerator->imagePath("settings", "help.svg")
  411. )
  412. );
  413. }
  414. // if the user is logged-in
  415. if (OC_User::isLoggedIn()) {
  416. // personal menu
  417. $settings[] = array(
  418. "id" => "personal",
  419. "order" => 1,
  420. "href" => $urlGenerator->linkToRoute('settings_personal'),
  421. "name" => $l->t("Personal"),
  422. "icon" => $urlGenerator->imagePath("settings", "personal.svg")
  423. );
  424. //SubAdmins are also allowed to access user management
  425. $userObject = \OC::$server->getUserSession()->getUser();
  426. $isSubAdmin = false;
  427. if($userObject !== null) {
  428. $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
  429. }
  430. if ($isSubAdmin) {
  431. // admin users menu
  432. $settings[] = array(
  433. "id" => "core_users",
  434. "order" => 3,
  435. "href" => $urlGenerator->linkToRoute('settings_users'),
  436. "name" => $l->t("Users"),
  437. "icon" => $urlGenerator->imagePath("settings", "users.svg")
  438. );
  439. }
  440. // if the user is an admin
  441. if (OC_User::isAdminUser(OC_User::getUser())) {
  442. // admin settings
  443. $settings[] = array(
  444. "id" => "admin",
  445. "order" => 2,
  446. "href" => $urlGenerator->linkToRoute('settings.AdminSettings.index'),
  447. "name" => $l->t("Admin"),
  448. "icon" => $urlGenerator->imagePath("settings", "admin.svg")
  449. );
  450. }
  451. }
  452. $navigation = self::proceedNavigation($settings);
  453. return $navigation;
  454. }
  455. // This is private as well. It simply works, so don't ask for more details
  456. private static function proceedNavigation($list) {
  457. $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
  458. foreach ($list as &$navEntry) {
  459. if ($navEntry['id'] == $activeApp) {
  460. $navEntry['active'] = true;
  461. } else {
  462. $navEntry['active'] = false;
  463. }
  464. }
  465. unset($navEntry);
  466. usort($list, function($a, $b) {
  467. if (isset($a['order']) && isset($b['order'])) {
  468. return ($a['order'] < $b['order']) ? -1 : 1;
  469. } else if (isset($a['order']) || isset($b['order'])) {
  470. return isset($a['order']) ? -1 : 1;
  471. } else {
  472. return ($a['name'] < $b['name']) ? -1 : 1;
  473. }
  474. });
  475. return $list;
  476. }
  477. /**
  478. * Get the path where to install apps
  479. *
  480. * @return string|false
  481. */
  482. public static function getInstallPath() {
  483. if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
  484. return false;
  485. }
  486. foreach (OC::$APPSROOTS as $dir) {
  487. if (isset($dir['writable']) && $dir['writable'] === true) {
  488. return $dir['path'];
  489. }
  490. }
  491. \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
  492. return null;
  493. }
  494. /**
  495. * search for an app in all app-directories
  496. *
  497. * @param string $appId
  498. * @return false|string
  499. */
  500. protected static function findAppInDirectories($appId) {
  501. $sanitizedAppId = self::cleanAppId($appId);
  502. if($sanitizedAppId !== $appId) {
  503. return false;
  504. }
  505. static $app_dir = array();
  506. if (isset($app_dir[$appId])) {
  507. return $app_dir[$appId];
  508. }
  509. $possibleApps = array();
  510. foreach (OC::$APPSROOTS as $dir) {
  511. if (file_exists($dir['path'] . '/' . $appId)) {
  512. $possibleApps[] = $dir;
  513. }
  514. }
  515. if (empty($possibleApps)) {
  516. return false;
  517. } elseif (count($possibleApps) === 1) {
  518. $dir = array_shift($possibleApps);
  519. $app_dir[$appId] = $dir;
  520. return $dir;
  521. } else {
  522. $versionToLoad = array();
  523. foreach ($possibleApps as $possibleApp) {
  524. $version = self::getAppVersionByPath($possibleApp['path']);
  525. if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
  526. $versionToLoad = array(
  527. 'dir' => $possibleApp,
  528. 'version' => $version,
  529. );
  530. }
  531. }
  532. $app_dir[$appId] = $versionToLoad['dir'];
  533. return $versionToLoad['dir'];
  534. //TODO - write test
  535. }
  536. }
  537. /**
  538. * Get the directory for the given app.
  539. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  540. *
  541. * @param string $appId
  542. * @return string|false
  543. */
  544. public static function getAppPath($appId) {
  545. if ($appId === null || trim($appId) === '') {
  546. return false;
  547. }
  548. if (($dir = self::findAppInDirectories($appId)) != false) {
  549. return $dir['path'] . '/' . $appId;
  550. }
  551. return false;
  552. }
  553. /**
  554. * check if an app's directory is writable
  555. *
  556. * @param string $appId
  557. * @return bool
  558. */
  559. public static function isAppDirWritable($appId) {
  560. $path = self::getAppPath($appId);
  561. return ($path !== false) ? is_writable($path) : false;
  562. }
  563. /**
  564. * Get the path for the given app on the access
  565. * If the app is defined in multiple directories, the first one is taken. (false if not found)
  566. *
  567. * @param string $appId
  568. * @return string|false
  569. */
  570. public static function getAppWebPath($appId) {
  571. if (($dir = self::findAppInDirectories($appId)) != false) {
  572. return OC::$WEBROOT . $dir['url'] . '/' . $appId;
  573. }
  574. return false;
  575. }
  576. /**
  577. * get the last version of the app from appinfo/info.xml
  578. *
  579. * @param string $appId
  580. * @return string
  581. */
  582. public static function getAppVersion($appId) {
  583. if (!isset(self::$appVersion[$appId])) {
  584. $file = self::getAppPath($appId);
  585. self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
  586. }
  587. return self::$appVersion[$appId];
  588. }
  589. /**
  590. * get app's version based on it's path
  591. *
  592. * @param string $path
  593. * @return string
  594. */
  595. public static function getAppVersionByPath($path) {
  596. $infoFile = $path . '/appinfo/info.xml';
  597. $appData = self::getAppInfo($infoFile, true);
  598. return isset($appData['version']) ? $appData['version'] : '';
  599. }
  600. /**
  601. * Read all app metadata from the info.xml file
  602. *
  603. * @param string $appId id of the app or the path of the info.xml file
  604. * @param boolean $path (optional)
  605. * @return array|null
  606. * @note all data is read from info.xml, not just pre-defined fields
  607. */
  608. public static function getAppInfo($appId, $path = false) {
  609. if ($path) {
  610. $file = $appId;
  611. } else {
  612. if (isset(self::$appInfo[$appId])) {
  613. return self::$appInfo[$appId];
  614. }
  615. $appPath = self::getAppPath($appId);
  616. if($appPath === false) {
  617. return null;
  618. }
  619. $file = $appPath . '/appinfo/info.xml';
  620. }
  621. $parser = new \OC\App\InfoParser(\OC::$server->getURLGenerator());
  622. $data = $parser->parse($file);
  623. if (is_array($data)) {
  624. $data = OC_App::parseAppInfo($data);
  625. }
  626. if(isset($data['ocsid'])) {
  627. $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
  628. if($storedId !== '' && $storedId !== $data['ocsid']) {
  629. $data['ocsid'] = $storedId;
  630. }
  631. }
  632. self::$appInfo[$appId] = $data;
  633. return $data;
  634. }
  635. /**
  636. * Returns the navigation
  637. *
  638. * @return array
  639. *
  640. * This function returns an array containing all entries added. The
  641. * entries are sorted by the key 'order' ascending. Additional to the keys
  642. * given for each app the following keys exist:
  643. * - active: boolean, signals if the user is on this navigation entry
  644. */
  645. public static function getNavigation() {
  646. $entries = OC::$server->getNavigationManager()->getAll();
  647. $navigation = self::proceedNavigation($entries);
  648. return $navigation;
  649. }
  650. /**
  651. * get the id of loaded app
  652. *
  653. * @return string
  654. */
  655. public static function getCurrentApp() {
  656. $request = \OC::$server->getRequest();
  657. $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
  658. $topFolder = substr($script, 0, strpos($script, '/'));
  659. if (empty($topFolder)) {
  660. $path_info = $request->getPathInfo();
  661. if ($path_info) {
  662. $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
  663. }
  664. }
  665. if ($topFolder == 'apps') {
  666. $length = strlen($topFolder);
  667. return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
  668. } else {
  669. return $topFolder;
  670. }
  671. }
  672. /**
  673. * @param string $type
  674. * @return array
  675. */
  676. public static function getForms($type) {
  677. $forms = array();
  678. switch ($type) {
  679. case 'admin':
  680. $source = self::$adminForms;
  681. break;
  682. case 'personal':
  683. $source = self::$personalForms;
  684. break;
  685. default:
  686. return array();
  687. }
  688. foreach ($source as $form) {
  689. $forms[] = include $form;
  690. }
  691. return $forms;
  692. }
  693. /**
  694. * register an admin form to be shown
  695. *
  696. * @param string $app
  697. * @param string $page
  698. */
  699. public static function registerAdmin($app, $page) {
  700. self::$adminForms[] = $app . '/' . $page . '.php';
  701. }
  702. /**
  703. * register a personal form to be shown
  704. * @param string $app
  705. * @param string $page
  706. */
  707. public static function registerPersonal($app, $page) {
  708. self::$personalForms[] = $app . '/' . $page . '.php';
  709. }
  710. /**
  711. * @param array $entry
  712. */
  713. public static function registerLogIn(array $entry) {
  714. self::$altLogin[] = $entry;
  715. }
  716. /**
  717. * @return array
  718. */
  719. public static function getAlternativeLogIns() {
  720. return self::$altLogin;
  721. }
  722. /**
  723. * get a list of all apps in the apps folder
  724. *
  725. * @return array an array of app names (string IDs)
  726. * @todo: change the name of this method to getInstalledApps, which is more accurate
  727. */
  728. public static function getAllApps() {
  729. $apps = array();
  730. foreach (OC::$APPSROOTS as $apps_dir) {
  731. if (!is_readable($apps_dir['path'])) {
  732. \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
  733. continue;
  734. }
  735. $dh = opendir($apps_dir['path']);
  736. if (is_resource($dh)) {
  737. while (($file = readdir($dh)) !== false) {
  738. if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
  739. $apps[] = $file;
  740. }
  741. }
  742. }
  743. }
  744. return $apps;
  745. }
  746. /**
  747. * List all apps, this is used in apps.php
  748. *
  749. * @param bool $onlyLocal
  750. * @param bool $includeUpdateInfo Should we check whether there is an update
  751. * in the app store?
  752. * @param OCSClient $ocsClient
  753. * @return array
  754. */
  755. public static function listAllApps($onlyLocal = false,
  756. $includeUpdateInfo = true,
  757. OCSClient $ocsClient) {
  758. $installedApps = OC_App::getAllApps();
  759. //TODO which apps do we want to blacklist and how do we integrate
  760. // blacklisting with the multi apps folder feature?
  761. //we don't want to show configuration for these
  762. $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
  763. $appList = array();
  764. foreach ($installedApps as $app) {
  765. if (array_search($app, $blacklist) === false) {
  766. $info = OC_App::getAppInfo($app);
  767. if (!is_array($info)) {
  768. \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
  769. continue;
  770. }
  771. if (!isset($info['name'])) {
  772. \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
  773. continue;
  774. }
  775. $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
  776. $info['groups'] = null;
  777. if ($enabled === 'yes') {
  778. $active = true;
  779. } else if ($enabled === 'no') {
  780. $active = false;
  781. } else {
  782. $active = true;
  783. $info['groups'] = $enabled;
  784. }
  785. $info['active'] = $active;
  786. if (self::isShipped($app)) {
  787. $info['internal'] = true;
  788. $info['level'] = self::officialApp;
  789. $info['removable'] = false;
  790. } else {
  791. $info['internal'] = false;
  792. $info['removable'] = true;
  793. }
  794. $info['update'] = ($includeUpdateInfo) ? Installer::isUpdateAvailable($app) : null;
  795. $appPath = self::getAppPath($app);
  796. if($appPath !== false) {
  797. $appIcon = $appPath . '/img/' . $app . '.svg';
  798. if (file_exists($appIcon)) {
  799. $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
  800. $info['previewAsIcon'] = true;
  801. } else {
  802. $appIcon = $appPath . '/img/app.svg';
  803. if (file_exists($appIcon)) {
  804. $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
  805. $info['previewAsIcon'] = true;
  806. }
  807. }
  808. }
  809. $info['version'] = OC_App::getAppVersion($app);
  810. $appList[] = $info;
  811. }
  812. }
  813. if ($onlyLocal) {
  814. $remoteApps = [];
  815. } else {
  816. $remoteApps = OC_App::getAppstoreApps('approved', null, $ocsClient);
  817. }
  818. if ($remoteApps) {
  819. // Remove duplicates
  820. foreach ($appList as $app) {
  821. foreach ($remoteApps AS $key => $remote) {
  822. if ($app['name'] === $remote['name'] ||
  823. (isset($app['ocsid']) &&
  824. $app['ocsid'] === $remote['id'])
  825. ) {
  826. unset($remoteApps[$key]);
  827. }
  828. }
  829. }
  830. $combinedApps = array_merge($appList, $remoteApps);
  831. } else {
  832. $combinedApps = $appList;
  833. }
  834. return $combinedApps;
  835. }
  836. /**
  837. * Returns the internal app ID or false
  838. * @param string $ocsID
  839. * @return string|false
  840. */
  841. public static function getInternalAppIdByOcs($ocsID) {
  842. if(is_numeric($ocsID)) {
  843. $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
  844. if(array_search($ocsID, $idArray)) {
  845. return array_search($ocsID, $idArray);
  846. }
  847. }
  848. return false;
  849. }
  850. /**
  851. * Get a list of all apps on the appstore
  852. * @param string $filter
  853. * @param string|null $category
  854. * @param OCSClient $ocsClient
  855. * @return array|bool multi-dimensional array of apps.
  856. * Keys: id, name, type, typename, personid, license, detailpage, preview, changed, description
  857. */
  858. public static function getAppstoreApps($filter = 'approved',
  859. $category = null,
  860. OCSClient $ocsClient) {
  861. $categories = [$category];
  862. if (is_null($category)) {
  863. $categoryNames = $ocsClient->getCategories(\OCP\Util::getVersion());
  864. if (is_array($categoryNames)) {
  865. // Check that categories of apps were retrieved correctly
  866. if (!$categories = array_keys($categoryNames)) {
  867. return false;
  868. }
  869. } else {
  870. return false;
  871. }
  872. }
  873. $page = 0;
  874. $remoteApps = $ocsClient->getApplications($categories, $page, $filter, \OCP\Util::getVersion());
  875. $apps = [];
  876. $i = 0;
  877. $l = \OC::$server->getL10N('core');
  878. foreach ($remoteApps as $app) {
  879. $potentialCleanId = self::getInternalAppIdByOcs($app['id']);
  880. // enhance app info (for example the description)
  881. $apps[$i] = OC_App::parseAppInfo($app);
  882. $apps[$i]['author'] = $app['personid'];
  883. $apps[$i]['ocs_id'] = $app['id'];
  884. $apps[$i]['internal'] = 0;
  885. $apps[$i]['active'] = ($potentialCleanId !== false) ? self::isEnabled($potentialCleanId) : false;
  886. $apps[$i]['update'] = false;
  887. $apps[$i]['groups'] = false;
  888. $apps[$i]['score'] = $app['score'];
  889. $apps[$i]['removable'] = false;
  890. if ($app['label'] == 'recommended') {
  891. $apps[$i]['internallabel'] = (string)$l->t('Recommended');
  892. $apps[$i]['internalclass'] = 'recommendedapp';
  893. }
  894. // Apps from the appstore are always assumed to be compatible with the
  895. // the current release as the initial filtering is done on the appstore
  896. $apps[$i]['dependencies']['owncloud']['@attributes']['min-version'] = implode('.', \OCP\Util::getVersion());
  897. $apps[$i]['dependencies']['owncloud']['@attributes']['max-version'] = implode('.', \OCP\Util::getVersion());
  898. $i++;
  899. }
  900. if (empty($apps)) {
  901. return false;
  902. } else {
  903. return $apps;
  904. }
  905. }
  906. public static function shouldUpgrade($app) {
  907. $versions = self::getAppVersions();
  908. $currentVersion = OC_App::getAppVersion($app);
  909. if ($currentVersion && isset($versions[$app])) {
  910. $installedVersion = $versions[$app];
  911. if (!version_compare($currentVersion, $installedVersion, '=')) {
  912. return true;
  913. }
  914. }
  915. return false;
  916. }
  917. /**
  918. * Adjust the number of version parts of $version1 to match
  919. * the number of version parts of $version2.
  920. *
  921. * @param string $version1 version to adjust
  922. * @param string $version2 version to take the number of parts from
  923. * @return string shortened $version1
  924. */
  925. private static function adjustVersionParts($version1, $version2) {
  926. $version1 = explode('.', $version1);
  927. $version2 = explode('.', $version2);
  928. // reduce $version1 to match the number of parts in $version2
  929. while (count($version1) > count($version2)) {
  930. array_pop($version1);
  931. }
  932. // if $version1 does not have enough parts, add some
  933. while (count($version1) < count($version2)) {
  934. $version1[] = '0';
  935. }
  936. return implode('.', $version1);
  937. }
  938. /**
  939. * Check whether the current ownCloud version matches the given
  940. * application's version requirements.
  941. *
  942. * The comparison is made based on the number of parts that the
  943. * app info version has. For example for ownCloud 6.0.3 if the
  944. * app info version is expecting version 6.0, the comparison is
  945. * made on the first two parts of the ownCloud version.
  946. * This means that it's possible to specify "requiremin" => 6
  947. * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
  948. *
  949. * @param string $ocVersion ownCloud version to check against
  950. * @param array $appInfo app info (from xml)
  951. *
  952. * @return boolean true if compatible, otherwise false
  953. */
  954. public static function isAppCompatible($ocVersion, $appInfo) {
  955. $requireMin = '';
  956. $requireMax = '';
  957. if (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
  958. $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
  959. } else if (isset($appInfo['requiremin'])) {
  960. $requireMin = $appInfo['requiremin'];
  961. } else if (isset($appInfo['require'])) {
  962. $requireMin = $appInfo['require'];
  963. }
  964. if (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
  965. $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
  966. } else if (isset($appInfo['requiremax'])) {
  967. $requireMax = $appInfo['requiremax'];
  968. }
  969. if (is_array($ocVersion)) {
  970. $ocVersion = implode('.', $ocVersion);
  971. }
  972. if (!empty($requireMin)
  973. && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
  974. ) {
  975. return false;
  976. }
  977. if (!empty($requireMax)
  978. && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
  979. ) {
  980. return false;
  981. }
  982. return true;
  983. }
  984. /**
  985. * get the installed version of all apps
  986. */
  987. public static function getAppVersions() {
  988. static $versions;
  989. if(!$versions) {
  990. $appConfig = \OC::$server->getAppConfig();
  991. $versions = $appConfig->getValues(false, 'installed_version');
  992. }
  993. return $versions;
  994. }
  995. /**
  996. * @param string $app
  997. * @return bool
  998. * @throws Exception if app is not compatible with this version of ownCloud
  999. * @throws Exception if no app-name was specified
  1000. */
  1001. public static function installApp($app) {
  1002. $appName = $app; // $app will be overwritten, preserve name for error logging
  1003. $l = \OC::$server->getL10N('core');
  1004. $config = \OC::$server->getConfig();
  1005. $ocsClient = new OCSClient(
  1006. \OC::$server->getHTTPClientService(),
  1007. $config,
  1008. \OC::$server->getLogger()
  1009. );
  1010. $appData = $ocsClient->getApplication($app, \OCP\Util::getVersion());
  1011. // check if app is a shipped app or not. OCS apps have an integer as id, shipped apps use a string
  1012. if (!is_numeric($app)) {
  1013. $shippedVersion = self::getAppVersion($app);
  1014. if ($appData && version_compare($shippedVersion, $appData['version'], '<')) {
  1015. $app = self::downloadApp($app);
  1016. } else {
  1017. $app = Installer::installShippedApp($app);
  1018. }
  1019. } else {
  1020. // Maybe the app is already installed - compare the version in this
  1021. // case and use the local already installed one.
  1022. // FIXME: This is a horrible hack. I feel sad. The god of code cleanness may forgive me.
  1023. $internalAppId = self::getInternalAppIdByOcs($app);
  1024. if($internalAppId !== false) {
  1025. if($appData && version_compare(\OC_App::getAppVersion($internalAppId), $appData['version'], '<')) {
  1026. $app = self::downloadApp($app);
  1027. } else {
  1028. self::enable($internalAppId);
  1029. $app = $internalAppId;
  1030. }
  1031. } else {
  1032. $app = self::downloadApp($app);
  1033. }
  1034. }
  1035. if ($app !== false) {
  1036. // check if the app is compatible with this version of ownCloud
  1037. $info = self::getAppInfo($app);
  1038. if(!is_array($info)) {
  1039. throw new \Exception(
  1040. $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
  1041. [$info['name']]
  1042. )
  1043. );
  1044. }
  1045. $version = \OCP\Util::getVersion();
  1046. if (!self::isAppCompatible($version, $info)) {
  1047. throw new \Exception(
  1048. $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
  1049. array($info['name'])
  1050. )
  1051. );
  1052. }
  1053. // check for required dependencies
  1054. $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
  1055. $missing = $dependencyAnalyzer->analyze($info);
  1056. if (!empty($missing)) {
  1057. $missingMsg = join(PHP_EOL, $missing);
  1058. throw new \Exception(
  1059. $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
  1060. array($info['name'], $missingMsg)
  1061. )
  1062. );
  1063. }
  1064. $config->setAppValue($app, 'enabled', 'yes');
  1065. if (isset($appData['id'])) {
  1066. $config->setAppValue($app, 'ocsid', $appData['id']);
  1067. }
  1068. if(isset($info['settings']) && is_array($info['settings'])) {
  1069. $appPath = self::getAppPath($app);
  1070. self::registerAutoloading($app, $appPath);
  1071. \OC::$server->getSettingsManager()->setupSettings($info['settings']);
  1072. }
  1073. \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
  1074. } else {
  1075. if(empty($appName) ) {
  1076. throw new \Exception($l->t("No app name specified"));
  1077. } else {
  1078. throw new \Exception($l->t("App '%s' could not be installed!", $appName));
  1079. }
  1080. }
  1081. return $app;
  1082. }
  1083. /**
  1084. * update the database for the app and call the update script
  1085. *
  1086. * @param string $appId
  1087. * @return bool
  1088. */
  1089. public static function updateApp($appId) {
  1090. $appPath = self::getAppPath($appId);
  1091. if($appPath === false) {
  1092. return false;
  1093. }
  1094. $appData = self::getAppInfo($appId);
  1095. self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
  1096. if (file_exists($appPath . '/appinfo/database.xml')) {
  1097. OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
  1098. }
  1099. self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
  1100. self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
  1101. unset(self::$appVersion[$appId]);
  1102. // run upgrade code
  1103. if (file_exists($appPath . '/appinfo/update.php')) {
  1104. self::loadApp($appId, false);
  1105. include $appPath . '/appinfo/update.php';
  1106. }
  1107. self::setupBackgroundJobs($appData['background-jobs']);
  1108. if(isset($appData['settings']) && is_array($appData['settings'])) {
  1109. $appPath = self::getAppPath($appId);
  1110. self::registerAutoloading($appId, $appPath);
  1111. \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
  1112. }
  1113. //set remote/public handlers
  1114. if (array_key_exists('ocsid', $appData)) {
  1115. \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
  1116. } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
  1117. \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
  1118. }
  1119. foreach ($appData['remote'] as $name => $path) {
  1120. \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
  1121. }
  1122. foreach ($appData['public'] as $name => $path) {
  1123. \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
  1124. }
  1125. self::setAppTypes($appId);
  1126. $version = \OC_App::getAppVersion($appId);
  1127. \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
  1128. \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
  1129. ManagerEvent::EVENT_APP_UPDATE, $appId
  1130. ));
  1131. return true;
  1132. }
  1133. /**
  1134. * @param string $appId
  1135. * @param string[] $steps
  1136. * @throws \OC\NeedsUpdateException
  1137. */
  1138. public static function executeRepairSteps($appId, array $steps) {
  1139. if (empty($steps)) {
  1140. return;
  1141. }
  1142. // load the app
  1143. self::loadApp($appId, false);
  1144. $dispatcher = OC::$server->getEventDispatcher();
  1145. // load the steps
  1146. $r = new Repair([], $dispatcher);
  1147. foreach ($steps as $step) {
  1148. try {
  1149. $r->addStep($step);
  1150. } catch (Exception $ex) {
  1151. $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
  1152. \OC::$server->getLogger()->logException($ex);
  1153. }
  1154. }
  1155. // run the steps
  1156. $r->run();
  1157. }
  1158. public static function setupBackgroundJobs(array $jobs) {
  1159. $queue = \OC::$server->getJobList();
  1160. foreach ($jobs as $job) {
  1161. $queue->add($job);
  1162. }
  1163. }
  1164. /**
  1165. * @param string $appId
  1166. * @param string[] $steps
  1167. */
  1168. private static function setupLiveMigrations($appId, array $steps) {
  1169. $queue = \OC::$server->getJobList();
  1170. foreach ($steps as $step) {
  1171. $queue->add('OC\Migration\BackgroundRepair', [
  1172. 'app' => $appId,
  1173. 'step' => $step]);
  1174. }
  1175. }
  1176. /**
  1177. * @param string $appId
  1178. * @return \OC\Files\View|false
  1179. */
  1180. public static function getStorage($appId) {
  1181. if (OC_App::isEnabled($appId)) { //sanity check
  1182. if (OC_User::isLoggedIn()) {
  1183. $view = new \OC\Files\View('/' . OC_User::getUser());
  1184. if (!$view->file_exists($appId)) {
  1185. $view->mkdir($appId);
  1186. }
  1187. return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
  1188. } else {
  1189. \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
  1190. return false;
  1191. }
  1192. } else {
  1193. \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
  1194. return false;
  1195. }
  1196. }
  1197. /**
  1198. * parses the app data array and enhanced the 'description' value
  1199. *
  1200. * @param array $data the app data
  1201. * @return array improved app data
  1202. */
  1203. public static function parseAppInfo(array $data) {
  1204. // just modify the description if it is available
  1205. // otherwise this will create a $data element with an empty 'description'
  1206. if (isset($data['description'])) {
  1207. if (is_string($data['description'])) {
  1208. // sometimes the description contains line breaks and they are then also
  1209. // shown in this way in the app management which isn't wanted as HTML
  1210. // manages line breaks itself
  1211. // first of all we split on empty lines
  1212. $paragraphs = preg_split("!\n[[:space:]]*\n!mu", $data['description']);
  1213. $result = [];
  1214. foreach ($paragraphs as $value) {
  1215. // replace multiple whitespace (tabs, space, newlines) inside a paragraph
  1216. // with a single space - also trims whitespace
  1217. $result[] = trim(preg_replace('![[:space:]]+!mu', ' ', $value));
  1218. }
  1219. // join the single paragraphs with a empty line in between
  1220. $data['description'] = implode("\n\n", $result);
  1221. } else {
  1222. $data['description'] = '';
  1223. }
  1224. }
  1225. return $data;
  1226. }
  1227. }