1
0

RefreshWebcalJob.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2018 Georg Ehrke <oc.list@georgehrke.com>
  5. *
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  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. namespace OCA\DAV\BackgroundJob;
  25. use GuzzleHttp\HandlerStack;
  26. use GuzzleHttp\Middleware;
  27. use OC\BackgroundJob\Job;
  28. use OCA\DAV\CalDAV\CalDavBackend;
  29. use OCP\AppFramework\Utility\ITimeFactory;
  30. use OCP\Http\Client\IClientService;
  31. use OCP\IConfig;
  32. use OCP\ILogger;
  33. use Psr\Http\Message\RequestInterface;
  34. use Psr\Http\Message\ResponseInterface;
  35. use Sabre\DAV\Exception\BadRequest;
  36. use Sabre\DAV\PropPatch;
  37. use Sabre\DAV\Xml\Property\Href;
  38. use Sabre\VObject\Component;
  39. use Sabre\VObject\DateTimeParser;
  40. use Sabre\VObject\InvalidDataException;
  41. use Sabre\VObject\ParseException;
  42. use Sabre\VObject\Reader;
  43. use Sabre\VObject\Splitter\ICalendar;
  44. class RefreshWebcalJob extends Job {
  45. /** @var CalDavBackend */
  46. private $calDavBackend;
  47. /** @var IClientService */
  48. private $clientService;
  49. /** @var IConfig */
  50. private $config;
  51. /** @var ILogger */
  52. private $logger;
  53. /** @var ITimeFactory */
  54. private $timeFactory;
  55. /** @var array */
  56. private $subscription;
  57. /**
  58. * RefreshWebcalJob constructor.
  59. *
  60. * @param CalDavBackend $calDavBackend
  61. * @param IClientService $clientService
  62. * @param IConfig $config
  63. * @param ILogger $logger
  64. * @param ITimeFactory $timeFactory
  65. */
  66. public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger, ITimeFactory $timeFactory) {
  67. $this->calDavBackend = $calDavBackend;
  68. $this->clientService = $clientService;
  69. $this->config = $config;
  70. $this->logger = $logger;
  71. $this->timeFactory = $timeFactory;
  72. }
  73. /**
  74. * this function is called at most every hour
  75. *
  76. * @inheritdoc
  77. */
  78. public function execute($jobList, ILogger $logger = null) {
  79. $subscription = $this->getSubscription($this->argument['principaluri'], $this->argument['uri']);
  80. if (!$subscription) {
  81. return;
  82. }
  83. // if no refresh rate was configured, just refresh once a week
  84. $subscriptionId = $subscription['id'];
  85. $refreshrate = $subscription['refreshrate'] ?? 'P1W';
  86. try {
  87. /** @var \DateInterval $dateInterval */
  88. $dateInterval = DateTimeParser::parseDuration($refreshrate);
  89. } catch(InvalidDataException $ex) {
  90. $this->logger->logException($ex);
  91. $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid");
  92. return;
  93. }
  94. $interval = $this->getIntervalFromDateInterval($dateInterval);
  95. if (($this->timeFactory->getTime() - $this->lastRun) <= $interval) {
  96. return;
  97. }
  98. parent::execute($jobList, $logger);
  99. }
  100. /**
  101. * @param array $argument
  102. */
  103. protected function run($argument) {
  104. $subscription = $this->getSubscription($argument['principaluri'], $argument['uri']);
  105. $mutations = [];
  106. if (!$subscription) {
  107. return;
  108. }
  109. $webcalData = $this->queryWebcalFeed($subscription, $mutations);
  110. if (!$webcalData) {
  111. return;
  112. }
  113. $stripTodos = $subscription['striptodos'] ?? 1;
  114. $stripAlarms = $subscription['stripalarms'] ?? 1;
  115. $stripAttachments = $subscription['stripattachments'] ?? 1;
  116. try {
  117. $splitter = new ICalendar($webcalData, Reader::OPTION_FORGIVING);
  118. // we wait with deleting all outdated events till we parsed the new ones
  119. // in case the new calendar is broken and `new ICalendar` throws a ParseException
  120. // the user will still see the old data
  121. $this->calDavBackend->purgeAllCachedEventsForSubscription($subscription['id']);
  122. while ($vObject = $splitter->getNext()) {
  123. /** @var Component $vObject */
  124. $uid = null;
  125. $compName = null;
  126. foreach ($vObject->getComponents() as $component) {
  127. if ($component->name === 'VTIMEZONE') {
  128. continue;
  129. }
  130. $uid = $component->{'UID'}->getValue();
  131. $compName = $component->name;
  132. if ($stripAlarms) {
  133. unset($component->{'VALARM'});
  134. }
  135. if ($stripAttachments) {
  136. unset($component->{'ATTACH'});
  137. }
  138. }
  139. if ($stripTodos && $compName === 'VTODO') {
  140. continue;
  141. }
  142. $uri = $uid . '.ics';
  143. $calendarData = $vObject->serialize();
  144. try {
  145. $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION);
  146. } catch(BadRequest $ex) {
  147. $this->logger->logException($ex);
  148. }
  149. }
  150. $newRefreshRate = $this->checkWebcalDataForRefreshRate($subscription, $webcalData);
  151. if ($newRefreshRate) {
  152. $mutations['{http://apple.com/ns/ical/}refreshrate'] = $newRefreshRate;
  153. }
  154. $this->updateSubscription($subscription, $mutations);
  155. } catch(ParseException $ex) {
  156. $subscriptionId = $subscription['id'];
  157. $this->logger->logException($ex);
  158. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error");
  159. }
  160. }
  161. /**
  162. * gets webcal feed from remote server
  163. *
  164. * @param array $subscription
  165. * @param array &$mutations
  166. * @return null|string
  167. */
  168. private function queryWebcalFeed(array $subscription, array &$mutations) {
  169. $client = $this->clientService->newClient();
  170. $didBreak301Chain = false;
  171. $latestLocation = null;
  172. $handlerStack = HandlerStack::create();
  173. $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
  174. return $request
  175. ->withHeader('Accept', 'text/calendar, application/calendar+json, application/calendar+xml')
  176. ->withHeader('User-Agent', 'Nextcloud Webcal Crawler');
  177. }));
  178. $handlerStack->push(Middleware::mapResponse(function(ResponseInterface $response) use (&$didBreak301Chain, &$latestLocation) {
  179. if (!$didBreak301Chain) {
  180. if ($response->getStatusCode() !== 301) {
  181. $didBreak301Chain = true;
  182. } else {
  183. $latestLocation = $response->getHeader('Location');
  184. }
  185. }
  186. return $response;
  187. }));
  188. $allowLocalAccess = $this->config->getAppValue('dav', 'webcalAllowLocalAccess', 'no');
  189. $subscriptionId = $subscription['id'];
  190. $url = $this->cleanURL($subscription['source']);
  191. if ($url === null) {
  192. return null;
  193. }
  194. if ($allowLocalAccess !== 'yes') {
  195. $host = parse_url($url, PHP_URL_HOST);
  196. // remove brackets from IPv6 addresses
  197. if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
  198. $host = substr($host, 1, -1);
  199. }
  200. if ($host === 'localhost' || substr($host, -6) === '.local' || substr($host, -10) === '.localhost' ||
  201. preg_match('/(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/', $host)) {
  202. $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules");
  203. return null;
  204. }
  205. }
  206. try {
  207. $params = [
  208. 'allow_redirects' => [
  209. 'redirects' => 10
  210. ],
  211. 'handler' => $handlerStack,
  212. ];
  213. $user = parse_url($subscription['source'], PHP_URL_USER);
  214. $pass = parse_url($subscription['source'], PHP_URL_PASS);
  215. if ($user !== null && $pass !== null) {
  216. $params['auth'] = [$user, $pass];
  217. }
  218. $response = $client->get($url, $params);
  219. $body = $response->getBody();
  220. if ($latestLocation) {
  221. $mutations['{http://calendarserver.org/ns/}source'] = new Href($latestLocation);
  222. }
  223. $contentType = $response->getHeader('Content-Type');
  224. $contentType = explode(';', $contentType, 2)[0];
  225. switch($contentType) {
  226. case 'application/calendar+json':
  227. try {
  228. $jCalendar = Reader::readJson($body, Reader::OPTION_FORGIVING);
  229. } catch(\Exception $ex) {
  230. // In case of a parsing error return null
  231. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  232. return null;
  233. }
  234. return $jCalendar->serialize();
  235. case 'application/calendar+xml':
  236. try {
  237. $xCalendar = Reader::readXML($body);
  238. } catch(\Exception $ex) {
  239. // In case of a parsing error return null
  240. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  241. return null;
  242. }
  243. return $xCalendar->serialize();
  244. case 'text/calendar':
  245. default:
  246. try {
  247. $vCalendar = Reader::read($body);
  248. } catch(\Exception $ex) {
  249. // In case of a parsing error return null
  250. $this->logger->debug("Subscription $subscriptionId could not be parsed");
  251. return null;
  252. }
  253. return $vCalendar->serialize();
  254. }
  255. } catch(\Exception $ex) {
  256. $this->logger->logException($ex);
  257. $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error");
  258. return null;
  259. }
  260. }
  261. /**
  262. * loads subscription from backend
  263. *
  264. * @param string $principalUri
  265. * @param string $uri
  266. * @return array|null
  267. */
  268. private function getSubscription(string $principalUri, string $uri) {
  269. $subscriptions = array_values(array_filter(
  270. $this->calDavBackend->getSubscriptionsForUser($principalUri),
  271. function($sub) use ($uri) {
  272. return $sub['uri'] === $uri;
  273. }
  274. ));
  275. if (\count($subscriptions) === 0) {
  276. return null;
  277. }
  278. $this->subscription = $subscriptions[0];
  279. return $this->subscription;
  280. }
  281. /**
  282. * get total number of seconds from DateInterval object
  283. *
  284. * @param \DateInterval $interval
  285. * @return int
  286. */
  287. private function getIntervalFromDateInterval(\DateInterval $interval):int {
  288. return $interval->s
  289. + ($interval->i * 60)
  290. + ($interval->h * 60 * 60)
  291. + ($interval->d * 60 * 60 * 24)
  292. + ($interval->m * 60 * 60 * 24 * 30)
  293. + ($interval->y * 60 * 60 * 24 * 365);
  294. }
  295. /**
  296. * check if:
  297. * - current subscription stores a refreshrate
  298. * - the webcal feed suggests a refreshrate
  299. * - return suggested refreshrate if user didn't set a custom one
  300. *
  301. * @param array $subscription
  302. * @param string $webcalData
  303. * @return string|null
  304. */
  305. private function checkWebcalDataForRefreshRate($subscription, $webcalData) {
  306. // if there is no refreshrate stored in the database, check the webcal feed
  307. // whether it suggests any refresh rate and store that in the database
  308. if (isset($subscription['refreshrate']) && $subscription['refreshrate'] !== null) {
  309. return null;
  310. }
  311. /** @var Component\VCalendar $vCalendar */
  312. $vCalendar = Reader::read($webcalData);
  313. $newRefreshrate = null;
  314. if (isset($vCalendar->{'X-PUBLISHED-TTL'})) {
  315. $newRefreshrate = $vCalendar->{'X-PUBLISHED-TTL'}->getValue();
  316. }
  317. if (isset($vCalendar->{'REFRESH-INTERVAL'})) {
  318. $newRefreshrate = $vCalendar->{'REFRESH-INTERVAL'}->getValue();
  319. }
  320. if (!$newRefreshrate) {
  321. return null;
  322. }
  323. // check if new refresh rate is even valid
  324. try {
  325. DateTimeParser::parseDuration($newRefreshrate);
  326. } catch(InvalidDataException $ex) {
  327. return null;
  328. }
  329. return $newRefreshrate;
  330. }
  331. /**
  332. * update subscription stored in database
  333. * used to set:
  334. * - refreshrate
  335. * - source
  336. *
  337. * @param array $subscription
  338. * @param array $mutations
  339. */
  340. private function updateSubscription(array $subscription, array $mutations) {
  341. if (empty($mutations)) {
  342. return;
  343. }
  344. $propPatch = new PropPatch($mutations);
  345. $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
  346. $propPatch->commit();
  347. }
  348. /**
  349. * This method will strip authentication information and replace the
  350. * 'webcal' or 'webcals' protocol scheme
  351. *
  352. * @param string $url
  353. * @return string|null
  354. */
  355. private function cleanURL(string $url) {
  356. $parsed = parse_url($url);
  357. if ($parsed === false) {
  358. return null;
  359. }
  360. if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
  361. $scheme = 'http';
  362. } else {
  363. $scheme = 'https';
  364. }
  365. $host = $parsed['host'] ?? '';
  366. $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
  367. $path = $parsed['path'] ?? '';
  368. $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
  369. $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
  370. $cleanURL = "$scheme://$host$port$path$query$fragment";
  371. // parse_url is giving some weird results if no url and no :// is given,
  372. // so let's test the url again
  373. $parsedClean = parse_url($cleanURL);
  374. if ($parsedClean === false || !isset($parsedClean['host'])) {
  375. return null;
  376. }
  377. return $cleanURL;
  378. }
  379. }