You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Installer.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 Brice Maron <brice@bmaron.net>
  8. * @author Christian Weiske <cweiske@cweiske.de>
  9. * @author Christopher Schäpers <kondou@ts.unde.re>
  10. * @author Frank Karlitschek <frank@karlitschek.de>
  11. * @author Georg Ehrke <georg@owncloud.com>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  15. * @author Kamil Domanski <kdomanski@kdemail.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author michag86 <micha_g@arcor.de>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author root <root@oc.(none)>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Thomas Tanghus <thomas@tanghus.net>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OC;
  41. use OC\App\CodeChecker\CodeChecker;
  42. use OC\App\CodeChecker\EmptyCheck;
  43. use OC\App\CodeChecker\PrivateCheck;
  44. use OC_App;
  45. use OC_DB;
  46. use OC_Helper;
  47. /**
  48. * This class provides the functionality needed to install, update and remove plugins/apps
  49. */
  50. class Installer {
  51. /**
  52. *
  53. * This function installs an app. All information needed are passed in the
  54. * associative array $data.
  55. * The following keys are required:
  56. * - source: string, can be "path" or "http"
  57. *
  58. * One of the following keys is required:
  59. * - path: path to the file containing the app
  60. * - href: link to the downloadable file containing the app
  61. *
  62. * The following keys are optional:
  63. * - pretend: boolean, if set true the system won't do anything
  64. * - noinstall: boolean, if true appinfo/install.php won't be loaded
  65. * - inactive: boolean, if set true the appconfig/app.sample.php won't be
  66. * renamed
  67. *
  68. * This function works as follows
  69. * -# fetching the file
  70. * -# unzipping it
  71. * -# check the code
  72. * -# installing the database at appinfo/database.xml
  73. * -# including appinfo/install.php
  74. * -# setting the installed version
  75. *
  76. * It is the task of oc_app_install to create the tables and do whatever is
  77. * needed to get the app working.
  78. *
  79. * Installs an app
  80. * @param array $data with all information
  81. * @throws \Exception
  82. * @return integer
  83. */
  84. public static function installApp( $data = array()) {
  85. $l = \OC::$server->getL10N('lib');
  86. list($extractDir, $path) = self::downloadApp($data);
  87. $info = self::checkAppsIntegrity($data, $extractDir, $path);
  88. $appId = OC_App::cleanAppId($info['id']);
  89. $basedir = OC_App::getInstallPath().'/'.$appId;
  90. //check if the destination directory already exists
  91. if(is_dir($basedir)) {
  92. OC_Helper::rmdirr($extractDir);
  93. if($data['source']=='http') {
  94. unlink($path);
  95. }
  96. throw new \Exception($l->t("App directory already exists"));
  97. }
  98. if(!empty($data['pretent'])) {
  99. return false;
  100. }
  101. //copy the app to the correct place
  102. if(@!mkdir($basedir)) {
  103. OC_Helper::rmdirr($extractDir);
  104. if($data['source']=='http') {
  105. unlink($path);
  106. }
  107. throw new \Exception($l->t("Can't create app folder. Please fix permissions. %s", array($basedir)));
  108. }
  109. $extractDir .= '/' . $info['id'];
  110. if(!file_exists($extractDir)) {
  111. OC_Helper::rmdirr($basedir);
  112. throw new \Exception($l->t("Archive does not contain a directory named %s", $info['id']));
  113. }
  114. OC_Helper::copyr($extractDir, $basedir);
  115. //remove temporary files
  116. OC_Helper::rmdirr($extractDir);
  117. //install the database
  118. if(is_file($basedir.'/appinfo/database.xml')) {
  119. if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
  120. OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
  121. } else {
  122. OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
  123. }
  124. }
  125. \OC_App::setupBackgroundJobs($info['background-jobs']);
  126. //run appinfo/install.php
  127. if((!isset($data['noinstall']) or $data['noinstall']==false)) {
  128. self::includeAppScript($basedir . '/appinfo/install.php');
  129. }
  130. $appData = OC_App::getAppInfo($appId);
  131. OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
  132. //set the installed version
  133. \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id']));
  134. \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
  135. //set remote/public handlers
  136. foreach($info['remote'] as $name=>$path) {
  137. \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
  138. }
  139. foreach($info['public'] as $name=>$path) {
  140. \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
  141. }
  142. OC_App::setAppTypes($info['id']);
  143. return $info['id'];
  144. }
  145. /**
  146. * @brief checks whether or not an app is installed
  147. * @param string $app app
  148. * @returns bool
  149. *
  150. * Checks whether or not an app is installed, i.e. registered in apps table.
  151. */
  152. public static function isInstalled( $app ) {
  153. return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
  154. }
  155. /**
  156. * @brief Update an application
  157. * @param array $info
  158. * @param bool $isShipped
  159. * @throws \Exception
  160. * @return bool
  161. *
  162. * This function could work like described below, but currently it disables and then
  163. * enables the app again. This does result in an updated app.
  164. *
  165. *
  166. * This function installs an app. All information needed are passed in the
  167. * associative array $info.
  168. * The following keys are required:
  169. * - source: string, can be "path" or "http"
  170. *
  171. * One of the following keys is required:
  172. * - path: path to the file containing the app
  173. * - href: link to the downloadable file containing the app
  174. *
  175. * The following keys are optional:
  176. * - pretend: boolean, if set true the system won't do anything
  177. * - noupgrade: boolean, if true appinfo/upgrade.php won't be loaded
  178. *
  179. * This function works as follows
  180. * -# fetching the file
  181. * -# removing the old files
  182. * -# unzipping new file
  183. * -# including appinfo/upgrade.php
  184. * -# setting the installed version
  185. *
  186. * upgrade.php can determine the current installed version of the app using
  187. * "\OC::$server->getAppConfig()->getValue($appid, 'installed_version')"
  188. */
  189. public static function updateApp($info=array(), $isShipped=false) {
  190. list($extractDir, $path) = self::downloadApp($info);
  191. $info = self::checkAppsIntegrity($info, $extractDir, $path, $isShipped);
  192. $currentDir = OC_App::getAppPath($info['id']);
  193. $basedir = OC_App::getInstallPath();
  194. $basedir .= '/';
  195. $basedir .= $info['id'];
  196. if($currentDir !== false && is_writable($currentDir)) {
  197. $basedir = $currentDir;
  198. }
  199. if(is_dir($basedir)) {
  200. OC_Helper::rmdirr($basedir);
  201. }
  202. $appInExtractDir = $extractDir;
  203. if (substr($extractDir, -1) !== '/') {
  204. $appInExtractDir .= '/';
  205. }
  206. $appInExtractDir .= $info['id'];
  207. OC_Helper::copyr($appInExtractDir, $basedir);
  208. OC_Helper::rmdirr($extractDir);
  209. return OC_App::updateApp($info['id']);
  210. }
  211. /**
  212. * update an app by it's id
  213. *
  214. * @param integer $ocsId
  215. * @return bool
  216. * @throws \Exception
  217. */
  218. public static function updateAppByOCSId($ocsId) {
  219. $ocsClient = new OCSClient(
  220. \OC::$server->getHTTPClientService(),
  221. \OC::$server->getConfig(),
  222. \OC::$server->getLogger()
  223. );
  224. $appData = $ocsClient->getApplication($ocsId, \OCP\Util::getVersion());
  225. $download = $ocsClient->getApplicationDownload($ocsId, \OCP\Util::getVersion());
  226. if (isset($download['downloadlink']) && trim($download['downloadlink']) !== '') {
  227. $download['downloadlink'] = str_replace(' ', '%20', $download['downloadlink']);
  228. $info = array(
  229. 'source' => 'http',
  230. 'href' => $download['downloadlink'],
  231. 'appdata' => $appData
  232. );
  233. } else {
  234. throw new \Exception('Could not fetch app info!');
  235. }
  236. return self::updateApp($info);
  237. }
  238. /**
  239. * @param array $data
  240. * @return array
  241. * @throws \Exception
  242. */
  243. public static function downloadApp($data = array()) {
  244. $l = \OC::$server->getL10N('lib');
  245. if(!isset($data['source'])) {
  246. throw new \Exception($l->t("No source specified when installing app"));
  247. }
  248. //download the file if necessary
  249. if($data['source']=='http') {
  250. $pathInfo = pathinfo($data['href']);
  251. $extension = isset($pathInfo['extension']) ? '.' . $pathInfo['extension'] : '';
  252. $path = \OC::$server->getTempManager()->getTemporaryFile($extension);
  253. if(!isset($data['href'])) {
  254. throw new \Exception($l->t("No href specified when installing app from http"));
  255. }
  256. $client = \OC::$server->getHTTPClientService()->newClient();
  257. $client->get($data['href'], ['save_to' => $path]);
  258. } else {
  259. if(!isset($data['path'])) {
  260. throw new \Exception($l->t("No path specified when installing app from local file"));
  261. }
  262. $path=$data['path'];
  263. }
  264. //detect the archive type
  265. $mime = \OC::$server->getMimeTypeDetector()->detect($path);
  266. if ($mime !=='application/zip' && $mime !== 'application/x-gzip' && $mime !== 'application/x-bzip2') {
  267. throw new \Exception($l->t("Archives of type %s are not supported", array($mime)));
  268. }
  269. //extract the archive in a temporary folder
  270. $extractDir = \OC::$server->getTempManager()->getTemporaryFolder();
  271. OC_Helper::rmdirr($extractDir);
  272. mkdir($extractDir);
  273. if($archive=\OC\Archive\Archive::open($path)) {
  274. $archive->extract($extractDir);
  275. } else {
  276. OC_Helper::rmdirr($extractDir);
  277. if($data['source']=='http') {
  278. unlink($path);
  279. }
  280. throw new \Exception($l->t("Failed to open archive when installing app"));
  281. }
  282. return array(
  283. $extractDir,
  284. $path
  285. );
  286. }
  287. /**
  288. * check an app's integrity
  289. * @param array $data
  290. * @param string $extractDir
  291. * @param string $path
  292. * @param bool $isShipped
  293. * @return array
  294. * @throws \Exception
  295. */
  296. public static function checkAppsIntegrity($data, $extractDir, $path, $isShipped = false) {
  297. $l = \OC::$server->getL10N('lib');
  298. //load the info.xml file of the app
  299. if(!is_file($extractDir.'/appinfo/info.xml')) {
  300. //try to find it in a subdir
  301. $dh=opendir($extractDir);
  302. if(is_resource($dh)) {
  303. while (($folder = readdir($dh)) !== false) {
  304. if($folder[0]!='.' and is_dir($extractDir.'/'.$folder)) {
  305. if(is_file($extractDir.'/'.$folder.'/appinfo/info.xml')) {
  306. $extractDir.='/'.$folder;
  307. }
  308. }
  309. }
  310. }
  311. }
  312. if(!is_file($extractDir.'/appinfo/info.xml')) {
  313. OC_Helper::rmdirr($extractDir);
  314. if($data['source'] === 'http') {
  315. unlink($path);
  316. }
  317. throw new \Exception($l->t("App does not provide an info.xml file"));
  318. }
  319. $info = OC_App::getAppInfo($extractDir.'/appinfo/info.xml', true);
  320. if(!is_array($info)) {
  321. throw new \Exception($l->t('App cannot be installed because appinfo file cannot be read.'));
  322. }
  323. // We can't trust the parsed info.xml file as it may have been tampered
  324. // with by an attacker and thus we need to use the local data to check
  325. // whether the application needs to be signed.
  326. $appId = OC_App::cleanAppId($data['appdata']['id']);
  327. $appBelongingToId = OC_App::getInternalAppIdByOcs($appId);
  328. if(is_string($appBelongingToId)) {
  329. $previouslySigned = \OC::$server->getConfig()->getAppValue($appBelongingToId, 'signed', 'false');
  330. } else {
  331. $appBelongingToId = $info['id'];
  332. $previouslySigned = 'false';
  333. }
  334. if($data['appdata']['level'] === OC_App::officialApp || $previouslySigned === 'true') {
  335. \OC::$server->getConfig()->setAppValue($appBelongingToId, 'signed', 'true');
  336. $integrityResult = \OC::$server->getIntegrityCodeChecker()->verifyAppSignature(
  337. $appBelongingToId,
  338. $extractDir
  339. );
  340. if($integrityResult !== []) {
  341. $e = new \Exception(
  342. $l->t(
  343. 'Signature could not get checked. Please contact the app developer and check your admin screen.'
  344. )
  345. );
  346. throw $e;
  347. }
  348. }
  349. // check the code for not allowed calls
  350. if(!$isShipped && !Installer::checkCode($extractDir)) {
  351. OC_Helper::rmdirr($extractDir);
  352. throw new \Exception($l->t("App can't be installed because of not allowed code in the App"));
  353. }
  354. // check if the app is compatible with this version of ownCloud
  355. if(!OC_App::isAppCompatible(\OCP\Util::getVersion(), $info)) {
  356. OC_Helper::rmdirr($extractDir);
  357. throw new \Exception($l->t("App can't be installed because it is not compatible with this version of the server"));
  358. }
  359. // check if shipped tag is set which is only allowed for apps that are shipped with ownCloud
  360. if(!$isShipped && isset($info['shipped']) && ($info['shipped']=='true')) {
  361. OC_Helper::rmdirr($extractDir);
  362. throw new \Exception($l->t("App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps"));
  363. }
  364. // check if the ocs version is the same as the version in info.xml/version
  365. $version = trim($info['version']);
  366. if(isset($data['appdata']['version']) && $version<>trim($data['appdata']['version'])) {
  367. OC_Helper::rmdirr($extractDir);
  368. throw new \Exception($l->t("App can't be installed because the version in info.xml is not the same as the version reported from the app store"));
  369. }
  370. return $info;
  371. }
  372. /**
  373. * Check if an update for the app is available
  374. * @param string $app
  375. * @return string|false false or the version number of the update
  376. *
  377. * The function will check if an update for a version is available
  378. */
  379. public static function isUpdateAvailable( $app ) {
  380. static $isInstanceReadyForUpdates = null;
  381. if ($isInstanceReadyForUpdates === null) {
  382. $installPath = OC_App::getInstallPath();
  383. if ($installPath === false || $installPath === null) {
  384. $isInstanceReadyForUpdates = false;
  385. } else {
  386. $isInstanceReadyForUpdates = true;
  387. }
  388. }
  389. if ($isInstanceReadyForUpdates === false) {
  390. return false;
  391. }
  392. $ocsid=\OC::$server->getAppConfig()->getValue( $app, 'ocsid', '');
  393. if($ocsid<>'') {
  394. $ocsClient = new OCSClient(
  395. \OC::$server->getHTTPClientService(),
  396. \OC::$server->getConfig(),
  397. \OC::$server->getLogger()
  398. );
  399. $ocsdata = $ocsClient->getApplication($ocsid, \OCP\Util::getVersion());
  400. $ocsversion= (string) $ocsdata['version'];
  401. $currentversion=OC_App::getAppVersion($app);
  402. if (version_compare($ocsversion, $currentversion, '>')) {
  403. return($ocsversion);
  404. }else{
  405. return false;
  406. }
  407. }else{
  408. return false;
  409. }
  410. }
  411. /**
  412. * Check if app is already downloaded
  413. * @param string $name name of the application to remove
  414. * @return boolean
  415. *
  416. * The function will check if the app is already downloaded in the apps repository
  417. */
  418. public static function isDownloaded( $name ) {
  419. foreach(\OC::$APPSROOTS as $dir) {
  420. $dirToTest = $dir['path'];
  421. $dirToTest .= '/';
  422. $dirToTest .= $name;
  423. $dirToTest .= '/';
  424. if (is_dir($dirToTest)) {
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. /**
  431. * Removes an app
  432. * @param string $name name of the application to remove
  433. * @return boolean
  434. *
  435. *
  436. * This function works as follows
  437. * -# call uninstall repair steps
  438. * -# removing the files
  439. *
  440. * The function will not delete preferences, tables and the configuration,
  441. * this has to be done by the function oc_app_uninstall().
  442. */
  443. public static function removeApp($appId) {
  444. if(Installer::isDownloaded( $appId )) {
  445. $appDir=OC_App::getInstallPath() . '/' . $appId;
  446. OC_Helper::rmdirr($appDir);
  447. return true;
  448. }else{
  449. \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
  450. return false;
  451. }
  452. }
  453. /**
  454. * Installs shipped apps
  455. *
  456. * This function installs all apps found in the 'apps' directory that should be enabled by default;
  457. * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
  458. * working ownCloud at the end instead of an aborted update.
  459. * @return array Array of error messages (appid => Exception)
  460. */
  461. public static function installShippedApps($softErrors = false) {
  462. $errors = [];
  463. foreach(\OC::$APPSROOTS as $app_dir) {
  464. if($dir = opendir( $app_dir['path'] )) {
  465. while( false !== ( $filename = readdir( $dir ))) {
  466. if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
  467. if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
  468. if(!Installer::isInstalled($filename)) {
  469. $info=OC_App::getAppInfo($filename);
  470. $enabled = isset($info['default_enable']);
  471. if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
  472. && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
  473. if ($softErrors) {
  474. try {
  475. Installer::installShippedApp($filename);
  476. } catch (\Doctrine\DBAL\Exception\TableExistsException $e) {
  477. $errors[$filename] = $e;
  478. continue;
  479. }
  480. } else {
  481. Installer::installShippedApp($filename);
  482. }
  483. \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
  484. }
  485. }
  486. }
  487. }
  488. }
  489. closedir( $dir );
  490. }
  491. }
  492. return $errors;
  493. }
  494. /**
  495. * install an app already placed in the app folder
  496. * @param string $app id of the app to install
  497. * @return integer
  498. */
  499. public static function installShippedApp($app) {
  500. //install the database
  501. $appPath = OC_App::getAppPath($app);
  502. if(is_file("$appPath/appinfo/database.xml")) {
  503. OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
  504. }
  505. //run appinfo/install.php
  506. \OC_App::registerAutoloading($app, $appPath);
  507. self::includeAppScript("$appPath/appinfo/install.php");
  508. $info = OC_App::getAppInfo($app);
  509. if (is_null($info)) {
  510. return false;
  511. }
  512. \OC_App::setupBackgroundJobs($info['background-jobs']);
  513. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  514. $config = \OC::$server->getConfig();
  515. $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
  516. if (array_key_exists('ocsid', $info)) {
  517. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  518. }
  519. //set remote/public handlers
  520. foreach($info['remote'] as $name=>$path) {
  521. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  522. }
  523. foreach($info['public'] as $name=>$path) {
  524. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  525. }
  526. OC_App::setAppTypes($info['id']);
  527. if(isset($info['settings']) && is_array($info['settings'])) {
  528. // requires that autoloading was registered for the app,
  529. // as happens before running the install.php some lines above
  530. \OC::$server->getSettingsManager()->setupSettings($info['settings']);
  531. }
  532. return $info['id'];
  533. }
  534. /**
  535. * check the code of an app with some static code checks
  536. * @param string $folder the folder of the app to check
  537. * @return boolean true for app is o.k. and false for app is not o.k.
  538. */
  539. public static function checkCode($folder) {
  540. // is the code checker enabled?
  541. if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
  542. return true;
  543. }
  544. $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
  545. $errors = $codeChecker->analyseFolder($folder);
  546. return empty($errors);
  547. }
  548. /**
  549. * @param $basedir
  550. */
  551. private static function includeAppScript($script) {
  552. if ( file_exists($script) ){
  553. include $script;
  554. }
  555. }
  556. }