| 9 | use OCP\Http\Client\IClientService; |
| 10 | |
| 11 | class ExternalHttpClient { |
| 12 | public const CONNECT_TIMEOUT_SECONDS = 10; |
| 13 | public const TIMEOUT_SECONDS = 60; |
| 14 | |
| 15 | public function __construct( |
| 16 | private IClientService $clientService, |
| 17 | private ExternalUrlValidator $urlValidator, |
| 18 | ) { |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * @param array<string, string> $headers |
| 23 | * @return array{status: int, body: string, error: string|null} |
| 24 | */ |
| 25 | public function request( |
| 26 | string $url, |
| 27 | string $method = 'GET', |
| 28 | array $headers = [], |
| 29 | ?string $body = null, |
| 30 | ?string $basicAuth = null, |
| 31 | ): array { |
| 32 | $urlError = $this->urlValidator->validate($url); |
| 33 | if ($urlError !== null) { |
| 34 | return ['status' => 0, 'body' => '', 'error' => $urlError]; |
| 35 | } |
| 36 | |
| 37 | foreach ($headers as $name => $value) { |
| 38 | if (!is_string($name) || preg_match('/[\r\n:]/', $name) || preg_match('/[\r\n]/', $value)) { |
| 39 | return ['status' => 0, 'body' => '', 'error' => 'External request headers are invalid']; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | $options = [ |
| 44 | 'allow_redirects' => false, |
| 45 | 'connect_timeout' => self::CONNECT_TIMEOUT_SECONDS, |
| 46 | 'timeout' => self::TIMEOUT_SECONDS, |
| 47 | 'verify' => true, |
| 48 | 'headers' => $headers, |
| 49 | ]; |
| 50 | if ($body !== null) { |
| 51 | $options['body'] = $body; |
| 52 | } |
| 53 | if ($basicAuth !== null && $basicAuth !== '') { |
| 54 | [$username, $password] = array_pad(explode(':', $basicAuth, 2), 2, ''); |
| 55 | $options['auth'] = [$username, $password]; |
| 56 | } |
| 57 | |
| 58 | try { |
| 59 | $response = $this->clientService->newClient()->request(strtoupper($method), $url, $options); |
| 60 | return [ |
| 61 | 'status' => $response->getStatusCode(), |
| 62 | 'body' => (string)$response->getBody(), |
| 63 | 'error' => null, |
| 64 | ]; |
| 65 | } catch (\Throwable $e) { |
| 66 | return ['status' => 0, 'body' => '', 'error' => 'External request failed']; |
| 67 | } |
| 68 | } |
nothing calls this directly
no outgoing calls
no test coverage detected