app.php 35 KB

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