IMipPlugin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2017, Georg Ehrke
  5. *
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Leon Klingele <leon@struktur.de>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OCA\DAV\CalDAV\Schedule;
  27. use OCP\AppFramework\Utility\ITimeFactory;
  28. use OCP\Defaults;
  29. use OCP\IConfig;
  30. use OCP\IDBConnection;
  31. use OCP\IL10N;
  32. use OCP\ILogger;
  33. use OCP\IURLGenerator;
  34. use OCP\L10N\IFactory as L10NFactory;
  35. use OCP\Mail\IEMailTemplate;
  36. use OCP\Mail\IMailer;
  37. use OCP\Security\ISecureRandom;
  38. use Sabre\CalDAV\Schedule\IMipPlugin as SabreIMipPlugin;
  39. use Sabre\VObject\Component\VCalendar;
  40. use Sabre\VObject\Component\VEvent;
  41. use Sabre\VObject\DateTimeParser;
  42. use Sabre\VObject\ITip\Message;
  43. use Sabre\VObject\Parameter;
  44. use Sabre\VObject\Property;
  45. use Sabre\VObject\Recur\EventIterator;
  46. /**
  47. * iMIP handler.
  48. *
  49. * This class is responsible for sending out iMIP messages. iMIP is the
  50. * email-based transport for iTIP. iTIP deals with scheduling operations for
  51. * iCalendar objects.
  52. *
  53. * If you want to customize the email that gets sent out, you can do so by
  54. * extending this class and overriding the sendMessage method.
  55. *
  56. * @copyright Copyright (C) 2007-2015 fruux GmbH (https://fruux.com/).
  57. * @author Evert Pot (http://evertpot.com/)
  58. * @license http://sabre.io/license/ Modified BSD License
  59. */
  60. class IMipPlugin extends SabreIMipPlugin {
  61. /** @var string */
  62. private $userId;
  63. /** @var IConfig */
  64. private $config;
  65. /** @var IMailer */
  66. private $mailer;
  67. /** @var ILogger */
  68. private $logger;
  69. /** @var ITimeFactory */
  70. private $timeFactory;
  71. /** @var L10NFactory */
  72. private $l10nFactory;
  73. /** @var IURLGenerator */
  74. private $urlGenerator;
  75. /** @var ISecureRandom */
  76. private $random;
  77. /** @var IDBConnection */
  78. private $db;
  79. /** @var Defaults */
  80. private $defaults;
  81. const MAX_DATE = '2038-01-01';
  82. const METHOD_REQUEST = 'request';
  83. const METHOD_REPLY = 'reply';
  84. const METHOD_CANCEL = 'cancel';
  85. /**
  86. * @param IConfig $config
  87. * @param IMailer $mailer
  88. * @param ILogger $logger
  89. * @param ITimeFactory $timeFactory
  90. * @param L10NFactory $l10nFactory
  91. * @param IUrlGenerator $urlGenerator
  92. * @param Defaults $defaults
  93. * @param ISecureRandom $random
  94. * @param IDBConnection $db
  95. * @param string $userId
  96. */
  97. public function __construct(IConfig $config, IMailer $mailer, ILogger $logger,
  98. ITimeFactory $timeFactory, L10NFactory $l10nFactory,
  99. IURLGenerator $urlGenerator, Defaults $defaults,
  100. ISecureRandom $random, IDBConnection $db, $userId) {
  101. parent::__construct('');
  102. $this->userId = $userId;
  103. $this->config = $config;
  104. $this->mailer = $mailer;
  105. $this->logger = $logger;
  106. $this->timeFactory = $timeFactory;
  107. $this->l10nFactory = $l10nFactory;
  108. $this->urlGenerator = $urlGenerator;
  109. $this->random = $random;
  110. $this->db = $db;
  111. $this->defaults = $defaults;
  112. }
  113. /**
  114. * Event handler for the 'schedule' event.
  115. *
  116. * @param Message $iTipMessage
  117. * @return void
  118. */
  119. public function schedule(Message $iTipMessage) {
  120. // Not sending any emails if the system considers the update
  121. // insignificant.
  122. if (!$iTipMessage->significantChange) {
  123. if (!$iTipMessage->scheduleStatus) {
  124. $iTipMessage->scheduleStatus = '1.0;We got the message, but it\'s not significant enough to warrant an email';
  125. }
  126. return;
  127. }
  128. $summary = $iTipMessage->message->VEVENT->SUMMARY;
  129. if (parse_url($iTipMessage->sender, PHP_URL_SCHEME) !== 'mailto') {
  130. return;
  131. }
  132. if (parse_url($iTipMessage->recipient, PHP_URL_SCHEME) !== 'mailto') {
  133. return;
  134. }
  135. // don't send out mails for events that already took place
  136. $lastOccurrence = $this->getLastOccurrence($iTipMessage->message);
  137. $currentTime = $this->timeFactory->getTime();
  138. if ($lastOccurrence < $currentTime) {
  139. return;
  140. }
  141. // Strip off mailto:
  142. $sender = substr($iTipMessage->sender, 7);
  143. $recipient = substr($iTipMessage->recipient, 7);
  144. $senderName = $iTipMessage->senderName ?: null;
  145. $recipientName = $iTipMessage->recipientName ?: null;
  146. /** @var VEvent $vevent */
  147. $vevent = $iTipMessage->message->VEVENT;
  148. $attendee = $this->getCurrentAttendee($iTipMessage);
  149. $defaultLang = $this->l10nFactory->findLanguage();
  150. $lang = $this->getAttendeeLangOrDefault($defaultLang, $attendee);
  151. $l10n = $this->l10nFactory->get('dav', $lang);
  152. $meetingAttendeeName = $recipientName ?: $recipient;
  153. $meetingInviteeName = $senderName ?: $sender;
  154. $meetingTitle = $vevent->SUMMARY;
  155. $meetingDescription = $vevent->DESCRIPTION;
  156. $start = $vevent->DTSTART;
  157. if (isset($vevent->DTEND)) {
  158. $end = $vevent->DTEND;
  159. } elseif (isset($vevent->DURATION)) {
  160. $isFloating = $vevent->DTSTART->isFloating();
  161. $end = clone $vevent->DTSTART;
  162. $endDateTime = $end->getDateTime();
  163. $endDateTime = $endDateTime->add(DateTimeParser::parse($vevent->DURATION->getValue()));
  164. $end->setDateTime($endDateTime, $isFloating);
  165. } elseif (!$vevent->DTSTART->hasTime()) {
  166. $isFloating = $vevent->DTSTART->isFloating();
  167. $end = clone $vevent->DTSTART;
  168. $endDateTime = $end->getDateTime();
  169. $endDateTime = $endDateTime->modify('+1 day');
  170. $end->setDateTime($endDateTime, $isFloating);
  171. } else {
  172. $end = clone $vevent->DTSTART;
  173. }
  174. $meetingWhen = $this->generateWhenString($l10n, $start, $end);
  175. $meetingUrl = $vevent->URL;
  176. $meetingLocation = $vevent->LOCATION;
  177. $defaultVal = '--';
  178. $method = self::METHOD_REQUEST;
  179. switch (strtolower($iTipMessage->method)) {
  180. case self::METHOD_REPLY:
  181. $method = self::METHOD_REPLY;
  182. break;
  183. case self::METHOD_CANCEL:
  184. $method = self::METHOD_CANCEL;
  185. break;
  186. }
  187. $data = array(
  188. 'attendee_name' => (string)$meetingAttendeeName ?: $defaultVal,
  189. 'invitee_name' => (string)$meetingInviteeName ?: $defaultVal,
  190. 'meeting_title' => (string)$meetingTitle ?: $defaultVal,
  191. 'meeting_description' => (string)$meetingDescription ?: $defaultVal,
  192. 'meeting_url' => (string)$meetingUrl ?: $defaultVal,
  193. );
  194. $fromEMail = \OCP\Util::getDefaultEmailAddress('invitations-noreply');
  195. $fromName = $l10n->t('%1$s via %2$s', [$senderName, $this->defaults->getName()]);
  196. $message = $this->mailer->createMessage()
  197. ->setFrom([$fromEMail => $fromName])
  198. ->setReplyTo([$sender => $senderName])
  199. ->setTo([$recipient => $recipientName]);
  200. $template = $this->mailer->createEMailTemplate('dav.calendarInvite.' . $method, $data);
  201. $template->addHeader();
  202. $this->addSubjectAndHeading($template, $l10n, $method, $summary,
  203. $meetingAttendeeName, $meetingInviteeName);
  204. $this->addBulletList($template, $l10n, $meetingWhen, $meetingLocation,
  205. $meetingDescription, $meetingUrl);
  206. $this->addResponseButtons($template, $l10n, $iTipMessage, $lastOccurrence);
  207. $template->addFooter();
  208. $message->useTemplate($template);
  209. $attachment = $this->mailer->createAttachment(
  210. $iTipMessage->message->serialize(),
  211. 'event.ics',// TODO(leon): Make file name unique, e.g. add event id
  212. 'text/calendar; method=' . $iTipMessage->method
  213. );
  214. $message->attach($attachment);
  215. try {
  216. $failed = $this->mailer->send($message);
  217. $iTipMessage->scheduleStatus = '1.1; Scheduling message is sent via iMip';
  218. if ($failed) {
  219. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  220. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  221. }
  222. } catch(\Exception $ex) {
  223. $this->logger->logException($ex, ['app' => 'dav']);
  224. $iTipMessage->scheduleStatus = '5.0; EMail delivery failed';
  225. }
  226. }
  227. /**
  228. * check if event took place in the past already
  229. * @param VCalendar $vObject
  230. * @return int
  231. */
  232. private function getLastOccurrence(VCalendar $vObject) {
  233. /** @var VEvent $component */
  234. $component = $vObject->VEVENT;
  235. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  236. // Finding the last occurrence is a bit harder
  237. if (!isset($component->RRULE)) {
  238. if (isset($component->DTEND)) {
  239. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  240. } elseif (isset($component->DURATION)) {
  241. /** @var \DateTime $endDate */
  242. $endDate = clone $component->DTSTART->getDateTime();
  243. // $component->DTEND->getDateTime() returns DateTimeImmutable
  244. $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  245. $lastOccurrence = $endDate->getTimestamp();
  246. } elseif (!$component->DTSTART->hasTime()) {
  247. /** @var \DateTime $endDate */
  248. $endDate = clone $component->DTSTART->getDateTime();
  249. // $component->DTSTART->getDateTime() returns DateTimeImmutable
  250. $endDate = $endDate->modify('+1 day');
  251. $lastOccurrence = $endDate->getTimestamp();
  252. } else {
  253. $lastOccurrence = $firstOccurrence;
  254. }
  255. } else {
  256. $it = new EventIterator($vObject, (string)$component->UID);
  257. $maxDate = new \DateTime(self::MAX_DATE);
  258. if ($it->isInfinite()) {
  259. $lastOccurrence = $maxDate->getTimestamp();
  260. } else {
  261. $end = $it->getDtEnd();
  262. while($it->valid() && $end < $maxDate) {
  263. $end = $it->getDtEnd();
  264. $it->next();
  265. }
  266. $lastOccurrence = $end->getTimestamp();
  267. }
  268. }
  269. return $lastOccurrence;
  270. }
  271. /**
  272. * @param Message $iTipMessage
  273. * @return null|Property
  274. */
  275. private function getCurrentAttendee(Message $iTipMessage) {
  276. /** @var VEvent $vevent */
  277. $vevent = $iTipMessage->message->VEVENT;
  278. $attendees = $vevent->select('ATTENDEE');
  279. foreach ($attendees as $attendee) {
  280. /** @var Property $attendee */
  281. if (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  282. return $attendee;
  283. }
  284. }
  285. return null;
  286. }
  287. /**
  288. * @param string $default
  289. * @param Property|null $attendee
  290. * @return string
  291. */
  292. private function getAttendeeLangOrDefault($default, Property $attendee = null) {
  293. if ($attendee !== null) {
  294. $lang = $attendee->offsetGet('LANGUAGE');
  295. if ($lang instanceof Parameter) {
  296. return $lang->getValue();
  297. }
  298. }
  299. return $default;
  300. }
  301. /**
  302. * @param IL10N $l10n
  303. * @param Property $dtstart
  304. * @param Property $dtend
  305. */
  306. private function generateWhenString(IL10N $l10n, Property $dtstart, Property $dtend) {
  307. $isAllDay = $dtstart instanceof Property\ICalendar\Date;
  308. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
  309. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
  310. /** @var \DateTimeImmutable $dtstartDt */
  311. $dtstartDt = $dtstart->getDateTime();
  312. /** @var \DateTimeImmutable $dtendDt */
  313. $dtendDt = $dtend->getDateTime();
  314. $diff = $dtstartDt->diff($dtendDt);
  315. $dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
  316. $dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
  317. if ($isAllDay) {
  318. // One day event
  319. if ($diff->days === 1) {
  320. return $l10n->l('date', $dtstartDt, ['width' => 'medium']);
  321. }
  322. //event that spans over multiple days
  323. $localeStart = $l10n->l('date', $dtstartDt, ['width' => 'medium']);
  324. $localeEnd = $l10n->l('date', $dtendDt, ['width' => 'medium']);
  325. return $localeStart . ' - ' . $localeEnd;
  326. }
  327. /** @var Property\ICalendar\DateTime $dtstart */
  328. /** @var Property\ICalendar\DateTime $dtend */
  329. $isFloating = $dtstart->isFloating();
  330. $startTimezone = $endTimezone = null;
  331. if (!$isFloating) {
  332. $prop = $dtstart->offsetGet('TZID');
  333. if ($prop instanceof Parameter) {
  334. $startTimezone = $prop->getValue();
  335. }
  336. $prop = $dtend->offsetGet('TZID');
  337. if ($prop instanceof Parameter) {
  338. $endTimezone = $prop->getValue();
  339. }
  340. }
  341. $localeStart = $l10n->l('weekdayName', $dtstartDt, ['width' => 'abbreviated']) . ', ' .
  342. $l10n->l('datetime', $dtstartDt, ['width' => 'medium|short']);
  343. // always show full date with timezone if timezones are different
  344. if ($startTimezone !== $endTimezone) {
  345. $localeEnd = $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  346. return $localeStart . ' (' . $startTimezone . ') - ' .
  347. $localeEnd . ' (' . $endTimezone . ')';
  348. }
  349. // show only end time if date is the same
  350. if ($this->isDayEqual($dtstartDt, $dtendDt)) {
  351. $localeEnd = $l10n->l('time', $dtendDt, ['width' => 'short']);
  352. } else {
  353. $localeEnd = $l10n->l('weekdayName', $dtendDt, ['width' => 'abbreviated']) . ', ' .
  354. $l10n->l('datetime', $dtendDt, ['width' => 'medium|short']);
  355. }
  356. return $localeStart . ' - ' . $localeEnd . ' (' . $startTimezone . ')';
  357. }
  358. /**
  359. * @param \DateTime $dtStart
  360. * @param \DateTime $dtEnd
  361. * @return bool
  362. */
  363. private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) {
  364. return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
  365. }
  366. /**
  367. * @param IEMailTemplate $template
  368. * @param IL10N $l10n
  369. * @param string $method
  370. * @param string $summary
  371. * @param string $attendeeName
  372. * @param string $inviteeName
  373. */
  374. private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n,
  375. $method, $summary, $attendeeName, $inviteeName) {
  376. if ($method === self::METHOD_CANCEL) {
  377. $template->setSubject('Cancelled: ' . $summary);
  378. $template->addHeading($l10n->t('Invitation canceled'), $l10n->t('Hello %s,', [$attendeeName]));
  379. $template->addBodyText($l10n->t('The meeting »%1$s« with %2$s was canceled.', [$summary, $inviteeName]));
  380. } else if ($method === self::METHOD_REPLY) {
  381. $template->setSubject('Re: ' . $summary);
  382. $template->addHeading($l10n->t('Invitation updated'), $l10n->t('Hello %s,', [$attendeeName]));
  383. $template->addBodyText($l10n->t('The meeting »%1$s« with %2$s was updated.', [$summary, $inviteeName]));
  384. } else {
  385. $template->setSubject('Invitation: ' . $summary);
  386. $template->addHeading($l10n->t('%1$s invited you to »%2$s«', [$inviteeName, $summary]), $l10n->t('Hello %s,', [$attendeeName]));
  387. }
  388. }
  389. /**
  390. * @param IEMailTemplate $template
  391. * @param IL10N $l10n
  392. * @param string $time
  393. * @param string $location
  394. * @param string $description
  395. * @param string $url
  396. */
  397. private function addBulletList(IEMailTemplate $template, IL10N $l10n, $time, $location, $description, $url) {
  398. $template->addBodyListItem($time, $l10n->t('When:'),
  399. $this->getAbsoluteImagePath('filetypes/text-calendar.svg'));
  400. if ($location) {
  401. $template->addBodyListItem($location, $l10n->t('Where:'),
  402. $this->getAbsoluteImagePath('filetypes/location.svg'));
  403. }
  404. if ($description) {
  405. $template->addBodyListItem((string)$description, $l10n->t('Description:'),
  406. $this->getAbsoluteImagePath('filetypes/text.svg'));
  407. }
  408. if ($url) {
  409. $template->addBodyListItem((string)$url, $l10n->t('Link:'),
  410. $this->getAbsoluteImagePath('filetypes/link.svg'));
  411. }
  412. }
  413. /**
  414. * @param IEMailTemplate $template
  415. * @param IL10N $l10n
  416. * @param Message $iTipMessage
  417. * @param int $lastOccurrence
  418. */
  419. private function addResponseButtons(IEMailTemplate $template, IL10N $l10n,
  420. Message $iTipMessage, $lastOccurrence) {
  421. $token = $this->createInvitationToken($iTipMessage, $lastOccurrence);
  422. $template->addBodyButtonGroup(
  423. $l10n->t('Accept'),
  424. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
  425. 'token' => $token,
  426. ]),
  427. $l10n->t('Decline'),
  428. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
  429. 'token' => $token,
  430. ])
  431. );
  432. $moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
  433. 'token' => $token,
  434. ]);
  435. $html = vsprintf('<small><a href="%s">%s</a></small>', [
  436. $moreOptionsURL, $l10n->t('More options …')
  437. ]);
  438. $text = $l10n->t('More options at %s', [$moreOptionsURL]);
  439. $template->addBodyText($html, $text);
  440. }
  441. /**
  442. * @param string $path
  443. * @return string
  444. */
  445. private function getAbsoluteImagePath($path) {
  446. return $this->urlGenerator->getAbsoluteURL(
  447. $this->urlGenerator->imagePath('core', $path)
  448. );
  449. }
  450. /**
  451. * @param Message $iTipMessage
  452. * @param int $lastOccurrence
  453. * @return string
  454. */
  455. private function createInvitationToken(Message $iTipMessage, $lastOccurrence):string {
  456. $token = $this->random->generate(60, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  457. /** @var VEvent $vevent */
  458. $vevent = $iTipMessage->message->VEVENT;
  459. $attendee = $iTipMessage->recipient;
  460. $organizer = $iTipMessage->sender;
  461. $sequence = $iTipMessage->sequence;
  462. $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
  463. $vevent->{'RECURRENCE-ID'}->serialize() : null;
  464. $uid = $vevent->{'UID'};
  465. $query = $this->db->getQueryBuilder();
  466. $query->insert('calendar_invitations')
  467. ->values([
  468. 'token' => $query->createNamedParameter($token),
  469. 'attendee' => $query->createNamedParameter($attendee),
  470. 'organizer' => $query->createNamedParameter($organizer),
  471. 'sequence' => $query->createNamedParameter($sequence),
  472. 'recurrenceid' => $query->createNamedParameter($recurrenceId),
  473. 'expiration' => $query->createNamedParameter($lastOccurrence),
  474. 'uid' => $query->createNamedParameter($uid)
  475. ])
  476. ->execute();
  477. return $token;
  478. }
  479. }