aboutsummaryrefslogtreecommitdiffstats
path: root/apps/dav/lib/CalDAV/WebcalCaching/Connection.php
blob: 9d626f2db6dd67f233e4abf5f4031ebc57e0aad6 (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
159
160
161
162
163
164
165
166
167
168
169
170
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OCA\DAV\CalDAV\WebcalCaching;

use Exception;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use OCP\Http\Client\IClientService;
use OCP\Http\Client\LocalServerException;
use OCP\IAppConfig;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Sabre\DAV\Xml\Property\Href;
use Sabre\VObject\Reader;

class Connection {
	public function __construct(private IClientService $clientService,
		private IAppConfig $config,
		private LoggerInterface $logger) {
	}

	/**
	 * gets webcal feed from remote server
	 */
	public function queryWebcalFeed(array $subscription, array &$mutations): ?string {
		$client = $this->clientService->newClient();

		$didBreak301Chain = false;
		$latestLocation = null;

		$handlerStack = HandlerStack::create();
		$handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
			return $request
				->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
				->withHeader('User-Agent', 'Nextcloud Webcal Service');
		}));
		$handlerStack->push(Middleware::mapResponse(function (ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
			if (!$didBreak301Chain) {
				if ($response->getStatusCode() !== 301) {
					$didBreak301Chain = true;
				} else {
					$latestLocation = $response->getHeader('Location');
				}
			}
			return $response;
		}));

		$allowLocalAccess = $this->config->getValueString('dav', 'webcalAllowLocalAccess', 'no');
		$subscriptionId = $subscription['id'];
		$url = $this->cleanURL($subscription['source']);
		if ($url === null) {
			return null;
		}

		try {
			$params = [
				'allow_redirects' => [
					'redirects' => 10
				],
				'handler' => $handlerStack,
				'nextcloud' => [
					'allow_local_address' => $allowLocalAccess === 'yes',
				]
			];

			$user = parse_url($subscription['source'], PHP_URL_USER);
			$pass = parse_url($subscription['source'], PHP_URL_PASS);
			if ($user !== null && $pass !== null) {
				$params['auth'] = [$user, $pass];
			}

			$response = $client->get($url, $params);
			$body = $response->getBody();

			if ($latestLocation !== null) {
				$mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
			}

			$contentType = $response->getHeader('Content-Type');
			$contentType = explode(';', $contentType, 2)[0];
			switch ($contentType) {
				case 'application/calendar+json':
					try {
						$jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
					} catch (Exception $ex) {
						// In case of a parsing error return null
						$this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]);
						return null;
					}
					return $jCalendar->serialize();

				case 'application/calendar+xml':
					try {
						$xCalendar = Reader::readXML($body);
					} catch (Exception $ex) {
						// In case of a parsing error return null
						$this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]);
						return null;
					}
					return $xCalendar->serialize();

				case 'text/calendar':
				default:
					try {
						$vCalendar = Reader::read($body);
					} catch (Exception $ex) {
						// In case of a parsing error return null
						$this->logger->warning("Subscription $subscriptionId could not be parsed", ['exception' => $ex]);
						return null;
					}
					return $vCalendar->serialize();
			}
		} catch (LocalServerException $ex) {
			$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [
				'exception' => $ex,
			]);

			return null;
		} catch (Exception $ex) {
			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [
				'exception' => $ex,
			]);

			return null;
		}
	}

	/**
	 * This method will strip authentication information and replace the
	 * 'webcal' or 'webcals' protocol scheme
	 *
	 * @param string $url
	 * @return string|null
	 */
	private function cleanURL(string $url): ?string {
		$parsed = parse_url($url);
		if ($parsed === false) {
			return null;
		}

		if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
			$scheme = 'http';
		} else {
			$scheme = 'https';
		}

		$host = $parsed['host'] ?? '';
		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
		$path = $parsed['path'] ?? '';
		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';

		$cleanURL = "$scheme://$host$port$path$query$fragment";
		// parse_url is giving some weird results if no url and no :// is given,
		// so let's test the url again
		$parsedClean = parse_url($cleanURL);
		if ($parsedClean === false || !isset($parsedClean['host'])) {
			return null;
		}

		return $cleanURL;
	}
}