-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
DavListener.php
1688 lines (1436 loc) · 67.2 KB
/
DavListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/** @noinspection PhpFullyQualifiedNameUsageInspection */
namespace OCA\Appointments\Backend;
use OC\Mail\EMailTemplate;
use OCA\Appointments\AppInfo\Application;
use OCA\Appointments\Linkify;
use OCA\DAV\Events\CalendarObjectMovedToTrashEvent;
use OCA\DAV\Events\CalendarObjectUpdatedEvent;
use OCA\DAV\Events\SubscriptionDeletedEvent;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Mail\IEMailTemplate;
use OCP\Mail\IMailer;
use OCP\Mail\IMessage;
use Psr\Log\LoggerInterface;
use Sabre\VObject\Reader;
class DavListener implements IEventListener
{
private const VIDEO_NONE = 0;
private const VIDEO_TALK = 1;
private const VIDEO_BBB = 2;
private $appName;
private $l10N;
private $logger;
private $utils;
/** @type IMailer */
private $mailer;
/** @type IConfig */
private $config;
private $linkify;
public function __construct(\OCP\IL10N $l10N,
LoggerInterface $logger,
BackendUtils $utils)
{
$this->appName = Application::APP_ID;
$this->l10N = $l10N;
$this->logger = $logger;
$this->utils = $utils;
$this->mailer = \OC::$server->get(IMailer::class);
$this->config = \OC::$server->get(IConfig::class);
$this->linkify = new Linkify();
}
function handle(Event $event): void
{
if ($event instanceof CalendarObjectUpdatedEvent) {
$this->handler($event->getObjectData(), $event->getCalendarData(), false);
} elseif ($event instanceof CalendarObjectMovedToTrashEvent) {
$this->handler($event->getObjectData(), $event->getCalendarData(), true);
} elseif ($event instanceof SubscriptionDeletedEvent) {
// clean BackendUtils::SYNC_TABLE_NAME
$this->utils->removeSubscriptionSync($event->getSubscriptionId());
}
}
public function handleOld(\Symfony\Component\EventDispatcher\GenericEvent $event, string $eventName): void
{
$this->handler($event['objectData'], $event['calendarData'], $eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject');
}
/**
* @param int $lastStart timestamp set by IJobList->setLastRun() product of time() func
*/
public function handleReminders(int $lastStart, IDBConnection $db, IBackendConnector $bc): void
{
// we need to pull all pending appointments between now + 42 min( 1 hour [min delta] - 18 min [time between jobs]) and now + 7 days(max delta)
$now = time();
$qb = $db->getQueryBuilder();
try {
$result = $qb->select('hash.*',
'pref.' . BackendUtils::KEY_REMINDERS)
->from(BackendUtils::HASH_TABLE_NAME, 'hash')
->leftJoin('hash', BackendUtils::PREF_TABLE_V2_NAME, 'pref', $qb->expr()->andX(
$qb->expr()->eq(
'hash.' . BackendUtils::KEY_USER_ID,
'pref.' . BackendUtils::KEY_USER_ID),
$qb->expr()->eq(
'hash.' . BackendUtils::KEY_PAGE_ID,
'pref.' . BackendUtils::KEY_PAGE_ID)))
->where($qb->expr()->isNotNull('pref.' . BackendUtils::KEY_REMINDERS))
->andWhere($qb->expr()->eq('hash.status', $qb->createNamedParameter(BackendUtils::PREF_STATUS_CONFIRMED, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->gte('hash.start', $qb->createNamedParameter($now + 2520, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->lte('hash.start', $qb->createNamedParameter($now + 604800, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->isNotNull('hash.' . BackendUtils::KEY_USER_ID))
->andWhere($qb->expr()->isNotNull('hash.' . BackendUtils::KEY_PAGE_ID))
->andWhere($qb->expr()->isNotNull('hash.uri'))
->orderBy('hash.' . BackendUtils::KEY_USER_ID)
->execute();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
return;
}
$userId = '';
$pageId = '';
$remDataArray = [];
// The first loop is to collect data from DB and close the connection,
// the second loop actually sends the emails
$remindersToSend = [];
while ($row = $result->fetch()) {
$reuseSettings = true;
if ($userId !== $row[BackendUtils::KEY_USER_ID]
|| $pageId !== $row[BackendUtils::KEY_PAGE_ID]) {
$userId = $row[BackendUtils::KEY_USER_ID];
$pageId = $row[BackendUtils::KEY_PAGE_ID];
$remObj = json_decode($row[BackendUtils::KEY_REMINDERS], true);
if ($remObj === null) {
$this->logger->error("json_decode failed for, userId: " . $userId . ", pageId: " . $pageId);
continue;
}
$reuseSettings = false;
$remDataArray = $remObj[BackendUtils::REMINDER_DATA];
}
foreach ($remDataArray as $remData) {
$remindAt = $row['start'] - $remData[BackendUtils::REMINDER_DATA_TIME];
// $this->logger->error($remindAt . ', '
// . $row['start'] . ', '
// . $remData[BackendUtils::REMINDER_DATA_TIME]);
// $lastStart is set at the START of previous job
// for next job $lastStart is already set to basically $now
if ($remindAt >= $lastStart && $remindAt < $now) {
$remindersToSend[] = [
'userId' => $userId,
'pageId' => $pageId,
'actions' => $remData[BackendUtils::REMINDER_DATA_ACTIONS],
'evtUri' => $row['uri'],
'evtUid' => $row['uid'],
'apptDoc' => is_resource($row['appt_doc'])
? stream_get_contents($row['appt_doc'])
: $row['appt_doc'],
'reuseSettings' => $reuseSettings
];
}
}
}
$result->closeCursor();
// $this->logger->error('rts: ' . var_export($remindersToSend, true));
if (count($remindersToSend) === 0) {
// nothing to do
return;
}
// just in-case
$remindersToSend[0]['reuseSettings'] = false;
$config = $this->config;
$mailer = $this->mailer;
$utils = $this->utils;
$utz = new \DateTimeZone('utc');
$calId = '-1';
$otherCalId = '-1';
$extNotifyFilePath = '';
$settings = [];
$doc = new ApptDocProp();
// This loop sends out emails (there is .5sec sleep between each send)
foreach ($remindersToSend as $remInfo) {
if ($remInfo['reuseSettings'] === false) {
$userId = $remInfo['userId'];
$pageId = $remInfo['pageId'];
if (!$utils->loadSettingsForUserAndPage($userId, $pageId)) {
$this->logger->error("loadSettingsForUserAndPage failed, userId: " . $userId . ", pageId: " . $pageId);
continue;
}
$settings = $utils->getUserSettings();
if (!isset($settings[BackendUtils::KEY_REMINDERS])) {
$this->logger->error(" missing settings reminder data, userId: " . $userId . ", pageId: " . $pageId);
continue;
}
$extNotifyFilePath = $config->getAppValue($this->appName, 'ext_notify_' . $userId);
$otherCalId = '-1';
$calId = $utils->getMainCalId($userId, null, $otherCalId);
if ($calId === '-1') {
$this->logger->error("can not find main calendar, userId: " . $userId . ", pageId: " . $pageId);
continue;
}
if ($otherCalId !== '-1'
&& $settings[BackendUtils::CLS_TS_MODE] === BackendUtils::CLS_TS_MODE_SIMPLE) {
// if we have a dst calendar in simple mode than it will hold confirmed appointments, so we should check it first and then check the src calendar just in-case settings have been changed after the appointment was booked
$temp = $calId;
$calId = $otherCalId;
$otherCalId = $temp;
} else {
// dst calendar is only valid in simple mode
$otherCalId = '-1';
}
$utz = $this->utils->getCalendarTimezone($userId, $bc->getCalendarById($calId, $userId));
}
// settings are good at this point
$evtUri = $remInfo['evtUri'];
$data = $bc->getObjectData($calId, $evtUri);
if ($data === null && $otherCalId !== '-1') {
$data = $bc->getObjectData($otherCalId, $evtUri);
}
if ($data === null) {
$this->logger->error("can not get object data, uri: " . $evtUri . ", calId: " . $calId);
continue;
}
if (!str_contains($data, "\r\nATTENDEE;")
|| (!str_contains($data, "\r\n" . BackendUtils::TZI_PROP . ":")
&& !str_contains($data, "\r\n" . ApptDocProp::PROP_NAME . ":"))
) {
$this->logger->error('bad event data, uid: ' . $remInfo['evtUid']);
continue;
}
$vObject = Reader::read($data);
if (!isset($vObject->VEVENT)) {
$this->logger->error("Reader::read failed, uid: " . $remInfo['evtUid']);
$vObject->destroy();
continue;
}
/** @var \Sabre\VObject\Component\VEvent $evt */
$evt = $vObject->VEVENT;
if (!isset($evt->UID)
|| !isset($evt->ATTENDEE)
|| !isset($evt->STATUS)
|| !isset($evt->DTEND)
|| !isset($evt->ORGANIZER)
|| $evt->STATUS->getValue() !== 'CONFIRMED'
|| (!isset($evt->{BackendUtils::XAD_PROP})
&& !isset($evt->{ApptDocProp::PROP_NAME}))
) {
$this->logger->error('bad event object, uid: ' . $remInfo['evtUid']);
$vObject->destroy();
continue;
}
$att = $utils->getAttendee($evt);
if ($att === null || $att->parameters['PARTSTAT']->getValue() === 'DECLINED') {
$this->logger->error('bad attendee data, uid: ' . $remInfo['evtUid']);
$vObject->destroy();
continue;
}
$to_name = $att->parameters['CN']->getValue();
if (empty($to_name) || preg_match('/[^\PC ]/u', $to_name)) {
$this->logger->error('invalid attendee name, uid: ' . $remInfo['evtUid']);
$vObject->destroy();
continue;
}
$att_v = $att->getValue();
$to_email = substr($att_v, strpos($att_v, ":") + 1);
if ($mailer->validateMailAddress($to_email) === false) {
$this->logger->error('invalid attendee email, uid: ' . $remInfo['evtUid']);
$vObject->destroy();
continue;
}
// event data looks ok...
if (isset($evt->{ApptDocProp::PROP_NAME})) {
if (!empty($remInfo['apptDoc']) && strlen($remInfo['apptDoc']) > 8) {
$doc->setFromString(substr($remInfo['apptDoc'], 8), 'dummy_evt_uid');
} else {
$doc->reset();
}
$date_time = $utils->getDateTimeString(
$evt->DTSTART->getDateTime(),
$doc->attendeeTimezone
);
} else {
$date_time = $utils->getDateTimeString(
$evt->DTSTART->getDateTime(),
$evt->{BackendUtils::TZI_PROP}->getValue()
);
}
list($org_email, $org_name, $org_phone) = $this->getOrgInfo();
$tmpl = $this->getEmailTemplate();
// TRANSLATORS Subject for email, Ex: {{Organization Name}} appointment reminder
$tmpl->setSubject($this->l10N->t("%s appointment reminder", [$org_name]));
$tmpl->addHeading(" "); // spacer
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS First line of email, Ex: Dear {{Customer Name}},
$this->l10N->t("Dear %s,", [$to_name])
]));
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS Main part of email, Ex: This is a reminder from {{Organization Name}} about your upcoming appointment on {{Date And Time}}. If you need to reschedule, please call {{Organization Phone}}.
$this->l10N->t('This is a reminder from %1$s about your upcoming appointment on %2$s. If you need to reschedule, please call %3$s.', [$org_name, $date_time, $org_phone])
]));
$cnl_lnk_url = '';
// do we want links and buttons ?
if ($remInfo['actions']) {
if (isset($evt->{ApptDocProp::PROP_NAME})) {
$embed = $doc->embed;
// overwrite.cli.url must be set if $embed is not used
if ($embed || $config->getSystemValue('overwrite.cli.url') !== '') {
list($btn_url, $btn_tkn) = $this->makeBtnInfo(
$userId, $pageId, $embed,
$evtUri, $config);
$cnl_lnk_url = $btn_url . "0" . $btn_tkn;
$videoType = $this->getVideoType($settings);
if ($videoType !== self::VIDEO_NONE) {
if (($videoType === self::VIDEO_TALK
&& $settings[BackendUtils::TALK_FORM_ENABLED])
|| ($videoType === self::VIDEO_BBB
&& $settings[BackendUtils::BBB_FORM_ENABLED])
) {
$has_link = !empty($doc->talkToken . $doc->bbbToken);
if ($has_link) {
$this->addVideoLinkInfo(
$userId, $tmpl, $doc, $settings,
$config->getUserValue($userId, $this->appName, "c" . "nk")
);
}
$this->addTypeChangeLink($tmpl, $settings, $btn_url . "3" . $btn_tkn, $has_link);
}
}
} else {
$this->logger->error('can not add actions to reminder, missing overwrite.cli.url');
}
} else {
// @see BackendUtils->dataSetAttendee for BackendUtils::XAD_PROP
$xad = explode(chr(31), $utils->decrypt(
$evt->{BackendUtils::XAD_PROP}->getValue(),
$evt->UID->getValue()));
if (count($xad) > 2) {
$embed = $xad[3] === "1";
} else {
$embed = false;
}
// overwrite.cli.url must be set if $embed is not used
if ($embed || $config->getSystemValue('overwrite.cli.url') !== '') {
list($btn_url, $btn_tkn) = $this->makeBtnInfo(
$userId, $pageId, $embed,
$evtUri, $config);
$cnl_lnk_url = $btn_url . "0" . $btn_tkn;
if (!empty($xad) && count($xad) > 4) {
$has_link = strlen($xad[4]) > 1;
if ($settings[BackendUtils::TALK_ENABLED]) {
if ($settings[BackendUtils::TALK_FORM_ENABLED] === true) {
if ($has_link) {
$ti = new TalkIntegration($settings, $utils);
// add talk link info
$this->addTalkInfo(
$tmpl, $xad, $ti, $settings,
$config->getUserValue($userId, $this->appName, "c" . "nk"));
}
$this->addTypeChangeLink($tmpl, $settings, $btn_url . "3" . $btn_tkn, $has_link);
}
}
}
} else {
$this->logger->error('can not add actions to reminder, missing overwrite.cli.url');
}
}
}
$remObj = $settings[BackendUtils::KEY_REMINDERS];
if (!empty($remObj[BackendUtils::REMINDER_MORE_TEXT])) {
list($remHtml, $remPlainText) = $this->prepHtmlEmailText($remObj[BackendUtils::REMINDER_MORE_TEXT]);
if ($remHtml === null) {
$tmpl->addBodyText(...$this->formatEmailBodyHtml([$remPlainText]));
} else {
$tmpl->addBodyText(...$this->formatEmailBodyHtml([$remHtml, $remPlainText]));
}
}
// everything is ready, send email...
$this->finalizeEmailText($tmpl, $cnl_lnk_url);
$msg = $mailer->createMessage();
$this->setFromAddress($msg, $userId, $org_email, $org_name);
$msg->setTo(array($to_email));
$msg->useTemplate($tmpl);
$description = '';
try {
$mailer->send($msg);
if (!isset($evt->DESCRIPTION)) {
$evt->add('DESCRIPTION');
}
$description = $evt->DESCRIPTION->getValue();
// TRANSLATORS Ex: Reminder sent on {{Date and Time}},
$description .= "\n" . $this->l10N->t("Reminder sent on %s", [$utils->getDateTimeString(
new \DateTimeImmutable('now', $utz),
"T" . $utz->getName()
, 1
)]);
$evt->DESCRIPTION->setValue($description);
if ($bc->updateObject($calId, $evtUri, $vObject->serialize()) === false) {
$this->logger->error("Can not update object uid: " . $remInfo['evtUid']);
}
} catch (\Exception $e) {
$this->logger->error("Can not send email to " . $to_email . ", uid: " . $remInfo['evtUid']);
$this->logger->error($e->getMessage());
}
// advanced/extensions
if ($extNotifyFilePath !== "") {
$data = [
'eventType' => 4,
'dateTime' => $evt->DTSTART->getDateTime(),
'attendeeName' => $to_name,
'attendeeEmail' => $to_email,
'attendeeTel' => $this->getPhoneFromDescription($description),
'pageId' => $pageId
];
$this->extNotify($data, $userId, $extNotifyFilePath);
}
// remove all circular references, so PHP can easily clean it up.
$vObject->destroy();
usleep(320000);
}
}
private function handler(array $objectData, array $calendarData, bool $isDelete): void
{
// \OC::$server->getLogger()->error('DL Debug: M0');
// objectUri
if (!isset($objectData['calendardata']) ||
!isset($objectData['uri'])) {
return;
}
$cd = $objectData['calendardata'];
if (!str_contains($cd, "\r\nATTENDEE;")
|| !str_contains($cd, "\r\nCATEGORIES:" . BackendUtils::APPT_CAT . "\r\n")
|| (!str_contains($cd, "\r\n" . BackendUtils::TZI_PROP . ":")
&& !str_contains($cd, "\r\n" . ApptDocProp::PROP_NAME . ":"))
|| !str_contains($cd, "\r\nORGANIZER;")
|| !str_contains($cd, "\r\nUID:")) {
// Not a good appointment, bail early...
return;
}
// \OC::$server->getLogger()->error('DL Debug: M1');
$hint = HintVar::getHint();
if ($hint === HintVar::APPT_SKIP
|| ($isDelete && $hint === HintVar::APPT_CONFIRM) // <-- booking in to a different calendar NOT deleting
) {
// no need for email
return;
}
// \OC::$server->getLogger()->error('DL Debug: M2');
$vObject = Reader::read($cd);
if (!isset($vObject->VEVENT)) {
// Not a VEVENT
return;
}
/** @var \Sabre\VObject\Component\VEvent $evt */
$evt = $vObject->VEVENT;
if (!isset($evt->UID)) {
$this->logger->error('UID not found');
return;
}
// \OC::$server->getLogger()->error('DL Debug: M3');
$utils = $this->utils;
$config = $this->config;
$doc = null;
if (isset($evt->{ApptDocProp::PROP_NAME})) {
$doc = $utils->getApptDoc($evt);
$embed = $doc->embed;
$hashRow = $this->utils->getApptHashRow($evt->UID->getValue());
if (!$hashRow) {
$this->logger->error("hashRow not found");
return;
}
$userId = $hashRow['user_id'];
$pageId = $hashRow['page_id'];
} elseif (isset($evt->{BackendUtils::XAD_PROP})) {
// @see BackendUtils->dataSetAttendee for BackendUtils::XAD_PROP
$xad = explode(chr(31), $utils->decrypt(
$evt->{BackendUtils::XAD_PROP}->getValue(),
$evt->UID->getValue()));
$userId = $xad[0];
if (count($xad) > 2) {
$pageId = $xad[2];
$embed = $xad[3] === "1";
} else {
$pageId = 'p0';
$embed = false;
}
} else {
$this->logger->error("XAD_PROP not found");
return;
}
// \OC::$server->getLogger()->error('DL Debug: M5');
if ($utils->loadSettingsForUserAndPage($userId, $pageId) === false) {
return;
}
$other_cal = '-1';
$cal_id = $utils->getMainCalId($userId, null, $other_cal);
$settings = $this->utils->getUserSettings();
if ($other_cal !== '-1') {
// only allowed in simple
if ($settings[BackendUtils::CLS_TS_MODE] !== '0') {
$other_cal = '-1';
}
}
// Check cal IDs.
// $calendarData['id'] can be a string or an int
if ($cal_id != $calendarData['id'] && $other_cal != $calendarData['id']) {
// Not this user's calendar
return;
}
// \OC::$server->getLogger()->error('DL Debug: M6');
$hash = $utils->getApptHash($evt->UID->getValue());
if ($isDelete) {
$utils->deleteApptHash($evt);
}
if ($hash === null
|| !isset($evt->ATTENDEE)
|| !isset($evt->STATUS)
|| !isset($evt->DTEND)
|| !isset($evt->ORGANIZER)
) {
// Bad data
return;
}
// \OC::$server->getLogger()->error('DL Debug: M7');
$utz = $utils->getCalendarTimezone($userId, $utils->transformCalInfo($calendarData));
try {
$now = new \DateTime('now', $utz);
} catch (\Exception $e) {
$this->logger->error($e->getMessage() . ", timezone: " . $utz->getName());
return;
}
// TODO: this needs to be fixed @see BackendUtils->encodeCalendarData
$now_f = (float)$now->format(BackendUtils::FLOAT_TIME_FORMAT);
if ($now_f > (float)str_replace("T", ".", $evt->DTEND->getRawMimeDirValue())
&& $now_f > $utils->getHashDTStart($hash)
) {
// Event is in the past
return;
}
// \OC::$server->getLogger()->error('DL Debug: M8');
$hash_ch = $utils->getHashChanges($hash, $evt);
$att = $utils->getAttendee($evt);
if ($att === null
|| ($hint === HintVar::APPT_NONE
&& ($att->parameters['PARTSTAT']->getValue() === 'DECLINED'
|| ($hash_ch === null && !$isDelete)
|| $utils->isApptCancelled($hash, $evt) === true
)
)) {
// Bad attendee value or no significant external changes
return;
}
// \OC::$server->getLogger()->error('DL Debug: M9');
$to_name = $att->parameters['CN']->getValue();
if (empty($to_name) || preg_match('/[^\PC ]/u', $to_name)) {
$this->logger->error("invalid attendee name");
return;
}
// \OC::$server->getLogger()->error('DL Debug: M10');
$mailer = $this->mailer;
$att_v = $att->getValue();
$to_email = substr($att_v, strpos($att_v, ":") + 1);
if ($mailer->validateMailAddress($to_email) === false) {
$this->logger->error("invalid attendee email");
return;
}
// \OC::$server->getLogger()->error('DL Debug: M11');
if ($doc) {
$date_time = $utils->getDateTimeString(
$evt->DTSTART->getDateTime(),
$doc->attendeeTimezone
);
} else {
$date_time = $utils->getDateTimeString(
$evt->DTSTART->getDateTime(),
$evt->{BackendUtils::TZI_PROP}->getValue()
);
}
list($org_email, $org_name, $org_phone) = $this->getOrgInfo();
$is_cancelled = false;
$tmpl = $this->getEmailTemplate();
// Message the organizer
$om_prefix = "";
// Description can get overwritten when the .ics attachment is constructed, so get it here
if (isset($evt->DESCRIPTION)) {
$om_info = $evt->DESCRIPTION->getValue();
} else {
$om_info = "";
}
// cancellation link for confirmation emails
$cnl_lnk_url = "";
// this is used to stop .ics file attachment on external actions when PARTSTAT:NEEDS-ACTION
$no_ics = false;
$talk_link_txt = '';
// \OC::$server->getLogger()->error('DL Debug: M12');
$ext_event_type = -1;
if ($hint === HintVar::APPT_BOOK) {
// Just booked, send email to the attendee requesting confirmation...
// TRANSLATORS Subject for email, Ex: {{Organization Name}} Appointment (action needed)
$tmpl->setSubject($this->l10N->t("%s appointment (action needed)", [$org_name]));
$tmpl->addHeading(" "); // spacer
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS First line of email, Ex: Dear {{Customer Name}},
$this->l10N->t("Dear %s,", [$to_name])
]));
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS Main part of email, Ex: The {{Organization Name}} appointment scheduled for {{Date Time}} is awaiting your confirmation.
$this->l10N->t('The %1$s appointment scheduled for %2$s is awaiting your confirmation.', [$org_name, $date_time])
]));
list($btn_url, $btn_tkn) = $this->makeBtnInfo(
$userId, $pageId, $embed,
$objectData['uri'],
$config);
$tmpl->addBodyButtonGroup(
$this->l10N->t("Confirm"),
$btn_url . '1' . $btn_tkn,
$this->l10N->t("Cancel"),
$btn_url . '0' . $btn_tkn
);
if (!empty($settings[BackendUtils::EML_VLD_TXT])) {
$this->addMoreEmailText($tmpl, $settings[BackendUtils::EML_VLD_TXT]);
}
if ($settings[BackendUtils::EML_MREQ]) {
$om_prefix = $this->l10N->t("Appointment pending");
}
} elseif ($hint === HintVar::APPT_CONFIRM) {
// Confirm link in the email is clicked ...
// ... or the email validation step is skipped
// TRANSLATORS Subject for email, Ex: {{Organization Name}} Appointment is Confirmed
$tmpl->setSubject($this->l10N->t("%s Appointment is confirmed", [$org_name]));
$tmpl->addHeading(" "); // spacer
$tmpl->addBodyText(...$this->formatEmailBodyHtml([$to_name . ","]));
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS Main body of email,Ex: Your {{Organization Name}} appointment scheduled for {{Date Time}} is now confirmed.
$this->l10N->t('Your %1$s appointment scheduled for %2$s is now confirmed.', [$org_name, $date_time])
]));
// add cancellation link
list($btn_url, $btn_tkn) = $this->makeBtnInfo(
$userId, $pageId, $embed,
$objectData['uri'],
$config);
$cnl_lnk_url = $btn_url . "0" . $btn_tkn;
if ($doc) {
$videoType = $this->getVideoType($settings);
if ($videoType !== self::VIDEO_NONE) {
$talk_link_txt = $this->addVideoLinkInfo(
$userId, $tmpl, $doc, $settings,
$config->getUserValue($userId, $this->appName, "c" . "nk")
);
if (($videoType === self::VIDEO_TALK
&& $settings[BackendUtils::TALK_FORM_ENABLED])
|| ($videoType === self::VIDEO_BBB
&& $settings[BackendUtils::BBB_FORM_ENABLED])
) {
// we need 'Meeting Type' and `Type Change` info
$has_link = !empty($talk_link_txt);
$tmpl->addBodyText(...$this->formatEmailBodyHtml([$this->makeMeetingTypeInfo($settings, $has_link)]));
$this->addTypeChangeLink($tmpl, $settings, $btn_url . "3" . $btn_tkn, $has_link);
}
}
} else {
if (!empty($xad) && count($xad) > 4) {
$has_link = strlen($xad[4]) > 1;
if ($settings[BackendUtils::TALK_ENABLED]) {
if ($has_link) {
$ti = new TalkIntegration($settings, $utils);
// add talk link info
$talk_link_txt = $this->addTalkInfo(
$tmpl, $xad, $ti, $settings,
$config->getUserValue($userId, $this->appName, "c" . "nk"));
}
if ($settings[BackendUtils::TALK_FORM_ENABLED] === true) {
if (!$has_link) {
// add in-person meeting type
$tmpl->addBodyText(...$this->formatEmailBodyHtml([$this->makeMeetingTypeInfo($settings, $has_link)]));
}
$this->addTypeChangeLink($tmpl, $settings, $btn_url . "3" . $btn_tkn, $has_link);
}
}
}
}
if (!empty($settings[BackendUtils::EML_CNF_TXT])) {
$this->addMoreEmailText($tmpl, $settings[BackendUtils::EML_CNF_TXT]);
} elseif (isset($evt->LOCATION) && filter_var($evt->LOCATION->getValue(), FILTER_VALIDATE_URL) !== false) {
$locationUrl=$evt->LOCATION->getValue();
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
$this->l10N->t('Location: ') . '<a href="' . $locationUrl . '">' . $locationUrl . '</a>',
$this->l10N->t('Location: ') . $locationUrl
]));
}
if ($settings[BackendUtils::EML_MCONF]) {
$om_prefix = $this->l10N->t("Appointment confirmed");
}
$ext_event_type = 0;
} elseif ($hint === HintVar::APPT_CANCEL || $isDelete) {
// Canceled or deleted
if ($hint !== HintVar::APPT_NONE) {
// Cancelled by the attendee (via the email link)
// TRANSLATORS Subject for email, Ex: {{Organization Name}} Appointment is Canceled
$tmpl->setSubject($this->l10N->t("%s Appointment is canceled", [$org_name]));
} else {
// Cancelled/deleted by the organizer
// TRANSLATORS Subject for email, Ex: {{Organization Name}} Appointment Status Changed
$tmpl->setSubject($this->l10N->t("%s appointment status changed", [$org_name]));
}
$tmpl->addHeading(" "); // spacer
$tmpl->addBodyText(...$this->formatEmailBodyHtml([$to_name . ","]));
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS Main body of email,Ex: Your {{Organization Name}} appointment scheduled for {{Date Time}} is now canceled.
$this->l10N->t('Your %1$s appointment scheduled for %2$s is now canceled.', [$org_name, $date_time])
]));
$is_cancelled = true;
if ($settings[BackendUtils::EML_MCNCL] && $hint !== HintVar::APPT_NONE) {
$om_prefix = $this->l10N->t("Appointment canceled");
}
if ($isDelete) {
if ($doc) {
if (!empty($doc->talkToken)) {
if ($settings[BackendUtils::TALK_DEL_ROOM] === true) {
$ti = new TalkIntegration($settings, $utils);
$ti->deleteRoom($doc->talkToken);
}
}
if (!empty($doc->bbbToken)) {
if ($settings[BackendUtils::BBB_DEL_ROOM] === true) {
$bi = \OC::$server->get(BbbIntegration::class);
$bi->deleteRoom($doc->bbbToken, $userId);
}
}
} else {
if ($settings[BackendUtils::TALK_DEL_ROOM] === true) {
if (!empty($xad) && count($xad) > 4 && strlen($xad[4]) > 1) {
$ti = new TalkIntegration($settings, $utils);
$ti->deleteRoom($xad[4]);
}
}
}
}
$ext_event_type = 1;
} elseif ($hint === HintVar::APPT_TYPE_CHANGE) {
$tmpl->setSubject($this->l10N->t("%s Appointment update", [$org_name]));
$tmpl->addHeading(" "); // spacer
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS First line of email, Ex: Dear {{Customer Name}},
$this->l10N->t("Dear %s,", [$to_name])
]));
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS Main part of email
$this->l10N->t("Your appointment details have changed. Please review information below.")
]));
list($btn_url, $btn_tkn) = $this->makeBtnInfo(
$userId, $pageId, $embed,
$objectData['uri'],
$config);
if ($doc) {
$has_link = !empty($doc->talkToken . $doc->bbbToken);
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->makeMeetingTypeInfo($settings, $has_link)));
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t("Date/Time: %s", [$date_time])));
$talk_link_txt = $this->addVideoLinkInfo(
$userId, $tmpl, $doc, $settings,
$config->getUserValue($userId, $this->appName, "c" . "nk")
);
} elseif (!empty($xad) && count($xad) > 4) {
$_talkToken = $xad[4];
$has_link = strlen($_talkToken) > 1;
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->makeMeetingTypeInfo($settings, $has_link)));
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t("Date/Time: %s", [$date_time])));
$ti = new TalkIntegration($settings, $utils);
$talk_link_txt = $this->addTalkInfo(
$tmpl, $xad, $ti, $settings,
$config->getUserValue($userId, $this->appName, "c" . "nk"));
}
$this->addTypeChangeLink($tmpl, $settings, $btn_url . "3" . $btn_tkn, $has_link);
$cnl_lnk_url = $btn_url . "0" . $btn_tkn;
if ($settings[BackendUtils::EML_MCONF]) {
$om_prefix = $this->l10N->t("Appointment updated");
}
$ext_event_type = 3;
} elseif ($hint === HintVar::APPT_NONE) {
// Organizer or External Action (something changed...)
// TRANSLATORS Subject for email, Ex: {{Organization Name}} appointment status update
$tmpl->setSubject($this->l10N->t("%s Appointment update", [$org_name]));
$tmpl->addHeading(" "); // spacer
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS First line of email, Ex: Dear {{Customer Name}},
$this->l10N->t("Dear %s,", [$to_name])
]));
$tmpl->addBodyText(...$this->formatEmailBodyHtml([
// TRANSLATORS Main part of email
$this->l10N->t("Your appointment details have changed. Please review information below.")
]));
$pst = $att->parameters['PARTSTAT']->getValue();
$ti = new TalkIntegration($settings, $utils);
// Add changes details...
if ($hash_ch[0] === true) { // DTSTART changed
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t("Date/Time: %s", [$date_time])));
// if we have a Talk room we need to update the room's name (and lobby time if implemented)
if ($doc) {
$videoType = $this->getVideoType($settings);
if ($videoType !== self::VIDEO_NONE) {
if ($videoType === self::VIDEO_TALK && !empty($doc->talkToken)) {
$ti->renameRoom(
$doc->talkToken, $to_name, $evt->DTSTART, $userId
);
} elseif ($videoType === self::VIDEO_BBB && !empty($doc->bbbToken)) {
$bi = \OC::$server->get(BbbIntegration::class);
$bi->renameRoom(
$doc->bbbToken, $to_name, $evt->DTSTART, $userId);
}
}
} elseif (!empty($xad) && count($xad) > 4 && strlen($xad[4]) > 1) {
$ti->renameRoom(
$xad[4], $to_name, $evt->DTSTART, $userId
);
}
}
$ext_event_type = 2;
if ($hash_ch[1] === true) { //STATUS changed
if ($evt->STATUS->getValue() === 'CANCELLED') {
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t('Status: Canceled')));
$is_cancelled = true;
$ext_event_type = 1;
} else {
// Non cancelled status is determined by the attendee's PARTSTAT
if ($pst === 'NEEDS-ACTION') {
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t('Status: Pending confirmation')));
$ext_event_type = -1; // no extNotify when pending
} elseif ($pst === 'ACCEPTED') {
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t('Status: Confirmed')));
$ext_event_type = 0;
}
}
}
if ($hash_ch[2] === true && isset($evt->LOCATION)) { // LOCATION changed
$tmpl->addBodyListItem(...$this->formatEmailListItem(
$this->l10N->t("Location: %s", [$evt->LOCATION->getValue()])));
}
list($btn_url, $btn_tkn) = $this->makeBtnInfo(
$userId, $pageId, $embed,
$objectData['uri'],
$config);
// if NOT cancelled and PARTSTAT:NEEDS-ACTION we ADD BUTTONS before the "If you have any questions..." text
if ($is_cancelled === false && $pst === 'NEEDS-ACTION') {
$no_ics = true;
$tmpl->addBodyButtonGroup(
$this->l10N->t("Confirm"),
$btn_url . '1' . $btn_tkn,
$this->l10N->t("Cancel"),
$btn_url . '0' . $btn_tkn
);
}
if ($doc) {
$videoType = $this->getVideoType($settings);
if ($videoType !== self::VIDEO_NONE) {