1
0

IMipService.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CalDAV\Schedule;
  8. use OC\URLGenerator;
  9. use OCA\DAV\CalDAV\EventReader;
  10. use OCP\AppFramework\Utility\ITimeFactory;
  11. use OCP\IConfig;
  12. use OCP\IDBConnection;
  13. use OCP\IL10N;
  14. use OCP\L10N\IFactory as L10NFactory;
  15. use OCP\Mail\IEMailTemplate;
  16. use OCP\Security\ISecureRandom;
  17. use Sabre\VObject\Component\VCalendar;
  18. use Sabre\VObject\Component\VEvent;
  19. use Sabre\VObject\DateTimeParser;
  20. use Sabre\VObject\ITip\Message;
  21. use Sabre\VObject\Parameter;
  22. use Sabre\VObject\Property;
  23. use Sabre\VObject\Recur\EventIterator;
  24. class IMipService {
  25. private URLGenerator $urlGenerator;
  26. private IConfig $config;
  27. private IDBConnection $db;
  28. private ISecureRandom $random;
  29. private L10NFactory $l10nFactory;
  30. private IL10N $l10n;
  31. private ITimeFactory $timeFactory;
  32. /** @var string[] */
  33. private const STRING_DIFF = [
  34. 'meeting_title' => 'SUMMARY',
  35. 'meeting_description' => 'DESCRIPTION',
  36. 'meeting_url' => 'URL',
  37. 'meeting_location' => 'LOCATION'
  38. ];
  39. public function __construct(URLGenerator $urlGenerator,
  40. IConfig $config,
  41. IDBConnection $db,
  42. ISecureRandom $random,
  43. L10NFactory $l10nFactory,
  44. ITimeFactory $timeFactory) {
  45. $this->urlGenerator = $urlGenerator;
  46. $this->config = $config;
  47. $this->db = $db;
  48. $this->random = $random;
  49. $this->l10nFactory = $l10nFactory;
  50. $default = $this->l10nFactory->findGenericLanguage();
  51. $this->l10n = $this->l10nFactory->get('dav', $default);
  52. $this->timeFactory = $timeFactory;
  53. }
  54. /**
  55. * @param string|null $senderName
  56. * @param string $default
  57. * @return string
  58. */
  59. public function getFrom(?string $senderName, string $default): string {
  60. if ($senderName === null) {
  61. return $default;
  62. }
  63. return $this->l10n->t('%1$s via %2$s', [$senderName, $default]);
  64. }
  65. public static function readPropertyWithDefault(VEvent $vevent, string $property, string $default) {
  66. if (isset($vevent->$property)) {
  67. $value = $vevent->$property->getValue();
  68. if (!empty($value)) {
  69. return $value;
  70. }
  71. }
  72. return $default;
  73. }
  74. private function generateDiffString(VEvent $vevent, VEvent $oldVEvent, string $property, string $default): ?string {
  75. $strikethrough = "<span style='text-decoration: line-through'>%s</span><br />%s";
  76. if (!isset($vevent->$property)) {
  77. return $default;
  78. }
  79. $newstring = $vevent->$property->getValue();
  80. if(isset($oldVEvent->$property) && $oldVEvent->$property->getValue() !== $newstring) {
  81. $oldstring = $oldVEvent->$property->getValue();
  82. return sprintf($strikethrough, $oldstring, $newstring);
  83. }
  84. return $newstring;
  85. }
  86. /**
  87. * Like generateDiffString() but linkifies the property values if they are urls.
  88. */
  89. private function generateLinkifiedDiffString(VEvent $vevent, VEvent $oldVEvent, string $property, string $default): ?string {
  90. if (!isset($vevent->$property)) {
  91. return $default;
  92. }
  93. /** @var string|null $newString */
  94. $newString = $vevent->$property->getValue();
  95. $oldString = isset($oldVEvent->$property) ? $oldVEvent->$property->getValue() : null;
  96. if ($oldString !== $newString) {
  97. return sprintf(
  98. "<span style='text-decoration: line-through'>%s</span><br />%s",
  99. $this->linkify($oldString) ?? $oldString ?? '',
  100. $this->linkify($newString) ?? $newString ?? ''
  101. );
  102. }
  103. return $this->linkify($newString) ?? $newString;
  104. }
  105. /**
  106. * Convert a given url to a html link element or return null otherwise.
  107. */
  108. private function linkify(?string $url): ?string {
  109. if ($url === null) {
  110. return null;
  111. }
  112. if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
  113. return null;
  114. }
  115. return sprintf('<a href="%1$s">%1$s</a>', htmlspecialchars($url));
  116. }
  117. /**
  118. * @param VEvent $vEvent
  119. * @param VEvent|null $oldVEvent
  120. * @return array
  121. */
  122. public function buildBodyData(VEvent $vEvent, ?VEvent $oldVEvent): array {
  123. // construct event reader
  124. $eventReaderCurrent = new EventReader($vEvent);
  125. $eventReaderPrevious = !empty($oldVEvent) ? new EventReader($oldVEvent) : null;
  126. $defaultVal = '';
  127. $data = [];
  128. $data['meeting_when'] = $this->generateWhenString($eventReaderCurrent);
  129. foreach(self::STRING_DIFF as $key => $property) {
  130. $data[$key] = self::readPropertyWithDefault($vEvent, $property, $defaultVal);
  131. }
  132. $data['meeting_url_html'] = self::readPropertyWithDefault($vEvent, 'URL', $defaultVal);
  133. if (($locationHtml = $this->linkify($data['meeting_location'])) !== null) {
  134. $data['meeting_location_html'] = $locationHtml;
  135. }
  136. if(!empty($oldVEvent)) {
  137. $oldMeetingWhen = $this->generateWhenString($eventReaderPrevious);
  138. $data['meeting_title_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'SUMMARY', $data['meeting_title']);
  139. $data['meeting_description_html'] = $this->generateDiffString($vEvent, $oldVEvent, 'DESCRIPTION', $data['meeting_description']);
  140. $data['meeting_location_html'] = $this->generateLinkifiedDiffString($vEvent, $oldVEvent, 'LOCATION', $data['meeting_location']);
  141. $oldUrl = self::readPropertyWithDefault($oldVEvent, 'URL', $defaultVal);
  142. $data['meeting_url_html'] = !empty($oldUrl) && $oldUrl !== $data['meeting_url'] ? sprintf('<a href="%1$s">%1$s</a>', $oldUrl) : $data['meeting_url'];
  143. $data['meeting_when_html'] = $oldMeetingWhen !== $data['meeting_when'] ? sprintf("<span style='text-decoration: line-through'>%s</span><br />%s", $oldMeetingWhen, $data['meeting_when']) : $data['meeting_when'];
  144. }
  145. // generate occuring next string
  146. if ($eventReaderCurrent->recurs()) {
  147. $data['meeting_occurring'] = $this->generateOccurringString($eventReaderCurrent);
  148. }
  149. return $data;
  150. }
  151. /**
  152. * genarates a when string based on if a event has an recurrence or not
  153. *
  154. * @since 30.0.0
  155. *
  156. * @param EventReader $er
  157. *
  158. * @return string
  159. */
  160. public function generateWhenString(EventReader $er): string {
  161. return match ($er->recurs()) {
  162. true => $this->generateWhenStringRecurring($er),
  163. false => $this->generateWhenStringSingular($er)
  164. };
  165. }
  166. /**
  167. * genarates a when string for a non recurring event
  168. *
  169. * @since 30.0.0
  170. *
  171. * @param EventReader $er
  172. *
  173. * @return string
  174. */
  175. public function generateWhenStringSingular(EventReader $er): string {
  176. // calculate time differnce from now to start of event
  177. $occuring = $this->minimizeInterval($this->timeFactory->getDateTime()->diff($er->recurrenceDate()));
  178. // extract start date
  179. $startDate = $this->l10n->l('date', $er->startDateTime(), ['width' => 'full']);
  180. // time of the day
  181. if (!$er->entireDay()) {
  182. $startTime = $this->l10n->l('time', $er->startDateTime(), ['width' => 'short']);
  183. $startTime .= $er->startTimeZone() != $er->endTimeZone() ? ' (' . $er->startTimeZone()->getName() . ')' : '';
  184. $endTime = $this->l10n->l('time', $er->endDateTime(), ['width' => 'short']) . ' (' . $er->endTimeZone()->getName() . ')';
  185. }
  186. // generate localized when string
  187. // TRANSLATORS
  188. // Indicates when a calendar event will happen, shown on invitation emails
  189. // Output produced in order:
  190. // In a day/week/month/year on July 1, 2024 for the entire day
  191. // In a day/week/month/year on July 1, 2024 between 8:00 AM - 9:00 AM (America/Toronto)
  192. // In 2 days/weeks/monthss/years on July 1, 2024 for the entire day
  193. // In 2 days/weeks/monthss/years on July 1, 2024 between 8:00 AM - 9:00 AM (America/Toronto)
  194. return match ([($occuring[0] > 1), !empty($endTime)]) {
  195. [false, false] => $this->l10n->t('In a %1$s on %2$s for the entire day', [$occuring[1], $startDate]),
  196. [false, true] => $this->l10n->t('In a %1$s on %2$s between %3$s - %4$s', [$occuring[1], $startDate, $startTime, $endTime]),
  197. [true, false] => $this->l10n->t('In %1$s %2$s on %3$s for the entire day', [$occuring[0], $occuring[1], $startDate]),
  198. [true, true] => $this->l10n->t('In %1$s %2$s on %3$s between %4$s - %5$s', [$occuring[0], $occuring[1], $startDate, $startTime, $endTime]),
  199. default => $this->l10n->t('Could not generate when statement')
  200. };
  201. }
  202. /**
  203. * genarates a when string based on recurrance precision/frequency
  204. *
  205. * @since 30.0.0
  206. *
  207. * @param EventReader $er
  208. *
  209. * @return string
  210. */
  211. public function generateWhenStringRecurring(EventReader $er): string {
  212. return match ($er->recurringPrecision()) {
  213. 'daily' => $this->generateWhenStringRecurringDaily($er),
  214. 'weekly' => $this->generateWhenStringRecurringWeekly($er),
  215. 'monthly' => $this->generateWhenStringRecurringMonthly($er),
  216. 'yearly' => $this->generateWhenStringRecurringYearly($er),
  217. 'fixed' => $this->generateWhenStringRecurringFixed($er),
  218. };
  219. }
  220. /**
  221. * genarates a when string for a daily precision/frequency
  222. *
  223. * @since 30.0.0
  224. *
  225. * @param EventReader $er
  226. *
  227. * @return string
  228. */
  229. public function generateWhenStringRecurringDaily(EventReader $er): string {
  230. // initialize
  231. $interval = (int)$er->recurringInterval();
  232. $startTime = '';
  233. $endTime = '';
  234. $conclusion = '';
  235. // time of the day
  236. if (!$er->entireDay()) {
  237. $startTime = $this->l10n->l('time', $er->startDateTime(), ['width' => 'short']);
  238. $startTime .= $er->startTimeZone() != $er->endTimeZone() ? ' (' . $er->startTimeZone()->getName() . ')' : '';
  239. $endTime = $this->l10n->l('time', $er->endDateTime(), ['width' => 'short']) . ' (' . $er->endTimeZone()->getName() . ')';
  240. }
  241. // conclusion
  242. if ($er->recurringConcludes()) {
  243. $conclusion = $this->l10n->l('date', $er->recurringConcludesOn(), ['width' => 'long']);
  244. }
  245. // generate localized when string
  246. // TRANSLATORS
  247. // Indicates when a calendar event will happen, shown on invitation emails
  248. // Output produced in order:
  249. // Every Day for the entire day
  250. // Every Day for the entire day until July 13, 2024
  251. // Every Day between 8:00 AM - 9:00 AM (America/Toronto)
  252. // Every Day between 8:00 AM - 9:00 AM (America/Toronto) until July 13, 2024
  253. // Every 3 Days for the entire day
  254. // Every 3 Days for the entire day until July 13, 2024
  255. // Every 3 Days between 8:00 AM - 9:00 AM (America/Toronto)
  256. // Every 3 Days between 8:00 AM - 9:00 AM (America/Toronto) until July 13, 2024
  257. return match ([($interval > 1), !empty($startTime), !empty($conclusion)]) {
  258. [false, false, false] => $this->l10n->t('Every Day for the entire day'),
  259. [false, false, true] => $this->l10n->t('Every Day for the entire day until %1$s', [$conclusion]),
  260. [false, true, false] => $this->l10n->t('Every Day between %1$s - %2$s', [$startTime, $endTime]),
  261. [false, true, true] => $this->l10n->t('Every Day between %1$s - %2$s until %3$s', [$startTime, $endTime, $conclusion]),
  262. [true, false, false] => $this->l10n->t('Every %1$d Days for the entire day', [$interval]),
  263. [true, false, true] => $this->l10n->t('Every %1$d Days for the entire day until %2$s', [$interval, $conclusion]),
  264. [true, true, false] => $this->l10n->t('Every %1$d Days between %2$s - %3$s', [$interval, $startTime, $endTime]),
  265. [true, true, true] => $this->l10n->t('Every %1$d Days between %2$s - %3$s until %4$s', [$interval, $startTime, $endTime, $conclusion]),
  266. default => $this->l10n->t('Could not generate event recurrence statement')
  267. };
  268. }
  269. /**
  270. * genarates a when string for a weekly precision/frequency
  271. *
  272. * @since 30.0.0
  273. *
  274. * @param EventReader $er
  275. *
  276. * @return string
  277. */
  278. public function generateWhenStringRecurringWeekly(EventReader $er): string {
  279. // initialize
  280. $interval = (int)$er->recurringInterval();
  281. $startTime = '';
  282. $endTime = '';
  283. $conclusion = '';
  284. // days of the week
  285. $days = implode(', ', array_map(function ($value) { return $this->localizeDayName($value); }, $er->recurringDaysOfWeekNamed()));
  286. // time of the day
  287. if (!$er->entireDay()) {
  288. $startTime = $this->l10n->l('time', $er->startDateTime(), ['width' => 'short']);
  289. $startTime .= $er->startTimeZone() != $er->endTimeZone() ? ' (' . $er->startTimeZone()->getName() . ')' : '';
  290. $endTime = $this->l10n->l('time', $er->endDateTime(), ['width' => 'short']) . ' (' . $er->endTimeZone()->getName() . ')';
  291. }
  292. // conclusion
  293. if ($er->recurringConcludes()) {
  294. $conclusion = $this->l10n->l('date', $er->recurringConcludesOn(), ['width' => 'long']);
  295. }
  296. // generate localized when string
  297. // TRANSLATORS
  298. // Indicates when a calendar event will happen, shown on invitation emails
  299. // Output produced in order:
  300. // Every Week on Monday, Wednesday, Friday for the entire day
  301. // Every Week on Monday, Wednesday, Friday for the entire day until July 13, 2024
  302. // Every Week on Monday, Wednesday, Friday between 8:00 AM - 9:00 AM (America/Toronto)
  303. // Every Week on Monday, Wednesday, Friday between 8:00 AM - 9:00 AM (America/Toronto) until July 13, 2024
  304. // Every 2 Weeks on Monday, Wednesday, Friday for the entire day
  305. // Every 2 Weeks on Monday, Wednesday, Friday for the entire day until July 13, 2024
  306. // Every 2 Weeks on Monday, Wednesday, Friday between 8:00 AM - 9:00 AM (America/Toronto)
  307. // Every 2 Weeks on Monday, Wednesday, Friday between 8:00 AM - 9:00 AM (America/Toronto) until July 13, 2024
  308. return match ([($interval > 1), !empty($startTime), !empty($conclusion)]) {
  309. [false, false, false] => $this->l10n->t('Every Week on %1$s for the entire day', [$days]),
  310. [false, false, true] => $this->l10n->t('Every Week on %1$s for the entire day until %2$s', [$days, $conclusion]),
  311. [false, true, false] => $this->l10n->t('Every Week on %1$s between %2$s - %3$s', [$days, $startTime, $endTime]),
  312. [false, true, true] => $this->l10n->t('Every Week on %1$s between %2$s - %3$s until %4$s', [$days, $startTime, $endTime, $conclusion]),
  313. [true, false, false] => $this->l10n->t('Every %1$d Weeks on %2$s for the entire day', [$interval, $days]),
  314. [true, false, true] => $this->l10n->t('Every %1$d Weeks on %2$s for the entire day until %3$s', [$interval, $days, $conclusion]),
  315. [true, true, false] => $this->l10n->t('Every %1$d Weeks on %2$s between %3$s - %4$s', [$interval, $days, $startTime, $endTime]),
  316. [true, true, true] => $this->l10n->t('Every %1$d Weeks on %2$s between %3$s - %4$s until %5$s', [$interval, $days, $startTime, $endTime, $conclusion]),
  317. default => $this->l10n->t('Could not generate event recurrence statement')
  318. };
  319. }
  320. /**
  321. * genarates a when string for a monthly precision/frequency
  322. *
  323. * @since 30.0.0
  324. *
  325. * @param EventReader $er
  326. *
  327. * @return string
  328. */
  329. public function generateWhenStringRecurringMonthly(EventReader $er): string {
  330. // initialize
  331. $interval = (int)$er->recurringInterval();
  332. $startTime = '';
  333. $endTime = '';
  334. $conclusion = '';
  335. // days of month
  336. if ($er->recurringPattern() === 'R') {
  337. $days = implode(', ', array_map(function ($value) { return $this->localizeRelativePositionName($value); }, $er->recurringRelativePositionNamed())) . ' ' .
  338. implode(', ', array_map(function ($value) { return $this->localizeDayName($value); }, $er->recurringDaysOfWeekNamed()));
  339. } else {
  340. $days = implode(', ', $er->recurringDaysOfMonth());
  341. }
  342. // time of the day
  343. if (!$er->entireDay()) {
  344. $startTime = $this->l10n->l('time', $er->startDateTime(), ['width' => 'short']);
  345. $startTime .= $er->startTimeZone() != $er->endTimeZone() ? ' (' . $er->startTimeZone()->getName() . ')' : '';
  346. $endTime = $this->l10n->l('time', $er->endDateTime(), ['width' => 'short']) . ' (' . $er->endTimeZone()->getName() . ')';
  347. }
  348. // conclusion
  349. if ($er->recurringConcludes()) {
  350. $conclusion = $this->l10n->l('date', $er->recurringConcludesOn(), ['width' => 'long']);
  351. }
  352. // generate localized when string
  353. // TRANSLATORS
  354. // Indicates when a calendar event will happen, shown on invitation emails
  355. // Output produced in order, output varies depending on if the event is absolute or releative:
  356. // Absolute: Every Month on the 1, 8 for the entire day
  357. // Relative: Every Month on the First Sunday, Saturday for the entire day
  358. // Absolute: Every Month on the 1, 8 for the entire day until December 31, 2024
  359. // Relative: Every Month on the First Sunday, Saturday for the entire day until December 31, 2024
  360. // Absolute: Every Month on the 1, 8 between 8:00 AM - 9:00 AM (America/Toronto)
  361. // Relative: Every Month on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto)
  362. // Absolute: Every Month on the 1, 8 between 8:00 AM - 9:00 AM (America/Toronto) until December 31, 2024
  363. // Relative: Every Month on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto) until December 31, 2024
  364. // Absolute: Every 2 Months on the 1, 8 for the entire day
  365. // Relative: Every 2 Months on the First Sunday, Saturday for the entire day
  366. // Absolute: Every 2 Months on the 1, 8 for the entire day until December 31, 2024
  367. // Relative: Every 2 Months on the First Sunday, Saturday for the entire day until December 31, 2024
  368. // Absolute: Every 2 Months on the 1, 8 between 8:00 AM - 9:00 AM (America/Toronto)
  369. // Relative: Every 2 Months on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto)
  370. // Absolute: Every 2 Months on the 1, 8 between 8:00 AM - 9:00 AM (America/Toronto) until December 31, 2024
  371. // Relative: Every 2 Months on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto) until December 31, 2024
  372. return match ([($interval > 1), !empty($startTime), !empty($conclusion)]) {
  373. [false, false, false] => $this->l10n->t('Every Month on the %1$s for the entire day', [$days]),
  374. [false, false, true] => $this->l10n->t('Every Month on the %1$s for the entire day until %2$s', [$days, $conclusion]),
  375. [false, true, false] => $this->l10n->t('Every Month on the %1$s between %2$s - %3$s', [$days, $startTime, $endTime]),
  376. [false, true, true] => $this->l10n->t('Every Month on the %1$s between %2$s - %3$s until %4$s', [$days, $startTime, $endTime, $conclusion]),
  377. [true, false, false] => $this->l10n->t('Every %1$d Months on the %2$s for the entire day', [$interval, $days]),
  378. [true, false, true] => $this->l10n->t('Every %1$d Months on the %2$s for the entire day until %3$s', [$interval, $days, $conclusion]),
  379. [true, true, false] => $this->l10n->t('Every %1$d Months on the %2$s between %3$s - %4$s', [$interval, $days, $startTime, $endTime]),
  380. [true, true, true] => $this->l10n->t('Every %1$d Months on the %2$s between %3$s - %4$s until %5$s', [$interval, $days, $startTime, $endTime, $conclusion]),
  381. default => $this->l10n->t('Could not generate event recurrence statement')
  382. };
  383. }
  384. /**
  385. * genarates a when string for a yearly precision/frequency
  386. *
  387. * @since 30.0.0
  388. *
  389. * @param EventReader $er
  390. *
  391. * @return string
  392. */
  393. public function generateWhenStringRecurringYearly(EventReader $er): string {
  394. // initialize
  395. $interval = (int)$er->recurringInterval();
  396. $startTime = '';
  397. $endTime = '';
  398. $conclusion = '';
  399. // months of year
  400. $months = implode(', ', array_map(function ($value) { return $this->localizeMonthName($value); }, $er->recurringMonthsOfYearNamed()));
  401. // days of month
  402. if ($er->recurringPattern() === 'R') {
  403. $days = implode(', ', array_map(function ($value) { return $this->localizeRelativePositionName($value); }, $er->recurringRelativePositionNamed())) . ' ' .
  404. implode(', ', array_map(function ($value) { return $this->localizeDayName($value); }, $er->recurringDaysOfWeekNamed()));
  405. } else {
  406. $days = $er->startDateTime()->format('jS');
  407. }
  408. // time of the day
  409. if (!$er->entireDay()) {
  410. $startTime = $this->l10n->l('time', $er->startDateTime(), ['width' => 'short']);
  411. $startTime .= $er->startTimeZone() != $er->endTimeZone() ? ' (' . $er->startTimeZone()->getName() . ')' : '';
  412. $endTime = $this->l10n->l('time', $er->endDateTime(), ['width' => 'short']) . ' (' . $er->endTimeZone()->getName() . ')';
  413. }
  414. // conclusion
  415. if ($er->recurringConcludes()) {
  416. $conclusion = $this->l10n->l('date', $er->recurringConcludesOn(), ['width' => 'long']);
  417. }
  418. // generate localized when string
  419. // TRANSLATORS
  420. // Indicates when a calendar event will happen, shown on invitation emails
  421. // Output produced in order, output varies depending on if the event is absolute or releative:
  422. // Absolute: Every Year in July on the 1st for the entire day
  423. // Relative: Every Year in July on the First Sunday, Saturday for the entire day
  424. // Absolute: Every Year in July on the 1st for the entire day until July 31, 2026
  425. // Relative: Every Year in July on the First Sunday, Saturday for the entire day until July 31, 2026
  426. // Absolute: Every Year in July on the 1st between 8:00 AM - 9:00 AM (America/Toronto)
  427. // Relative: Every Year in July on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto)
  428. // Absolute: Every Year in July on the 1st between 8:00 AM - 9:00 AM (America/Toronto) until July 31, 2026
  429. // Relative: Every Year in July on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto) until July 31, 2026
  430. // Absolute: Every 2 Years in July on the 1st for the entire day
  431. // Relative: Every 2 Years in July on the First Sunday, Saturday for the entire day
  432. // Absolute: Every 2 Years in July on the 1st for the entire day until July 31, 2026
  433. // Relative: Every 2 Years in July on the First Sunday, Saturday for the entire day until July 31, 2026
  434. // Absolute: Every 2 Years in July on the 1st between 8:00 AM - 9:00 AM (America/Toronto)
  435. // Relative: Every 2 Years in July on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto)
  436. // Absolute: Every 2 Years in July on the 1st between 8:00 AM - 9:00 AM (America/Toronto) until July 31, 2026
  437. // Relative: Every 2 Years in July on the First Sunday, Saturday between 8:00 AM - 9:00 AM (America/Toronto) until July 31, 2026
  438. return match ([($interval > 1), !empty($startTime), !empty($conclusion)]) {
  439. [false, false, false] => $this->l10n->t('Every Year in %1$s on the %2$s for the entire day', [$months, $days]),
  440. [false, false, true] => $this->l10n->t('Every Year in %1$s on the %2$s for the entire day until %3$s', [$months, $days, $conclusion]),
  441. [false, true, false] => $this->l10n->t('Every Year in %1$s on the %2$s between %3$s - %4$s', [$months, $days, $startTime, $endTime]),
  442. [false, true, true] => $this->l10n->t('Every Year in %1$s on the %2$s between %3$s - %4$s until %5$s', [$months, $days, $startTime, $endTime, $conclusion]),
  443. [true, false, false] => $this->l10n->t('Every %1$d Years in %2$s on the %3$s for the entire day', [$interval, $months, $days]),
  444. [true, false, true] => $this->l10n->t('Every %1$d Years in %2$s on the %3$s for the entire day until %4$s', [$interval, $months, $days, $conclusion]),
  445. [true, true, false] => $this->l10n->t('Every %1$d Years in %2$s on the %3$s between %4$s - %5$s', [$interval, $months, $days, $startTime, $endTime]),
  446. [true, true, true] => $this->l10n->t('Every %1$d Years in %2$s on the %3$s between %4$s - %5$s until %6$s', [$interval, $months, $days, $startTime, $endTime, $conclusion]),
  447. default => $this->l10n->t('Could not generate event recurrence statement')
  448. };
  449. }
  450. /**
  451. * genarates a when string for a fixed precision/frequency
  452. *
  453. * @since 30.0.0
  454. *
  455. * @param EventReader $er
  456. *
  457. * @return string
  458. */
  459. public function generateWhenStringRecurringFixed(EventReader $er): string {
  460. // initialize
  461. $startTime = '';
  462. $endTime = '';
  463. $conclusion = '';
  464. // time of the day
  465. if (!$er->entireDay()) {
  466. $startTime = $this->l10n->l('time', $er->startDateTime(), ['width' => 'short']);
  467. $startTime .= $er->startTimeZone() != $er->endTimeZone() ? ' (' . $er->startTimeZone()->getName() . ')' : '';
  468. $endTime = $this->l10n->l('time', $er->endDateTime(), ['width' => 'short']) . ' (' . $er->endTimeZone()->getName() . ')';
  469. }
  470. // conclusion
  471. $conclusion = $this->l10n->l('date', $er->recurringConcludesOn(), ['width' => 'long']);
  472. // generate localized when string
  473. // TRANSLATORS
  474. // Indicates when a calendar event will happen, shown on invitation emails
  475. // Output produced in order:
  476. // On specific dates for the entire day until July 13, 2024
  477. // On specific dates between 8:00 AM - 9:00 AM (America/Toronto) until July 13, 2024
  478. return match (!empty($startTime)) {
  479. false => $this->l10n->t('On specific dates for the entire day until %1$s', [$conclusion]),
  480. true => $this->l10n->t('On specific dates between %1$s - %2$s until %3$s', [$startTime, $endTime, $conclusion]),
  481. };
  482. }
  483. /**
  484. * genarates a occurring next string for a recurring event
  485. *
  486. * @since 30.0.0
  487. *
  488. * @param EventReader $er
  489. *
  490. * @return string
  491. */
  492. public function generateOccurringString(EventReader $er): string {
  493. // reset to initial occurance
  494. $er->recurrenceRewind();
  495. // forward to current date
  496. $er->recurrenceAdvanceTo($this->timeFactory->getDateTime());
  497. // calculate time differnce from now to start of next event occurance and minimize it
  498. $occuranceIn = $this->minimizeInterval($this->timeFactory->getDateTime()->diff($er->recurrenceDate()));
  499. // store next occurance value
  500. $occurance = $this->l10n->l('date', $er->recurrenceDate(), ['width' => 'long']);
  501. // forward one occurance
  502. $er->recurrenceAdvance();
  503. // evaluate if occurance is valid
  504. if ($er->recurrenceDate() !== null) {
  505. // store following occurance value
  506. $occurance2 = $this->l10n->l('date', $er->recurrenceDate(), ['width' => 'long']);
  507. // forward one occurance
  508. $er->recurrenceAdvance();
  509. // evaluate if occurance is valid
  510. if ($er->recurrenceDate()) {
  511. // store following occurance value
  512. $occurance3 = $this->l10n->l('date', $er->recurrenceDate(), ['width' => 'long']);
  513. }
  514. }
  515. // generate localized when string
  516. // TRANSLATORS
  517. // Indicates when a calendar event will happen, shown on invitation emails
  518. // Output produced in order:
  519. // In a day/week/month/year on July 1, 2024
  520. // In a day/week/month/year on July 1, 2024 then on July 3, 2024
  521. // In a day/week/month/year on July 1, 2024 then on July 3, 2024 and July 5, 2024
  522. // In 2 days/weeks/months/years on July 1, 2024
  523. // In 2 days/weeks/months/years on July 1, 2024 then on July 3, 2024
  524. // In 2 days/weeks/months/years on July 1, 2024 then on July 3, 2024 and July 5, 2024
  525. return match ([($occuranceIn[0] > 1), !empty($occurance2), !empty($occurance3)]) {
  526. [false, false, false] => $this->l10n->t('In a %1$s on %2$s', [$occuranceIn[1], $occurance]),
  527. [false, true, false] => $this->l10n->t('In a %1$s on %2$s then on %3$s', [$occuranceIn[1], $occurance, $occurance2]),
  528. [false, true, true] => $this->l10n->t('In a %1$s on %2$s then on %3$s and %4$s', [$occuranceIn[1], $occurance, $occurance2, $occurance3]),
  529. [true, false, false] => $this->l10n->t('In %1$s %2$s on %3$s', [$occuranceIn[0], $occuranceIn[1], $occurance]),
  530. [true, true, false] => $this->l10n->t('In %1$s %2$s on %3$s then on %4$s', [$occuranceIn[0], $occuranceIn[1], $occurance, $occurance2]),
  531. [true, true, true] => $this->l10n->t('In %1$s %2$s on %3$s then on %4$s and %5$s', [$occuranceIn[0], $occuranceIn[1], $occurance, $occurance2, $occurance3]),
  532. default => $this->l10n->t('Could not generate next recurrence statement')
  533. };
  534. }
  535. /**
  536. * @param VEvent $vEvent
  537. * @return array
  538. */
  539. public function buildCancelledBodyData(VEvent $vEvent): array {
  540. // construct event reader
  541. $eventReaderCurrent = new EventReader($vEvent);
  542. $defaultVal = '';
  543. $strikethrough = "<span style='text-decoration: line-through'>%s</span>";
  544. $newMeetingWhen = $this->generateWhenString($eventReaderCurrent);
  545. $newSummary = isset($vEvent->SUMMARY) && (string)$vEvent->SUMMARY !== '' ? (string)$vEvent->SUMMARY : $this->l10n->t('Untitled event');
  546. $newDescription = isset($vEvent->DESCRIPTION) && (string)$vEvent->DESCRIPTION !== '' ? (string)$vEvent->DESCRIPTION : $defaultVal;
  547. $newUrl = isset($vEvent->URL) && (string)$vEvent->URL !== '' ? sprintf('<a href="%1$s">%1$s</a>', $vEvent->URL) : $defaultVal;
  548. $newLocation = isset($vEvent->LOCATION) && (string)$vEvent->LOCATION !== '' ? (string)$vEvent->LOCATION : $defaultVal;
  549. $newLocationHtml = $this->linkify($newLocation) ?? $newLocation;
  550. $data = [];
  551. $data['meeting_when_html'] = $newMeetingWhen === '' ?: sprintf($strikethrough, $newMeetingWhen);
  552. $data['meeting_when'] = $newMeetingWhen;
  553. $data['meeting_title_html'] = sprintf($strikethrough, $newSummary);
  554. $data['meeting_title'] = $newSummary !== '' ? $newSummary: $this->l10n->t('Untitled event');
  555. $data['meeting_description_html'] = $newDescription !== '' ? sprintf($strikethrough, $newDescription) : '';
  556. $data['meeting_description'] = $newDescription;
  557. $data['meeting_url_html'] = $newUrl !== '' ? sprintf($strikethrough, $newUrl) : '';
  558. $data['meeting_url'] = isset($vEvent->URL) ? (string)$vEvent->URL : '';
  559. $data['meeting_location_html'] = $newLocationHtml !== '' ? sprintf($strikethrough, $newLocationHtml) : '';
  560. $data['meeting_location'] = $newLocation;
  561. return $data;
  562. }
  563. /**
  564. * Check if event took place in the past
  565. *
  566. * @param VCalendar $vObject
  567. * @return int
  568. */
  569. public function getLastOccurrence(VCalendar $vObject) {
  570. /** @var VEvent $component */
  571. $component = $vObject->VEVENT;
  572. if (isset($component->RRULE)) {
  573. $it = new EventIterator($vObject, (string)$component->UID);
  574. $maxDate = new \DateTime(IMipPlugin::MAX_DATE);
  575. if ($it->isInfinite()) {
  576. return $maxDate->getTimestamp();
  577. }
  578. $end = $it->getDtEnd();
  579. while ($it->valid() && $end < $maxDate) {
  580. $end = $it->getDtEnd();
  581. $it->next();
  582. }
  583. return $end->getTimestamp();
  584. }
  585. /** @var Property\ICalendar\DateTime $dtStart */
  586. $dtStart = $component->DTSTART;
  587. if (isset($component->DTEND)) {
  588. /** @var Property\ICalendar\DateTime $dtEnd */
  589. $dtEnd = $component->DTEND;
  590. return $dtEnd->getDateTime()->getTimeStamp();
  591. }
  592. if(isset($component->DURATION)) {
  593. /** @var \DateTime $endDate */
  594. $endDate = clone $dtStart->getDateTime();
  595. // $component->DTEND->getDateTime() returns DateTimeImmutable
  596. $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  597. return $endDate->getTimestamp();
  598. }
  599. if(!$dtStart->hasTime()) {
  600. /** @var \DateTime $endDate */
  601. // $component->DTSTART->getDateTime() returns DateTimeImmutable
  602. $endDate = clone $dtStart->getDateTime();
  603. $endDate = $endDate->modify('+1 day');
  604. return $endDate->getTimestamp();
  605. }
  606. // No computation of end time possible - return start date
  607. return $dtStart->getDateTime()->getTimeStamp();
  608. }
  609. /**
  610. * @param Property|null $attendee
  611. */
  612. public function setL10n(?Property $attendee = null) {
  613. if($attendee === null) {
  614. return;
  615. }
  616. $lang = $attendee->offsetGet('LANGUAGE');
  617. if ($lang instanceof Parameter) {
  618. $lang = $lang->getValue();
  619. $this->l10n = $this->l10nFactory->get('dav', $lang);
  620. }
  621. }
  622. /**
  623. * @param Property|null $attendee
  624. * @return bool
  625. */
  626. public function getAttendeeRsvpOrReqForParticipant(?Property $attendee = null) {
  627. if($attendee === null) {
  628. return false;
  629. }
  630. $rsvp = $attendee->offsetGet('RSVP');
  631. if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) {
  632. return true;
  633. }
  634. $role = $attendee->offsetGet('ROLE');
  635. // @see https://datatracker.ietf.org/doc/html/rfc5545#section-3.2.16
  636. // Attendees without a role are assumed required and should receive an invitation link even if they have no RSVP set
  637. if ($role === null
  638. || (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'REQ-PARTICIPANT') === 0))
  639. || (($role instanceof Parameter) && (strcasecmp($role->getValue(), 'OPT-PARTICIPANT') === 0))
  640. ) {
  641. return true;
  642. }
  643. // RFC 5545 3.2.17: default RSVP is false
  644. return false;
  645. }
  646. /**
  647. * @param IEMailTemplate $template
  648. * @param string $method
  649. * @param string $sender
  650. * @param string $summary
  651. * @param string|null $partstat
  652. * @param bool $isModified
  653. */
  654. public function addSubjectAndHeading(IEMailTemplate $template,
  655. string $method, string $sender, string $summary, bool $isModified, ?Property $replyingAttendee = null): void {
  656. if ($method === IMipPlugin::METHOD_CANCEL) {
  657. // TRANSLATORS Subject for email, when an invitation is cancelled. Ex: "Cancelled: {{Event Name}}"
  658. $template->setSubject($this->l10n->t('Cancelled: %1$s', [$summary]));
  659. $template->addHeading($this->l10n->t('"%1$s" has been canceled', [$summary]));
  660. } elseif ($method === IMipPlugin::METHOD_REPLY) {
  661. // TRANSLATORS Subject for email, when an invitation is replied to. Ex: "Re: {{Event Name}}"
  662. $template->setSubject($this->l10n->t('Re: %1$s', [$summary]));
  663. // Build the strings
  664. $partstat = (isset($replyingAttendee)) ? $replyingAttendee->offsetGet('PARTSTAT') : null;
  665. $partstat = ($partstat instanceof Parameter) ? $partstat->getValue() : null;
  666. switch ($partstat) {
  667. case 'ACCEPTED':
  668. $template->addHeading($this->l10n->t('%1$s has accepted your invitation', [$sender]));
  669. break;
  670. case 'TENTATIVE':
  671. $template->addHeading($this->l10n->t('%1$s has tentatively accepted your invitation', [$sender]));
  672. break;
  673. case 'DECLINED':
  674. $template->addHeading($this->l10n->t('%1$s has declined your invitation', [$sender]));
  675. break;
  676. case null:
  677. default:
  678. $template->addHeading($this->l10n->t('%1$s has responded to your invitation', [$sender]));
  679. break;
  680. }
  681. } elseif ($method === IMipPlugin::METHOD_REQUEST && $isModified) {
  682. // TRANSLATORS Subject for email, when an invitation is updated. Ex: "Invitation updated: {{Event Name}}"
  683. $template->setSubject($this->l10n->t('Invitation updated: %1$s', [$summary]));
  684. $template->addHeading($this->l10n->t('%1$s updated the event "%2$s"', [$sender, $summary]));
  685. } else {
  686. // TRANSLATORS Subject for email, when an invitation is sent. Ex: "Invitation: {{Event Name}}"
  687. $template->setSubject($this->l10n->t('Invitation: %1$s', [$summary]));
  688. $template->addHeading($this->l10n->t('%1$s would like to invite you to "%2$s"', [$sender, $summary]));
  689. }
  690. }
  691. /**
  692. * @param string $path
  693. * @return string
  694. */
  695. public function getAbsoluteImagePath($path): string {
  696. return $this->urlGenerator->getAbsoluteURL(
  697. $this->urlGenerator->imagePath('core', $path)
  698. );
  699. }
  700. /**
  701. * addAttendees: add organizer and attendee names/emails to iMip mail.
  702. *
  703. * Enable with DAV setting: invitation_list_attendees (default: no)
  704. *
  705. * The default is 'no', which matches old behavior, and is privacy preserving.
  706. *
  707. * To enable including attendees in invitation emails:
  708. * % php occ config:app:set dav invitation_list_attendees --value yes
  709. *
  710. * @param IEMailTemplate $template
  711. * @param IL10N $this->l10n
  712. * @param VEvent $vevent
  713. * @author brad2014 on github.com
  714. */
  715. public function addAttendees(IEMailTemplate $template, VEvent $vevent) {
  716. if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') {
  717. return;
  718. }
  719. if (isset($vevent->ORGANIZER)) {
  720. /** @var Property | Property\ICalendar\CalAddress $organizer */
  721. $organizer = $vevent->ORGANIZER;
  722. $organizerEmail = substr($organizer->getNormalizedValue(), 7);
  723. /** @var string|null $organizerName */
  724. $organizerName = isset($organizer->CN) ? $organizer->CN->getValue() : null;
  725. $organizerHTML = sprintf('<a href="%s">%s</a>',
  726. htmlspecialchars($organizer->getNormalizedValue()),
  727. htmlspecialchars($organizerName ?: $organizerEmail));
  728. $organizerText = sprintf('%s <%s>', $organizerName, $organizerEmail);
  729. if(isset($organizer['PARTSTAT'])) {
  730. /** @var Parameter $partstat */
  731. $partstat = $organizer['PARTSTAT'];
  732. if(strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
  733. $organizerHTML .= ' ✔︎';
  734. $organizerText .= ' ✔︎';
  735. }
  736. }
  737. $template->addBodyListItem($organizerHTML, $this->l10n->t('Organizer:'),
  738. $this->getAbsoluteImagePath('caldav/organizer.png'),
  739. $organizerText, '', IMipPlugin::IMIP_INDENT);
  740. }
  741. $attendees = $vevent->select('ATTENDEE');
  742. if (count($attendees) === 0) {
  743. return;
  744. }
  745. $attendeesHTML = [];
  746. $attendeesText = [];
  747. foreach ($attendees as $attendee) {
  748. $attendeeEmail = substr($attendee->getNormalizedValue(), 7);
  749. $attendeeName = isset($attendee['CN']) ? $attendee['CN']->getValue() : null;
  750. $attendeeHTML = sprintf('<a href="%s">%s</a>',
  751. htmlspecialchars($attendee->getNormalizedValue()),
  752. htmlspecialchars($attendeeName ?: $attendeeEmail));
  753. $attendeeText = sprintf('%s <%s>', $attendeeName, $attendeeEmail);
  754. if (isset($attendee['PARTSTAT'])) {
  755. /** @var Parameter $partstat */
  756. $partstat = $attendee['PARTSTAT'];
  757. if (strcasecmp($partstat->getValue(), 'ACCEPTED') === 0) {
  758. $attendeeHTML .= ' ✔︎';
  759. $attendeeText .= ' ✔︎';
  760. }
  761. }
  762. $attendeesHTML[] = $attendeeHTML;
  763. $attendeesText[] = $attendeeText;
  764. }
  765. $template->addBodyListItem(implode('<br/>', $attendeesHTML), $this->l10n->t('Attendees:'),
  766. $this->getAbsoluteImagePath('caldav/attendees.png'),
  767. implode("\n", $attendeesText), '', IMipPlugin::IMIP_INDENT);
  768. }
  769. /**
  770. * @param IEMailTemplate $template
  771. * @param VEVENT $vevent
  772. * @param $data
  773. */
  774. public function addBulletList(IEMailTemplate $template, VEvent $vevent, $data) {
  775. $template->addBodyListItem(
  776. $data['meeting_title_html'] ?? $data['meeting_title'], $this->l10n->t('Title:'),
  777. $this->getAbsoluteImagePath('caldav/title.png'), $data['meeting_title'], '', IMipPlugin::IMIP_INDENT);
  778. if ($data['meeting_when'] !== '') {
  779. $template->addBodyListItem($data['meeting_when_html'] ?? $data['meeting_when'], $this->l10n->t('When:'),
  780. $this->getAbsoluteImagePath('caldav/time.png'), $data['meeting_when'], '', IMipPlugin::IMIP_INDENT);
  781. }
  782. if ($data['meeting_location'] !== '') {
  783. $template->addBodyListItem($data['meeting_location_html'] ?? $data['meeting_location'], $this->l10n->t('Location:'),
  784. $this->getAbsoluteImagePath('caldav/location.png'), $data['meeting_location'], '', IMipPlugin::IMIP_INDENT);
  785. }
  786. if ($data['meeting_url'] !== '') {
  787. $template->addBodyListItem($data['meeting_url_html'] ?? $data['meeting_url'], $this->l10n->t('Link:'),
  788. $this->getAbsoluteImagePath('caldav/link.png'), $data['meeting_url'], '', IMipPlugin::IMIP_INDENT);
  789. }
  790. if (isset($data['meeting_occurring'])) {
  791. $template->addBodyListItem($data['meeting_occurring_html'] ?? $data['meeting_occurring'], $this->l10n->t('Occurring:'),
  792. $this->getAbsoluteImagePath('caldav/time.png'), $data['meeting_occurring'], '', IMipPlugin::IMIP_INDENT);
  793. }
  794. $this->addAttendees($template, $vevent);
  795. /* Put description last, like an email body, since it can be arbitrarily long */
  796. if ($data['meeting_description']) {
  797. $template->addBodyListItem($data['meeting_description_html'] ?? $data['meeting_description'], $this->l10n->t('Description:'),
  798. $this->getAbsoluteImagePath('caldav/description.png'), $data['meeting_description'], '', IMipPlugin::IMIP_INDENT);
  799. }
  800. }
  801. /**
  802. * @param Message $iTipMessage
  803. * @return null|Property
  804. */
  805. public function getCurrentAttendee(Message $iTipMessage): ?Property {
  806. /** @var VEvent $vevent */
  807. $vevent = $iTipMessage->message->VEVENT;
  808. $attendees = $vevent->select('ATTENDEE');
  809. foreach ($attendees as $attendee) {
  810. if ($iTipMessage->method === 'REPLY' && strcasecmp($attendee->getValue(), $iTipMessage->sender) === 0) {
  811. /** @var Property $attendee */
  812. return $attendee;
  813. } elseif (strcasecmp($attendee->getValue(), $iTipMessage->recipient) === 0) {
  814. /** @var Property $attendee */
  815. return $attendee;
  816. }
  817. }
  818. return null;
  819. }
  820. /**
  821. * @param Message $iTipMessage
  822. * @param VEvent $vevent
  823. * @param int $lastOccurrence
  824. * @return string
  825. */
  826. public function createInvitationToken(Message $iTipMessage, VEvent $vevent, int $lastOccurrence): string {
  827. $token = $this->random->generate(60, ISecureRandom::CHAR_ALPHANUMERIC);
  828. $attendee = $iTipMessage->recipient;
  829. $organizer = $iTipMessage->sender;
  830. $sequence = $iTipMessage->sequence;
  831. $recurrenceId = isset($vevent->{'RECURRENCE-ID'}) ?
  832. $vevent->{'RECURRENCE-ID'}->serialize() : null;
  833. $uid = $vevent->{'UID'};
  834. $query = $this->db->getQueryBuilder();
  835. $query->insert('calendar_invitations')
  836. ->values([
  837. 'token' => $query->createNamedParameter($token),
  838. 'attendee' => $query->createNamedParameter($attendee),
  839. 'organizer' => $query->createNamedParameter($organizer),
  840. 'sequence' => $query->createNamedParameter($sequence),
  841. 'recurrenceid' => $query->createNamedParameter($recurrenceId),
  842. 'expiration' => $query->createNamedParameter($lastOccurrence),
  843. 'uid' => $query->createNamedParameter($uid)
  844. ])
  845. ->execute();
  846. return $token;
  847. }
  848. /**
  849. * @param IEMailTemplate $template
  850. * @param $token
  851. */
  852. public function addResponseButtons(IEMailTemplate $template, $token) {
  853. $template->addBodyButtonGroup(
  854. $this->l10n->t('Accept'),
  855. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.accept', [
  856. 'token' => $token,
  857. ]),
  858. $this->l10n->t('Decline'),
  859. $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.decline', [
  860. 'token' => $token,
  861. ])
  862. );
  863. }
  864. public function addMoreOptionsButton(IEMailTemplate $template, $token) {
  865. $moreOptionsURL = $this->urlGenerator->linkToRouteAbsolute('dav.invitation_response.options', [
  866. 'token' => $token,
  867. ]);
  868. $html = vsprintf('<small><a href="%s">%s</a></small>', [
  869. $moreOptionsURL, $this->l10n->t('More options …')
  870. ]);
  871. $text = $this->l10n->t('More options at %s', [$moreOptionsURL]);
  872. $template->addBodyText($html, $text);
  873. }
  874. public function getReplyingAttendee(Message $iTipMessage): ?Property {
  875. /** @var VEvent $vevent */
  876. $vevent = $iTipMessage->message->VEVENT;
  877. $attendees = $vevent->select('ATTENDEE');
  878. foreach ($attendees as $attendee) {
  879. /** @var Property $attendee */
  880. if (strcasecmp($attendee->getValue(), $iTipMessage->sender) === 0) {
  881. return $attendee;
  882. }
  883. }
  884. return null;
  885. }
  886. public function isRoomOrResource(Property $attendee): bool {
  887. $cuType = $attendee->offsetGet('CUTYPE');
  888. if(!$cuType instanceof Parameter) {
  889. return false;
  890. }
  891. $type = $cuType->getValue() ?? 'INDIVIDUAL';
  892. if (\in_array(strtoupper($type), ['RESOURCE', 'ROOM', 'UNKNOWN'], true)) {
  893. // Don't send emails to things
  894. return true;
  895. }
  896. return false;
  897. }
  898. public function minimizeInterval(\DateInterval $dateInterval): array {
  899. // evaluate if time interval is in the past
  900. if ($dateInterval->invert == 1) {
  901. return [1, 'the past'];
  902. }
  903. // evaluate interval parts and return smallest time period
  904. if ($dateInterval->y > 0) {
  905. $interval = $dateInterval->y;
  906. $scale = ($dateInterval->y > 1) ? 'years' : 'year';
  907. } elseif ($dateInterval->m > 0) {
  908. $interval = $dateInterval->m;
  909. $scale = ($dateInterval->m > 1) ? 'months' : 'month';
  910. } elseif ($dateInterval->d >= 7) {
  911. $interval = (int)($dateInterval->d / 7);
  912. $scale = ((int)($dateInterval->d / 7) > 1) ? 'weeks' : 'week';
  913. } elseif ($dateInterval->d > 0) {
  914. $interval = $dateInterval->d;
  915. $scale = ($dateInterval->d > 1) ? 'days' : 'day';
  916. } elseif ($dateInterval->h > 0) {
  917. $interval = $dateInterval->h;
  918. $scale = ($dateInterval->h > 1) ? 'hours' : 'hour';
  919. } else {
  920. $interval = $dateInterval->i;
  921. $scale = 'minutes';
  922. }
  923. return [$interval, $scale];
  924. }
  925. /**
  926. * Localizes week day names to another language
  927. *
  928. * @param string $value
  929. *
  930. * @return string
  931. */
  932. public function localizeDayName(string $value): string {
  933. return match ($value) {
  934. 'Monday' => $this->l10n->t('Monday'),
  935. 'Tuesday' => $this->l10n->t('Tuesday'),
  936. 'Wednesday' => $this->l10n->t('Wednesday'),
  937. 'Thursday' => $this->l10n->t('Thursday'),
  938. 'Friday' => $this->l10n->t('Friday'),
  939. 'Saturday' => $this->l10n->t('Saturday'),
  940. 'Sunday' => $this->l10n->t('Sunday'),
  941. };
  942. }
  943. /**
  944. * Localizes month names to another language
  945. *
  946. * @param string $value
  947. *
  948. * @return string
  949. */
  950. public function localizeMonthName(string $value): string {
  951. return match ($value) {
  952. 'January' => $this->l10n->t('January'),
  953. 'February' => $this->l10n->t('February'),
  954. 'March' => $this->l10n->t('March'),
  955. 'April' => $this->l10n->t('April'),
  956. 'May' => $this->l10n->t('May'),
  957. 'June' => $this->l10n->t('June'),
  958. 'July' => $this->l10n->t('July'),
  959. 'August' => $this->l10n->t('August'),
  960. 'September' => $this->l10n->t('September'),
  961. 'October' => $this->l10n->t('October'),
  962. 'November' => $this->l10n->t('November'),
  963. 'December' => $this->l10n->t('December'),
  964. };
  965. }
  966. /**
  967. * Localizes relative position names to another language
  968. *
  969. * @param string $value
  970. *
  971. * @return string
  972. */
  973. public function localizeRelativePositionName(string $value): string {
  974. return match ($value) {
  975. 'First' => $this->l10n->t('First'),
  976. 'Second' => $this->l10n->t('Second'),
  977. 'Third' => $this->l10n->t('Third'),
  978. 'Fourth' => $this->l10n->t('Fourth'),
  979. 'Fifty' => $this->l10n->t('Fifty'),
  980. 'Last' => $this->l10n->t('Last'),
  981. 'Second Last' => $this->l10n->t('Second Last'),
  982. 'Third Last' => $this->l10n->t('Third Last'),
  983. 'Fourth Last' => $this->l10n->t('Fourth Last'),
  984. 'Fifty Last' => $this->l10n->t('Fifty Last'),
  985. };
  986. }
  987. }