EmailProvider.php 14 KB

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