Completed
Push — master ( 79f16f...3ff314 )
by Morris
36:57 queued 16:20
created

ChangesCheck::extractData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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