Passed
Push — master ( b75966...f85fb3 )
by Pauli
10:39
created

HttpUtil::loadFromUrl()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 19
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 30
rs 9.6333
1
<?php declare(strict_types=1);
2
3
/**
4
 * ownCloud - Music app
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Pauli Järvinen <[email protected]>
10
 * @copyright Pauli Järvinen 2022
11
 */
12
13
namespace OCA\Music\Utility;
14
15
/**
16
 * Static utility functions to work with HTTP requests
17
 */
18
class HttpUtil {
19
20
	/**
21
	 * Use HTTP GET to load the requested URL
22
	 * @return array with three keys: ['content' => string|false, 'status_code' => int, 'message' => string]
23
	 */
24
	public static function loadFromUrl(string $url) : array {
25
		if (!Util::startsWith($url, 'http://', /*ignoreCase=*/true)
26
				&& !Util::startsWith($url, 'https://', /*ignoreCase=*/true)) {
27
			$content = false;
28
			$status_code = 0;
29
			$message = 'URL scheme must be HTTP or HTTPS';
30
		} else {
31
			$opts = [
32
				'http' => [
33
					'header' => self::userAgentHeader(),	// some servers don't allow requests without a user agent header
34
					'ignore_errors' => true 				// don't emit warnings for bad/unavailable URL, we handle errors manually
35
				]
36
			];
37
			$context = \stream_context_create($opts);
38
			$content = \file_get_contents($url, false, $context);
39
40
			// It's some PHP magic that calling file_get_contents creates and populates also a local
41
			// variable array $http_response_header, provided that the server could be reached.
42
			// PhpStan thinks that this varialbe would always exist, and doesn't like the isset.
43
			// @phpstan-ignore-next-line
44
			if (isset($http_response_header)) {
45
				list($version, $status_code, $message) = \explode(' ', $http_response_header[0], 3);
46
				$status_code = (int)$status_code;
47
			} else {
48
				$status_code = 0;
49
				$message = 'The requested URL did not respond';
50
			}
51
		}
52
53
		return \compact('content', 'status_code', 'message');
54
	}
55
56
	public static function userAgentHeader() : string {
57
		// Note: the following is deprecated since NC14 but the replacement
58
		// \OCP\App\IAppManager::getAppVersion is not available before NC14.
59
		$appVersion = \OCP\App::getAppVersion('music');
60
61
		return 'User-Agent: OCMusic/' . $appVersion;
62
	}
63
}
64