Updater.php 16 KB

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