updater.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 Björn Schießle <bjoern@schiessle.org>
  8. * @author Frank Karlitschek <frank@karlitschek.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Robin McCorkell <robin@mccorkell.me.uk>
  14. * @author Steffen Lindner <mail@steffen-lindner.de>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  17. * @author Vincent Petry <pvince81@owncloud.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC;
  35. use OC\Hooks\BasicEmitter;
  36. use OC\IntegrityCheck\Checker;
  37. use OC_App;
  38. use OC_Installer;
  39. use OC_Util;
  40. use OCP\IConfig;
  41. use OC\Setup;
  42. use OCP\ILogger;
  43. /**
  44. * Class that handles autoupdating of ownCloud
  45. *
  46. * Hooks provided in scope \OC\Updater
  47. * - maintenanceStart()
  48. * - maintenanceEnd()
  49. * - dbUpgrade()
  50. * - failure(string $message)
  51. */
  52. class Updater extends BasicEmitter {
  53. /** @var ILogger $log */
  54. private $log;
  55. /** @var \OC\HTTPHelper $helper */
  56. private $httpHelper;
  57. /** @var IConfig */
  58. private $config;
  59. /** @var Checker */
  60. private $checker;
  61. /** @var bool */
  62. private $simulateStepEnabled;
  63. /** @var bool */
  64. private $updateStepEnabled;
  65. /** @var bool */
  66. private $skip3rdPartyAppsDisable;
  67. private $logLevelNames = [
  68. 0 => 'Debug',
  69. 1 => 'Info',
  70. 2 => 'Warning',
  71. 3 => 'Error',
  72. 4 => 'Fatal',
  73. ];
  74. /**
  75. * @param HTTPHelper $httpHelper
  76. * @param IConfig $config
  77. * @param Checker $checker
  78. * @param ILogger $log
  79. */
  80. public function __construct(HTTPHelper $httpHelper,
  81. IConfig $config,
  82. Checker $checker,
  83. ILogger $log = null) {
  84. $this->httpHelper = $httpHelper;
  85. $this->log = $log;
  86. $this->config = $config;
  87. $this->checker = $checker;
  88. $this->simulateStepEnabled = true;
  89. $this->updateStepEnabled = true;
  90. }
  91. /**
  92. * Sets whether the database migration simulation must
  93. * be enabled.
  94. * This can be set to false to skip this test.
  95. *
  96. * @param bool $flag true to enable simulation, false otherwise
  97. */
  98. public function setSimulateStepEnabled($flag) {
  99. $this->simulateStepEnabled = $flag;
  100. }
  101. /**
  102. * Sets whether the update must be performed.
  103. * This can be set to false to skip the actual update.
  104. *
  105. * @param bool $flag true to enable update, false otherwise
  106. */
  107. public function setUpdateStepEnabled($flag) {
  108. $this->updateStepEnabled = $flag;
  109. }
  110. /**
  111. * Sets whether the update disables 3rd party apps.
  112. * This can be set to true to skip the disable.
  113. *
  114. * @param bool $flag false to not disable, true otherwise
  115. */
  116. public function setSkip3rdPartyAppsDisable($flag) {
  117. $this->skip3rdPartyAppsDisable = $flag;
  118. }
  119. /**
  120. * Check if a new version is available
  121. *
  122. * @return array|bool
  123. */
  124. public function check() {
  125. // Look up the cache - it is invalidated all 30 minutes
  126. if (((int)$this->config->getAppValue('core', 'lastupdatedat') + 1800) > time()) {
  127. return json_decode($this->config->getAppValue('core', 'lastupdateResult'), true);
  128. }
  129. $updaterUrl = $this->config->getSystemValue('updater.server.url', 'https://updates.nextcloud.com/updater_server/');
  130. $this->config->setAppValue('core', 'lastupdatedat', time());
  131. if ($this->config->getAppValue('core', 'installedat', '') === '') {
  132. $this->config->setAppValue('core', 'installedat', microtime(true));
  133. }
  134. $version = \OCP\Util::getVersion();
  135. $version['installed'] = $this->config->getAppValue('core', 'installedat');
  136. $version['updated'] = $this->config->getAppValue('core', 'lastupdatedat');
  137. $version['updatechannel'] = \OC_Util::getChannel();
  138. $version['edition'] = \OC_Util::getEditionString();
  139. $version['build'] = \OC_Util::getBuild();
  140. $versionString = implode('x', $version);
  141. //fetch xml data from updater
  142. $url = $updaterUrl . '?version=' . $versionString;
  143. $tmp = [];
  144. $xml = $this->httpHelper->getUrlContent($url);
  145. if ($xml) {
  146. $loadEntities = libxml_disable_entity_loader(true);
  147. $data = @simplexml_load_string($xml);
  148. libxml_disable_entity_loader($loadEntities);
  149. if ($data !== false) {
  150. $tmp['version'] = (string)$data->version;
  151. $tmp['versionstring'] = (string)$data->versionstring;
  152. $tmp['url'] = (string)$data->url;
  153. $tmp['web'] = (string)$data->web;
  154. $tmp['autoupdater'] = (string)$data->autoupdater;
  155. } else {
  156. libxml_clear_errors();
  157. }
  158. } else {
  159. $data = [];
  160. }
  161. // Cache the result
  162. $this->config->setAppValue('core', 'lastupdateResult', json_encode($data));
  163. return $tmp;
  164. }
  165. /**
  166. * runs the update actions in maintenance mode, does not upgrade the source files
  167. * except the main .htaccess file
  168. *
  169. * @return bool true if the operation succeeded, false otherwise
  170. */
  171. public function upgrade() {
  172. $logLevel = $this->config->getSystemValue('loglevel', \OCP\Util::WARN);
  173. $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
  174. $this->config->setSystemValue('loglevel', \OCP\Util::DEBUG);
  175. $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
  176. if(!$wasMaintenanceModeEnabled) {
  177. $this->config->setSystemValue('maintenance', true);
  178. $this->emit('\OC\Updater', 'maintenanceEnabled');
  179. }
  180. $installedVersion = $this->config->getSystemValue('version', '0.0.0');
  181. $currentVersion = implode('.', \OCP\Util::getVersion());
  182. $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
  183. $success = true;
  184. try {
  185. $this->doUpgrade($currentVersion, $installedVersion);
  186. } catch (HintException $exception) {
  187. $this->log->logException($exception, ['app' => 'core']);
  188. $this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
  189. $success = false;
  190. } catch (\Exception $exception) {
  191. $this->log->logException($exception, ['app' => 'core']);
  192. $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
  193. $success = false;
  194. }
  195. $this->emit('\OC\Updater', 'updateEnd', array($success));
  196. if(!$wasMaintenanceModeEnabled && $success) {
  197. $this->config->setSystemValue('maintenance', false);
  198. $this->emit('\OC\Updater', 'maintenanceDisabled');
  199. } else {
  200. $this->emit('\OC\Updater', 'maintenanceActive');
  201. }
  202. $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
  203. $this->config->setSystemValue('loglevel', $logLevel);
  204. $this->config->setSystemValue('installed', true);
  205. return $success;
  206. }
  207. /**
  208. * Return version from which this version is allowed to upgrade from
  209. *
  210. * @return string allowed previous version
  211. */
  212. private function getAllowedPreviousVersion() {
  213. // this should really be a JSON file
  214. require \OC::$SERVERROOT . '/version.php';
  215. /** @var array $OC_VersionCanBeUpgradedFrom */
  216. return implode('.', $OC_VersionCanBeUpgradedFrom);
  217. }
  218. /**
  219. * Whether an upgrade to a specified version is possible
  220. * @param string $oldVersion
  221. * @param string $newVersion
  222. * @param string $allowedPreviousVersion
  223. * @return bool
  224. */
  225. public function isUpgradePossible($oldVersion, $newVersion, $allowedPreviousVersion) {
  226. return (version_compare($allowedPreviousVersion, $oldVersion, '<=')
  227. && (version_compare($oldVersion, $newVersion, '<=') || $this->config->getSystemValue('debug', false)));
  228. }
  229. /**
  230. * Forward messages emitted by the repair routine
  231. *
  232. * @param Repair $repair repair routine
  233. */
  234. private function emitRepairMessages(Repair $repair) {
  235. $repair->listen('\OC\Repair', 'warning', function ($description) {
  236. $this->emit('\OC\Updater', 'repairWarning', array($description));
  237. });
  238. $repair->listen('\OC\Repair', 'error', function ($description) {
  239. $this->emit('\OC\Updater', 'repairError', array($description));
  240. });
  241. $repair->listen('\OC\Repair', 'info', function ($description) {
  242. $this->emit('\OC\Updater', 'repairInfo', array($description));
  243. });
  244. $repair->listen('\OC\Repair', 'step', function ($description) {
  245. $this->emit('\OC\Updater', 'repairStep', array($description));
  246. });
  247. }
  248. /**
  249. * runs the update actions in maintenance mode, does not upgrade the source files
  250. * except the main .htaccess file
  251. *
  252. * @param string $currentVersion current version to upgrade to
  253. * @param string $installedVersion previous version from which to upgrade from
  254. *
  255. * @throws \Exception
  256. */
  257. private function doUpgrade($currentVersion, $installedVersion) {
  258. // Stop update if the update is over several major versions
  259. $allowedPreviousVersion = $this->getAllowedPreviousVersion();
  260. if (!self::isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersion)) {
  261. throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
  262. }
  263. // Update .htaccess files
  264. try {
  265. Setup::updateHtaccess();
  266. Setup::protectDataDirectory();
  267. } catch (\Exception $e) {
  268. throw new \Exception($e->getMessage());
  269. }
  270. // create empty file in data dir, so we can later find
  271. // out that this is indeed an ownCloud data directory
  272. // (in case it didn't exist before)
  273. file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
  274. // pre-upgrade repairs
  275. $repair = new Repair(Repair::getBeforeUpgradeRepairSteps());
  276. $this->emitRepairMessages($repair);
  277. $repair->run();
  278. // simulate DB upgrade
  279. if ($this->simulateStepEnabled) {
  280. $this->checkCoreUpgrade();
  281. // simulate apps DB upgrade
  282. $this->checkAppUpgrade($currentVersion);
  283. }
  284. if ($this->updateStepEnabled) {
  285. $this->doCoreUpgrade();
  286. // update all shipped apps
  287. $disabledApps = $this->checkAppsRequirements();
  288. $this->doAppUpgrade();
  289. // upgrade appstore apps
  290. $this->upgradeAppStoreApps($disabledApps);
  291. // install new shipped apps on upgrade
  292. OC_App::loadApps('authentication');
  293. $errors = OC_Installer::installShippedApps(true);
  294. foreach ($errors as $appId => $exception) {
  295. /** @var \Exception $exception */
  296. $this->log->logException($exception, ['app' => $appId]);
  297. $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
  298. }
  299. // post-upgrade repairs
  300. $repair = new Repair(Repair::getRepairSteps());
  301. $this->emitRepairMessages($repair);
  302. $repair->run();
  303. //Invalidate update feed
  304. $this->config->setAppValue('core', 'lastupdatedat', 0);
  305. // Check for code integrity if not disabled
  306. if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
  307. $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
  308. $this->checker->runInstanceVerification();
  309. $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
  310. }
  311. // only set the final version if everything went well
  312. $this->config->setSystemValue('version', implode('.', \OCP\Util::getVersion()));
  313. }
  314. }
  315. protected function checkCoreUpgrade() {
  316. $this->emit('\OC\Updater', 'dbSimulateUpgradeBefore');
  317. // simulate core DB upgrade
  318. \OC_DB::simulateUpdateDbFromStructure(\OC::$SERVERROOT . '/db_structure.xml');
  319. $this->emit('\OC\Updater', 'dbSimulateUpgrade');
  320. }
  321. protected function doCoreUpgrade() {
  322. $this->emit('\OC\Updater', 'dbUpgradeBefore');
  323. // do the real upgrade
  324. \OC_DB::updateDbFromStructure(\OC::$SERVERROOT . '/db_structure.xml');
  325. $this->emit('\OC\Updater', 'dbUpgrade');
  326. }
  327. /**
  328. * @param string $version the oc version to check app compatibility with
  329. */
  330. protected function checkAppUpgrade($version) {
  331. $apps = \OC_App::getEnabledApps();
  332. $this->emit('\OC\Updater', 'appUpgradeCheckBefore');
  333. foreach ($apps as $appId) {
  334. $info = \OC_App::getAppInfo($appId);
  335. $compatible = \OC_App::isAppCompatible($version, $info);
  336. $isShipped = \OC_App::isShipped($appId);
  337. if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
  338. /**
  339. * FIXME: The preupdate check is performed before the database migration, otherwise database changes
  340. * are not possible anymore within it. - Consider this when touching the code.
  341. * @link https://github.com/owncloud/core/issues/10980
  342. * @see \OC_App::updateApp
  343. */
  344. if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
  345. $this->includePreUpdate($appId);
  346. }
  347. if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
  348. $this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
  349. \OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
  350. }
  351. }
  352. }
  353. $this->emit('\OC\Updater', 'appUpgradeCheck');
  354. }
  355. /**
  356. * Includes the pre-update file. Done here to prevent namespace mixups.
  357. * @param string $appId
  358. */
  359. private function includePreUpdate($appId) {
  360. include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
  361. }
  362. /**
  363. * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
  364. * (types authentication, filesystem, logging, in that order) afterwards.
  365. *
  366. * @throws NeedsUpdateException
  367. */
  368. protected function doAppUpgrade() {
  369. $apps = \OC_App::getEnabledApps();
  370. $priorityTypes = array('authentication', 'filesystem', 'logging');
  371. $pseudoOtherType = 'other';
  372. $stacks = array($pseudoOtherType => array());
  373. foreach ($apps as $appId) {
  374. $priorityType = false;
  375. foreach ($priorityTypes as $type) {
  376. if(!isset($stacks[$type])) {
  377. $stacks[$type] = array();
  378. }
  379. if (\OC_App::isType($appId, $type)) {
  380. $stacks[$type][] = $appId;
  381. $priorityType = true;
  382. break;
  383. }
  384. }
  385. if (!$priorityType) {
  386. $stacks[$pseudoOtherType][] = $appId;
  387. }
  388. }
  389. foreach ($stacks as $type => $stack) {
  390. foreach ($stack as $appId) {
  391. if (\OC_App::shouldUpgrade($appId)) {
  392. $this->emit('\OC\Updater', 'appUpgradeStarted', array($appId, \OC_App::getAppVersion($appId)));
  393. \OC_App::updateApp($appId);
  394. $this->emit('\OC\Updater', 'appUpgrade', array($appId, \OC_App::getAppVersion($appId)));
  395. }
  396. if($type !== $pseudoOtherType) {
  397. // load authentication, filesystem and logging apps after
  398. // upgrading them. Other apps my need to rely on modifying
  399. // user and/or filesystem aspects.
  400. \OC_App::loadApp($appId, false);
  401. }
  402. }
  403. }
  404. }
  405. /**
  406. * check if the current enabled apps are compatible with the current
  407. * ownCloud version. disable them if not.
  408. * This is important if you upgrade ownCloud and have non ported 3rd
  409. * party apps installed.
  410. *
  411. * @return array
  412. * @throws \Exception
  413. */
  414. private function checkAppsRequirements() {
  415. $isCoreUpgrade = $this->isCodeUpgrade();
  416. $apps = OC_App::getEnabledApps();
  417. $version = \OCP\Util::getVersion();
  418. $disabledApps = [];
  419. foreach ($apps as $app) {
  420. // check if the app is compatible with this version of ownCloud
  421. $info = OC_App::getAppInfo($app);
  422. if(!OC_App::isAppCompatible($version, $info)) {
  423. OC_App::disable($app);
  424. $this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
  425. }
  426. // no need to disable any app in case this is a non-core upgrade
  427. if (!$isCoreUpgrade) {
  428. continue;
  429. }
  430. // shipped apps will remain enabled
  431. if (OC_App::isShipped($app)) {
  432. continue;
  433. }
  434. // authentication and session apps will remain enabled as well
  435. if (OC_App::isType($app, ['session', 'authentication'])) {
  436. continue;
  437. }
  438. // disable any other 3rd party apps if not overriden
  439. if(!$this->skip3rdPartyAppsDisable) {
  440. \OC_App::disable($app);
  441. $disabledApps[]= $app;
  442. $this->emit('\OC\Updater', 'thirdPartyAppDisabled', array($app));
  443. };
  444. }
  445. return $disabledApps;
  446. }
  447. /**
  448. * @return bool
  449. */
  450. private function isCodeUpgrade() {
  451. $installedVersion = $this->config->getSystemValue('version', '0.0.0');
  452. $currentVersion = implode('.', \OCP\Util::getVersion());
  453. if (version_compare($currentVersion, $installedVersion, '>')) {
  454. return true;
  455. }
  456. return false;
  457. }
  458. /**
  459. * @param array $disabledApps
  460. * @throws \Exception
  461. */
  462. private function upgradeAppStoreApps(array $disabledApps) {
  463. foreach($disabledApps as $app) {
  464. try {
  465. if (OC_Installer::isUpdateAvailable($app)) {
  466. $ocsId = \OC::$server->getConfig()->getAppValue($app, 'ocsid', '');
  467. $this->emit('\OC\Updater', 'upgradeAppStoreApp', array($app));
  468. OC_Installer::updateAppByOCSId($ocsId);
  469. }
  470. } catch (\Exception $ex) {
  471. $this->log->logException($ex, ['app' => 'core']);
  472. }
  473. }
  474. }
  475. }