EmailProvider.php 14 KB

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