EmailProvider.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV\Reminder\NotificationProvider;
  8. use DateTime;
  9. use OCP\IConfig;
  10. use OCP\IL10N;
  11. use OCP\IURLGenerator;
  12. use OCP\IUser;
  13. use OCP\L10N\IFactory as L10NFactory;
  14. use OCP\Mail\Headers\AutoSubmitted;
  15. use OCP\Mail\IEMailTemplate;
  16. use OCP\Mail\IMailer;
  17. use OCP\Util;
  18. use Psr\Log\LoggerInterface;
  19. use Sabre\VObject;
  20. use Sabre\VObject\Component\VEvent;
  21. use Sabre\VObject\Parameter;
  22. use Sabre\VObject\Property;
  23. /**
  24. * Class EmailProvider
  25. *
  26. * @package OCA\DAV\CalDAV\Reminder\NotificationProvider
  27. */
  28. class EmailProvider extends AbstractProvider {
  29. /** @var string */
  30. public const NOTIFICATION_TYPE = 'EMAIL';
  31. public function __construct(
  32. IConfig $config,
  33. private IMailer $mailer,
  34. LoggerInterface $logger,
  35. L10NFactory $l10nFactory,
  36. IURLGenerator $urlGenerator,
  37. ) {
  38. parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
  39. }
  40. /**
  41. * Send out notification via email
  42. *
  43. * @param VEvent $vevent
  44. * @param string|null $calendarDisplayName
  45. * @param string[] $principalEmailAddresses
  46. * @param array $users
  47. * @throws \Exception
  48. */
  49. public function send(VEvent $vevent,
  50. ?string $calendarDisplayName,
  51. array $principalEmailAddresses,
  52. array $users = []):void {
  53. $fallbackLanguage = $this->getFallbackLanguage();
  54. $organizerEmailAddress = null;
  55. if (isset($vevent->ORGANIZER)) {
  56. $organizerEmailAddress = $this->getEMailAddressOfAttendee($vevent->ORGANIZER);
  57. }
  58. $emailAddressesOfSharees = $this->getEMailAddressesOfAllUsersWithWriteAccessToCalendar($users);
  59. $emailAddressesOfAttendees = [];
  60. if (count($principalEmailAddresses) === 0
  61. || ($organizerEmailAddress && in_array($organizerEmailAddress, $principalEmailAddresses, true))
  62. ) {
  63. $emailAddressesOfAttendees = $this->getAllEMailAddressesFromEvent($vevent);
  64. }
  65. // Quote from php.net:
  66. // If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
  67. // => if there are duplicate email addresses, it will always take the system value
  68. $emailAddresses = array_merge(
  69. $emailAddressesOfAttendees,
  70. $emailAddressesOfSharees
  71. );
  72. $sortedByLanguage = $this->sortEMailAddressesByLanguage($emailAddresses, $fallbackLanguage);
  73. $organizer = $this->getOrganizerEMailAndNameFromEvent($vevent);
  74. foreach ($sortedByLanguage as $lang => $emailAddresses) {
  75. if (!$this->hasL10NForLang($lang)) {
  76. $lang = $fallbackLanguage;
  77. }
  78. $l10n = $this->getL10NForLang($lang);
  79. $fromEMail = Util::getDefaultEmailAddress('reminders-noreply');
  80. $template = $this->mailer->createEMailTemplate('dav.calendarReminder');
  81. $template->addHeader();
  82. $this->addSubjectAndHeading($template, $l10n, $vevent);
  83. $this->addBulletList($template, $l10n, $calendarDisplayName ?? $this->getCalendarDisplayNameFallback($lang), $vevent);
  84. $template->addFooter();
  85. foreach ($emailAddresses as $emailAddress) {
  86. if (!$this->mailer->validateMailAddress($emailAddress)) {
  87. $this->logger->error('Email address {address} for reminder notification is incorrect', ['app' => 'dav', 'address' => $emailAddress]);
  88. continue;
  89. }
  90. $message = $this->mailer->createMessage();
  91. $message->setFrom([$fromEMail]);
  92. if ($organizer) {
  93. $message->setReplyTo($organizer);
  94. }
  95. $message->setTo([$emailAddress]);
  96. $message->useTemplate($template);
  97. $message->setAutoSubmitted(AutoSubmitted::VALUE_AUTO_GENERATED);
  98. try {
  99. $failed = $this->mailer->send($message);
  100. if ($failed) {
  101. $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
  102. }
  103. } catch (\Exception $ex) {
  104. $this->logger->error($ex->getMessage(), ['app' => 'dav', 'exception' => $ex]);
  105. }
  106. }
  107. }
  108. }
  109. /**
  110. * @param IEMailTemplate $template
  111. * @param IL10N $l10n
  112. * @param VEvent $vevent
  113. */
  114. private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, VEvent $vevent):void {
  115. $template->setSubject('Notification: ' . $this->getTitleFromVEvent($vevent, $l10n));
  116. $template->addHeading($this->getTitleFromVEvent($vevent, $l10n));
  117. }
  118. /**
  119. * @param IEMailTemplate $template
  120. * @param IL10N $l10n
  121. * @param string $calendarDisplayName
  122. * @param array $eventData
  123. */
  124. private function addBulletList(IEMailTemplate $template,
  125. IL10N $l10n,
  126. string $calendarDisplayName,
  127. VEvent $vevent):void {
  128. $template->addBodyListItem($calendarDisplayName, $l10n->t('Calendar:'),
  129. $this->getAbsoluteImagePath('actions/info.png'));
  130. $template->addBodyListItem($this->generateDateString($l10n, $vevent), $l10n->t('Date:'),
  131. $this->getAbsoluteImagePath('places/calendar.png'));
  132. if (isset($vevent->LOCATION)) {
  133. $template->addBodyListItem((string)$vevent->LOCATION, $l10n->t('Where:'),
  134. $this->getAbsoluteImagePath('actions/address.png'));
  135. }
  136. if (isset($vevent->DESCRIPTION)) {
  137. $template->addBodyListItem((string)$vevent->DESCRIPTION, $l10n->t('Description:'),
  138. $this->getAbsoluteImagePath('actions/more.png'));
  139. }
  140. }
  141. private function getAbsoluteImagePath(string $path):string {
  142. return $this->urlGenerator->getAbsoluteURL(
  143. $this->urlGenerator->imagePath('core', $path)
  144. );
  145. }
  146. /**
  147. * @param VEvent $vevent
  148. * @return array|null
  149. */
  150. private function getOrganizerEMailAndNameFromEvent(VEvent $vevent):?array {
  151. if (!$vevent->ORGANIZER) {
  152. return null;
  153. }
  154. $organizer = $vevent->ORGANIZER;
  155. if (strcasecmp($organizer->getValue(), 'mailto:') !== 0) {
  156. return null;
  157. }
  158. $organizerEMail = substr($organizer->getValue(), 7);
  159. if (!$this->mailer->validateMailAddress($organizerEMail)) {
  160. return null;
  161. }
  162. $name = $organizer->offsetGet('CN');
  163. if ($name instanceof Parameter) {
  164. return [$organizerEMail => $name];
  165. }
  166. return [$organizerEMail];
  167. }
  168. /**
  169. * @param array<string, array{LANG?: string}> $emails
  170. * @return array<string, string[]>
  171. */
  172. private function sortEMailAddressesByLanguage(array $emails,
  173. string $defaultLanguage):array {
  174. $sortedByLanguage = [];
  175. foreach ($emails as $emailAddress => $parameters) {
  176. if (isset($parameters['LANG'])) {
  177. $lang = $parameters['LANG'];
  178. } else {
  179. $lang = $defaultLanguage;
  180. }
  181. if (!isset($sortedByLanguage[$lang])) {
  182. $sortedByLanguage[$lang] = [];
  183. }
  184. $sortedByLanguage[$lang][] = $emailAddress;
  185. }
  186. return $sortedByLanguage;
  187. }
  188. /**
  189. * @param VEvent $vevent
  190. * @return array<string, array{LANG?: string}>
  191. */
  192. private function getAllEMailAddressesFromEvent(VEvent $vevent):array {
  193. $emailAddresses = [];
  194. if (isset($vevent->ATTENDEE)) {
  195. foreach ($vevent->ATTENDEE as $attendee) {
  196. if (!($attendee instanceof VObject\Property)) {
  197. continue;
  198. }
  199. $cuType = $this->getCUTypeOfAttendee($attendee);
  200. if (\in_array($cuType, ['RESOURCE', 'ROOM', 'UNKNOWN'])) {
  201. // Don't send emails to things
  202. continue;
  203. }
  204. $partstat = $this->getPartstatOfAttendee($attendee);
  205. if ($partstat === 'DECLINED') {
  206. // Don't send out emails to people who declined
  207. continue;
  208. }
  209. if ($partstat === 'DELEGATED') {
  210. $delegates = $attendee->offsetGet('DELEGATED-TO');
  211. if (!($delegates instanceof VObject\Parameter)) {
  212. continue;
  213. }
  214. $emailAddressesOfDelegates = $delegates->getParts();
  215. foreach ($emailAddressesOfDelegates as $addressesOfDelegate) {
  216. if (strcasecmp($addressesOfDelegate, 'mailto:') === 0) {
  217. $delegateEmail = substr($addressesOfDelegate, 7);
  218. if ($this->mailer->validateMailAddress($delegateEmail)) {
  219. $emailAddresses[$delegateEmail] = [];
  220. }
  221. }
  222. }
  223. continue;
  224. }
  225. $emailAddressOfAttendee = $this->getEMailAddressOfAttendee($attendee);
  226. if ($emailAddressOfAttendee !== null) {
  227. $properties = [];
  228. $langProp = $attendee->offsetGet('LANG');
  229. if ($langProp instanceof VObject\Parameter && $langProp->getValue() !== null) {
  230. $properties['LANG'] = $langProp->getValue();
  231. }
  232. $emailAddresses[$emailAddressOfAttendee] = $properties;
  233. }
  234. }
  235. }
  236. if (isset($vevent->ORGANIZER) && $this->hasAttendeeMailURI($vevent->ORGANIZER)) {
  237. $organizerEmailAddress = $this->getEMailAddressOfAttendee($vevent->ORGANIZER);
  238. if ($organizerEmailAddress !== null) {
  239. $emailAddresses[$organizerEmailAddress] = [];
  240. }
  241. }
  242. return $emailAddresses;
  243. }
  244. private function getCUTypeOfAttendee(VObject\Property $attendee):string {
  245. $cuType = $attendee->offsetGet('CUTYPE');
  246. if ($cuType instanceof VObject\Parameter) {
  247. return strtoupper($cuType->getValue());
  248. }
  249. return 'INDIVIDUAL';
  250. }
  251. private function getPartstatOfAttendee(VObject\Property $attendee):string {
  252. $partstat = $attendee->offsetGet('PARTSTAT');
  253. if ($partstat instanceof VObject\Parameter) {
  254. return strtoupper($partstat->getValue());
  255. }
  256. return 'NEEDS-ACTION';
  257. }
  258. private function hasAttendeeMailURI(VObject\Property $attendee): bool {
  259. return stripos($attendee->getValue(), 'mailto:') === 0;
  260. }
  261. private function getEMailAddressOfAttendee(VObject\Property $attendee): ?string {
  262. if (!$this->hasAttendeeMailURI($attendee)) {
  263. return null;
  264. }
  265. $attendeeEMail = substr($attendee->getValue(), 7);
  266. if (!$this->mailer->validateMailAddress($attendeeEMail)) {
  267. return null;
  268. }
  269. return $attendeeEMail;
  270. }
  271. /**
  272. * @param IUser[] $users
  273. * @return array<string, array{LANG?: string}>
  274. */
  275. private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $users):array {
  276. $emailAddresses = [];
  277. foreach ($users as $user) {
  278. $emailAddress = $user->getEMailAddress();
  279. if ($emailAddress) {
  280. $lang = $this->l10nFactory->getUserLanguage($user);
  281. if ($lang) {
  282. $emailAddresses[$emailAddress] = [
  283. 'LANG' => $lang,
  284. ];
  285. } else {
  286. $emailAddresses[$emailAddress] = [];
  287. }
  288. }
  289. }
  290. return $emailAddresses;
  291. }
  292. /**
  293. * @throws \Exception
  294. */
  295. private function generateDateString(IL10N $l10n, VEvent $vevent): string {
  296. $isAllDay = $vevent->DTSTART instanceof Property\ICalendar\Date;
  297. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */
  298. /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */
  299. /** @var \DateTimeImmutable $dtstartDt */
  300. $dtstartDt = $vevent->DTSTART->getDateTime();
  301. /** @var \DateTimeImmutable $dtendDt */
  302. $dtendDt = $this->getDTEndFromEvent($vevent)->getDateTime();
  303. $diff = $dtstartDt->diff($dtendDt);
  304. $dtstartDt = new \DateTime($dtstartDt->format(\DateTimeInterface::ATOM));
  305. $dtendDt = new \DateTime($dtendDt->format(\DateTimeInterface::ATOM));
  306. if ($isAllDay) {
  307. // One day event
  308. if ($diff->days === 1) {
  309. return $this->getDateString($l10n, $dtstartDt);
  310. }
  311. return implode(' - ', [
  312. $this->getDateString($l10n, $dtstartDt),
  313. $this->getDateString($l10n, $dtendDt),
  314. ]);
  315. }
  316. $startTimezone = $endTimezone = null;
  317. if (!$vevent->DTSTART->isFloating()) {
  318. $startTimezone = $vevent->DTSTART->getDateTime()->getTimezone()->getName();
  319. $endTimezone = $this->getDTEndFromEvent($vevent)->getDateTime()->getTimezone()->getName();
  320. }
  321. $localeStart = implode(', ', [
  322. $this->getWeekDayName($l10n, $dtstartDt),
  323. $this->getDateTimeString($l10n, $dtstartDt)
  324. ]);
  325. // always show full date with timezone if timezones are different
  326. if ($startTimezone !== $endTimezone) {
  327. $localeEnd = implode(', ', [
  328. $this->getWeekDayName($l10n, $dtendDt),
  329. $this->getDateTimeString($l10n, $dtendDt)
  330. ]);
  331. return $localeStart
  332. . ' (' . $startTimezone . ') '
  333. . ' - '
  334. . $localeEnd
  335. . ' (' . $endTimezone . ')';
  336. }
  337. // Show only the time if the day is the same
  338. $localeEnd = $this->isDayEqual($dtstartDt, $dtendDt)
  339. ? $this->getTimeString($l10n, $dtendDt)
  340. : implode(', ', [
  341. $this->getWeekDayName($l10n, $dtendDt),
  342. $this->getDateTimeString($l10n, $dtendDt)
  343. ]);
  344. return $localeStart
  345. . ' - '
  346. . $localeEnd
  347. . ' (' . $startTimezone . ')';
  348. }
  349. private function isDayEqual(DateTime $dtStart,
  350. DateTime $dtEnd):bool {
  351. return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d');
  352. }
  353. private function getWeekDayName(IL10N $l10n, DateTime $dt):string {
  354. return (string)$l10n->l('weekdayName', $dt, ['width' => 'abbreviated']);
  355. }
  356. private function getDateString(IL10N $l10n, DateTime $dt):string {
  357. return (string)$l10n->l('date', $dt, ['width' => 'medium']);
  358. }
  359. private function getDateTimeString(IL10N $l10n, DateTime $dt):string {
  360. return (string)$l10n->l('datetime', $dt, ['width' => 'medium|short']);
  361. }
  362. private function getTimeString(IL10N $l10n, DateTime $dt):string {
  363. return (string)$l10n->l('time', $dt, ['width' => 'short']);
  364. }
  365. private function getTitleFromVEvent(VEvent $vevent, IL10N $l10n):string {
  366. if (isset($vevent->SUMMARY)) {
  367. return (string)$vevent->SUMMARY;
  368. }
  369. return $l10n->t('Untitled event');
  370. }
  371. }