aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Updater/ChangesCheck.php
blob: e88969f62a84abdaa477b584f7a8ffe9dbfd8ffa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OC\Updater;

use OCP\AppFramework\Db\DoesNotExistException;
use OCP\Http\Client\IClientService;
use OCP\Http\Client\IResponse;
use Psr\Log\LoggerInterface;

class ChangesCheck {
	/** @var IClientService */
	protected $clientService;
	/** @var ChangesMapper */
	private $mapper;
	private LoggerInterface $logger;

	public const RESPONSE_NO_CONTENT = 0;
	public const RESPONSE_USE_CACHE = 1;
	public const RESPONSE_HAS_CONTENT = 2;

	public function __construct(IClientService $clientService, ChangesMapper $mapper, LoggerInterface $logger) {
		$this->clientService = $clientService;
		$this->mapper = $mapper;
		$this->logger = $logger;
	}

	/**
	 * @throws DoesNotExistException
	 * @return array{changelogURL: string, whatsNew: array<string, array{admin: list<string>, regular: list<string>}>}
	 */
	public function getChangesForVersion(string $version): array {
		$version = $this->normalizeVersion($version);
		$changesInfo = $this->mapper->getChanges($version);
		$changesData = json_decode($changesInfo->getData(), true);
		if (empty($changesData)) {
			throw new DoesNotExistException('Unable to decode changes info');
		}
		return $changesData;
	}

	/**
	 * @throws \Exception
	 */
	public function check(string $uri, string $version): array {
		try {
			$version = $this->normalizeVersion($version);
			$changesInfo = $this->mapper->getChanges($version);
			if ($changesInfo->getLastCheck() + 1800 > time()) {
				return json_decode($changesInfo->getData(), true);
			}
		} catch (DoesNotExistException $e) {
			$changesInfo = new Changes();
		}

		$response = $this->queryChangesServer($uri, $changesInfo);

		switch ($this->evaluateResponse($response)) {
			case self::RESPONSE_NO_CONTENT:
				return [];
			case self::RESPONSE_USE_CACHE:
				return json_decode($changesInfo->getData(), true);
			case self::RESPONSE_HAS_CONTENT:
			default:
				$data = $this->extractData($response->getBody());
				$changesInfo->setData(json_encode($data));
				$changesInfo->setEtag($response->getHeader('Etag'));
				$this->cacheResult($changesInfo, $version);

				return $data;
		}
	}

	protected function evaluateResponse(IResponse $response): int {
		if ($response->getStatusCode() === 304) {
			return self::RESPONSE_USE_CACHE;
		} elseif ($response->getStatusCode() === 404) {
			return self::RESPONSE_NO_CONTENT;
		} elseif ($response->getStatusCode() === 200) {
			return self::RESPONSE_HAS_CONTENT;
		}
		$this->logger->debug('Unexpected return code {code} from changelog server', [
			'app' => 'core',
			'code' => $response->getStatusCode(),
		]);
		return self::RESPONSE_NO_CONTENT;
	}

	protected function cacheResult(Changes $entry, string $version) {
		if ($entry->getVersion() === $version) {
			$this->mapper->update($entry);
		} else {
			$entry->setVersion($version);
			$this->mapper->insert($entry);
		}
	}

	/**
	 * @throws \Exception
	 */
	protected function queryChangesServer(string $uri, Changes $entry): IResponse {
		$headers = [];
		if ($entry->getEtag() !== '') {
			$headers['If-None-Match'] = [$entry->getEtag()];
		}

		$entry->setLastCheck(time());
		$client = $this->clientService->newClient();
		return $client->get($uri, [
			'headers' => $headers,
		]);
	}

	protected function extractData($body):array {
		$data = [];
		if ($body) {
			if (\LIBXML_VERSION < 20900) {
				$loadEntities = libxml_disable_entity_loader(true);
				$xml = @simplexml_load_string($body);
				libxml_disable_entity_loader($loadEntities);
			} else {
				$xml = @simplexml_load_string($body);
			}
			if ($xml !== false) {
				$data['changelogURL'] = (string)$xml->changelog['href'];
				$data['whatsNew'] = [];
				foreach ($xml->whatsNew as $infoSet) {
					$data['whatsNew'][(string)$infoSet['lang']] = [
						'regular' => (array)$infoSet->regular->item,
						'admin' => (array)$infoSet->admin->item,
					];
				}
			} else {
				libxml_clear_errors();
			}
		}
		return $data;
	}

	/**
	 * returns a x.y.z form of the provided version. Extra numbers will be
	 * omitted, missing ones added as zeros.
	 */
	public function normalizeVersion(string $version): string {
		$versionNumbers = array_slice(explode('.', $version), 0, 3);
		$versionNumbers[0] = $versionNumbers[0] ?: '0'; // deal with empty input
		while (count($versionNumbers) < 3) {
			// changelog server expects x.y.z, pad 0 if it is too short
			$versionNumbers[] = 0;
		}
		return implode('.', $versionNumbers);
	}
}