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.

174 lines
5.1 KiB

3 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 Arthur Schiwon <blizzz@arthur-schiwon.de>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Updater;
  27. use OCP\AppFramework\Db\DoesNotExistException;
  28. use OCP\Http\Client\IClientService;
  29. use OCP\Http\Client\IResponse;
  30. use OCP\ILogger;
  31. class ChangesCheck {
  32. /** @var IClientService */
  33. protected $clientService;
  34. /** @var ChangesMapper */
  35. private $mapper;
  36. /** @var ILogger */
  37. private $logger;
  38. public const RESPONSE_NO_CONTENT = 0;
  39. public const RESPONSE_USE_CACHE = 1;
  40. public const RESPONSE_HAS_CONTENT = 2;
  41. public function __construct(IClientService $clientService, ChangesMapper $mapper, ILogger $logger) {
  42. $this->clientService = $clientService;
  43. $this->mapper = $mapper;
  44. $this->logger = $logger;
  45. }
  46. /**
  47. * @throws DoesNotExistException
  48. */
  49. public function getChangesForVersion(string $version): array {
  50. $version = $this->normalizeVersion($version);
  51. $changesInfo = $this->mapper->getChanges($version);
  52. $changesData = json_decode($changesInfo->getData(), true);
  53. if (empty($changesData)) {
  54. throw new DoesNotExistException('Unable to decode changes info');
  55. }
  56. return $changesData;
  57. }
  58. /**
  59. * @throws \Exception
  60. */
  61. public function check(string $uri, string $version): array {
  62. try {
  63. $version = $this->normalizeVersion($version);
  64. $changesInfo = $this->mapper->getChanges($version);
  65. if ($changesInfo->getLastCheck() + 1800 > time()) {
  66. return json_decode($changesInfo->getData(), true);
  67. }
  68. } catch (DoesNotExistException $e) {
  69. $changesInfo = new ChangesResult();
  70. }
  71. $response = $this->queryChangesServer($uri, $changesInfo);
  72. switch ($this->evaluateResponse($response)) {
  73. case self::RESPONSE_NO_CONTENT:
  74. return [];
  75. case self::RESPONSE_USE_CACHE:
  76. return json_decode($changesInfo->getData(), true);
  77. case self::RESPONSE_HAS_CONTENT:
  78. default:
  79. $data = $this->extractData($response->getBody());
  80. $changesInfo->setData(json_encode($data));
  81. $changesInfo->setEtag($response->getHeader('Etag'));
  82. $this->cacheResult($changesInfo, $version);
  83. return $data;
  84. }
  85. }
  86. protected function evaluateResponse(IResponse $response): int {
  87. if ($response->getStatusCode() === 304) {
  88. return self::RESPONSE_USE_CACHE;
  89. } elseif ($response->getStatusCode() === 404) {
  90. return self::RESPONSE_NO_CONTENT;
  91. } elseif ($response->getStatusCode() === 200) {
  92. return self::RESPONSE_HAS_CONTENT;
  93. }
  94. $this->logger->debug('Unexpected return code {code} from changelog server', [
  95. 'app' => 'core',
  96. 'code' => $response->getStatusCode(),
  97. ]);
  98. return self::RESPONSE_NO_CONTENT;
  99. }
  100. protected function cacheResult(ChangesResult $entry, string $version) {
  101. if ($entry->getVersion() === $version) {
  102. $this->mapper->update($entry);
  103. } else {
  104. $entry->setVersion($version);
  105. $this->mapper->insert($entry);
  106. }
  107. }
  108. /**
  109. * @throws \Exception
  110. */
  111. protected function queryChangesServer(string $uri, ChangesResult $entry): IResponse {
  112. $headers = [];
  113. if ($entry->getEtag() !== '') {
  114. $headers['If-None-Match'] = [$entry->getEtag()];
  115. }
  116. $entry->setLastCheck(time());
  117. $client = $this->clientService->newClient();
  118. return $client->get($uri, [
  119. 'headers' => $headers,
  120. ]);
  121. }
  122. protected function extractData($body):array {
  123. $data = [];
  124. if ($body) {
  125. $loadEntities = libxml_disable_entity_loader(true);
  126. $xml = @simplexml_load_string($body);
  127. libxml_disable_entity_loader($loadEntities);
  128. if ($xml !== false) {
  129. $data['changelogURL'] = (string)$xml->changelog['href'];
  130. $data['whatsNew'] = [];
  131. foreach ($xml->whatsNew as $infoSet) {
  132. $data['whatsNew'][(string)$infoSet['lang']] = [
  133. 'regular' => (array)$infoSet->regular->item,
  134. 'admin' => (array)$infoSet->admin->item,
  135. ];
  136. }
  137. } else {
  138. libxml_clear_errors();
  139. }
  140. }
  141. return $data;
  142. }
  143. /**
  144. * returns a x.y.z form of the provided version. Extra numbers will be
  145. * omitted, missing ones added as zeros.
  146. */
  147. public function normalizeVersion(string $version): string {
  148. $versionNumbers = array_slice(explode('.', $version), 0, 3);
  149. $versionNumbers[0] = $versionNumbers[0] ?: '0'; // deal with empty input
  150. while (count($versionNumbers) < 3) {
  151. // changelog server expects x.y.z, pad 0 if it is too short
  152. $versionNumbers[] = 0;
  153. }
  154. return implode('.', $versionNumbers);
  155. }
  156. }