/
SOGoAppointmentObject.m
2456 lines (2123 loc) · 86.2 KB
/
SOGoAppointmentObject.m
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
/*
Copyright (C) 2007-2016 Inverse inc.
This file is part of SOGo
SOGo is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
SOGo is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with OGo; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
#import <Foundation/NSCalendarDate.h>
#import <Foundation/NSTimeZone.h>
#import <Foundation/NSValue.h>
#import <NGObjWeb/NSException+HTTP.h>
#import <NGObjWeb/WOContext+SoObjects.h>
#import <NGObjWeb/WOResponse.h>
#import <NGExtensions/NGCalendarDateRange.h>
#import <NGExtensions/NSNull+misc.h>
#import <NGExtensions/NSObject+Logs.h>
#import <NGCards/iCalDateTime.h>
#import <NGCards/iCalEvent.h>
#import <NGCards/iCalToDo.h>
#import <NGCards/NSCalendarDate+NGCards.h>
#import <SaxObjC/XMLNamespaces.h>
#import <NGCards/iCalDateTime.h>
#import <NGCards/iCalTimeZone.h>
#import <NGCards/iCalTimeZonePeriod.h>
#import <NGCards/iCalToDo.h>
#import <NGCards/NSString+NGCards.h>
#import <SOGo/NSArray+Utilities.h>
#import <SOGo/NSDictionary+Utilities.h>
#import <SOGo/NSObject+DAV.h>
#import <SOGo/NSString+Utilities.h>
#import <SOGo/SOGoDateFormatter.h>
#import <SOGo/SOGoGroup.h>
#import <SOGo/SOGoUser.h>
#import <SOGo/SOGoUserSettings.h>
#import <SOGo/SOGoDomainDefaults.h>
#import <SOGo/WORequest+SOGo.h>
#import "iCalCalendar+SOGo.h"
#import "iCalEventChanges+SOGo.h"
#import "iCalEntityObject+SOGo.h"
#import "iCalPerson+SOGo.h"
#import "NSArray+Appointments.h"
#import "SOGoAppointmentFolder.h"
#import "SOGoAppointmentOccurence.h"
#import "SOGoAppointmentObject.h"
@implementation SOGoAppointmentObject
- (NSString *) componentTag
{
return @"vevent";
}
- (SOGoComponentOccurence *) occurence: (iCalRepeatableEntityObject *) occ
{
NSArray *allEvents;
allEvents = [[occ parent] events];
return [SOGoAppointmentOccurence
occurenceWithComponent: occ
withMasterComponent: [allEvents objectAtIndex: 0]
inContainer: self];
}
/**
* Return a new exception in the recurrent event.
* @param theRecurrenceID the ID of the occurence.
* @return a new occurence.
*/
- (iCalRepeatableEntityObject *) newOccurenceWithID: (NSString *) theRecurrenceID
{
iCalEvent *newOccurence, *master;
NSCalendarDate *date, *firstDate;
unsigned int interval, nbrDays;
newOccurence = (iCalEvent *) [super newOccurenceWithID: theRecurrenceID];
date = [newOccurence recurrenceId];
master = [self component: NO secure: NO];
firstDate = [master startDate];
interval = [[master endDate]
timeIntervalSinceDate: firstDate];
if ([newOccurence isAllDay])
{
nbrDays = ((float) abs (interval) / 86400);
[newOccurence setAllDayWithStartDate: date
duration: nbrDays];
}
else
{
[newOccurence setStartDate: date];
[newOccurence setEndDate: [date addYear: 0
month: 0
day: 0
hour: 0
minute: 0
second: interval]];
}
return newOccurence;
}
- (iCalRepeatableEntityObject *) lookupOccurrence: (NSString *) recID
{
return [[self calendar: NO secure: NO] eventWithRecurrenceID: recID];
}
- (SOGoAppointmentObject *) _lookupEvent: (NSString *) eventUID
forUID: (NSString *) uid
{
SOGoAppointmentFolder *folder;
SOGoAppointmentObject *object;
NSArray *folders;
NSEnumerator *e;
NSString *possibleName;
object = nil;
folders = [container lookupCalendarFoldersForUID: uid];
e = [folders objectEnumerator];
while ( object == nil && (folder = [e nextObject]) )
{
object = [folder lookupName: nameInContainer
inContext: context
acquire: NO];
if ([object isKindOfClass: [NSException class]] || [object isNew])
{
possibleName = [folder resourceNameForEventUID: eventUID];
if (possibleName)
{
object = [folder lookupName: possibleName
inContext: context acquire: NO];
if ([object isKindOfClass: [NSException class]] || [object isNew])
object = nil;
}
else
object = nil;
}
}
if (!object)
{
// Create the event in the user's personal calendar.
folder = [[SOGoUser userWithLogin: uid]
personalCalendarFolderInContext: context];
object = [SOGoAppointmentObject objectWithName: nameInContainer
inContainer: folder];
[object setIsNew: YES];
}
return object;
}
//
//
//
- (void) _addOrUpdateEvent: (iCalEvent *) theEvent
forUID: (NSString *) theUID
owner: (NSString *) theOwner
{
if (![theUID isEqualToString: theOwner])
{
SOGoAppointmentObject *attendeeObject;
iCalCalendar *iCalendarToSave;
iCalendarToSave = nil;
attendeeObject = [self _lookupEvent: [theEvent uid] forUID: theUID];
// We must add an occurence to a non-existing event. We have
// to handle this with care, as in the postCalDAVEventRequestTo:from:
if ([attendeeObject isNew] && [theEvent recurrenceId])
{
iCalEvent *ownerEvent;
iCalPerson *person;
SOGoUser *user;
// We check if the attendee that was added to a single occurence is
// present in the master component. If not, we add it with a participation
// status set to "DECLINED".
ownerEvent = [[[theEvent parent] events] objectAtIndex: 0];
user = [SOGoUser userWithLogin: theUID];
if (![ownerEvent userAsAttendee: user])
{
// Update the master event in the owner's calendar with the
// status of the new attendee set as "DECLINED".
person = [iCalPerson elementWithTag: @"attendee"];
[person setCn: [user cn]];
[person setEmail: [[user allEmails] objectAtIndex: 0]];
[person setParticipationStatus: iCalPersonPartStatDeclined];
[person setRsvp: @"TRUE"];
[person setRole: @"REQ-PARTICIPANT"];
[ownerEvent addToAttendees: person];
iCalendarToSave = [ownerEvent parent];
}
}
else
{
// TODO : if [theEvent recurrenceId], only update this occurrence
// in attendee's calendar
// TODO : when updating the master event, handle exception dates
// in attendee's calendar (add exception dates and remove matching
// occurrences) -- see _updateRecurrenceIDsWithEvent:
iCalendarToSave = [theEvent parent];
}
// Save the event in the attendee's calendar
if (iCalendarToSave)
[attendeeObject saveCalendar: iCalendarToSave];
}
}
//
//
//
- (void) _removeEventFromUID: (NSString *) theUID
owner: (NSString *) theOwner
withRecurrenceId: (NSCalendarDate *) recurrenceId
{
if (![theUID isEqualToString: theOwner])
{
SOGoAppointmentFolder *folder;
SOGoAppointmentObject *object;
iCalEntityObject *currentOccurence;
iCalRepeatableEntityObject *event;
iCalCalendar *calendar;
NSCalendarDate *currentId;
NSArray *occurences;
int max, count;
// Invitations are always written to the personal folder; it's not necessay
// to look into all folders of the user
folder = [[SOGoUser userWithLogin: theUID]
personalCalendarFolderInContext: context];
object = [folder lookupName: nameInContainer
inContext: context acquire: NO];
if (![object isKindOfClass: [NSException class]])
{
if (recurrenceId == nil)
[object delete];
else
{
calendar = [object calendar: NO secure: NO];
// If recurrenceId is defined, remove the occurence from
// the repeating event.
occurences = [calendar events];
max = [occurences count];
count = 1;
while (count < max)
{
currentOccurence = [occurences objectAtIndex: count];
currentId = [currentOccurence recurrenceId];
if ([currentId compare: recurrenceId] == NSOrderedSame)
{
[[calendar children] removeObject: currentOccurence];
break;
}
count++;
}
// Add an date exception.
event = (iCalRepeatableEntityObject*)[calendar firstChildWithTag: [object componentTag]];
[event addToExceptionDates: recurrenceId];
[event increaseSequence];
// We save the updated iCalendar in the database.
[object saveCalendar: calendar];
}
}
}
}
//
//
//
- (void) _handleRemovedUsers: (NSArray *) attendees
withRecurrenceId: (NSCalendarDate *) recurrenceId
{
NSEnumerator *enumerator;
iCalPerson *currentAttendee;
NSString *currentUID;
enumerator = [attendees objectEnumerator];
while ((currentAttendee = [enumerator nextObject]))
{
currentUID = [currentAttendee uidInContext: context];
if (currentUID)
[self _removeEventFromUID: currentUID
owner: owner
withRecurrenceId: recurrenceId];
}
}
//
//
//
- (void) _removeDelegationChain: (iCalPerson *) delegate
inEvent: (iCalEvent *) event
{
NSString *delegatedTo, *mailTo;
delegatedTo = [delegate delegatedTo];
if ([delegatedTo length] > 0)
{
mailTo = [delegatedTo rfc822Email];
delegate = [event findAttendeeWithEmail: mailTo];
if (delegate)
{
[self _removeDelegationChain: delegate
inEvent: event];
[event removeFromAttendees: delegate];
}
else
[self errorWithFormat:@"broken chain: delegate with email '%@' was not found", mailTo];
}
}
//
// This method returns YES when any attendee has been removed
// and NO otherwise.
//
- (BOOL) _requireResponseFromAttendees: (iCalEvent *) event
{
NSArray *attendees;
iCalPerson *currentAttendee;
BOOL listHasChanged = NO;
int count, max;
attendees = [event attendees];
max = [attendees count];
for (count = 0; count < max; count++)
{
currentAttendee = [attendees objectAtIndex: count];
if ([[currentAttendee delegatedTo] length] > 0)
{
[self _removeDelegationChain: currentAttendee
inEvent: event];
[currentAttendee setDelegatedTo: nil];
listHasChanged = YES;
}
[currentAttendee setRsvp: @"TRUE"];
[currentAttendee setParticipationStatus: iCalPersonPartStatNeedsAction];
}
return listHasChanged;
}
//
//
//
- (BOOL) _shouldScheduleEvent: (iCalPerson *) thePerson
{
//NSArray *userAgents;
NSString *v;
BOOL b;
//int i;
b = YES;
if (thePerson && (v = [thePerson value: 0 ofAttribute: @"SCHEDULE-AGENT"]))
{
if ([v caseInsensitiveCompare: @"NONE"] == NSOrderedSame ||
[v caseInsensitiveCompare: @"CLIENT"] == NSOrderedSame)
b = NO;
}
//
// If we have to deal with Thunderbird/Lightning, we always send invitation
// reponses, as Lightning v2.6 (at least this version) sets SCHEDULE-AGENT
// to NONE/CLIENT when responding to an external invitation received by
// SOGo - so no invitation responses are ever sent by Lightning. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=865726 and
// https://bugzilla.mozilla.org/show_bug.cgi?id=997784
//
// This code has been disabled - see 0003274.
//
#if 0
userAgents = [[context request] headersForKey: @"User-Agent"];
for (i = 0; i < [userAgents count]; i++)
{
if ([[userAgents objectAtIndex: i] rangeOfString: @"Thunderbird"].location != NSNotFound &&
[[userAgents objectAtIndex: i] rangeOfString: @"Lightning"].location != NSNotFound)
{
b = YES;
break;
}
}
#endif
return b;
}
//
//
//
- (void) _handleSequenceUpdateInEvent: (iCalEvent *) newEvent
ignoringAttendees: (NSArray *) attendees
fromOldEvent: (iCalEvent *) oldEvent
{
NSMutableArray *updateAttendees;
NSEnumerator *enumerator;
iCalPerson *currentAttendee;
NSString *currentUID;
updateAttendees = [NSMutableArray arrayWithArray: [newEvent attendees]];
[updateAttendees removeObjectsInArray: attendees];
enumerator = [updateAttendees objectEnumerator];
while ((currentAttendee = [enumerator nextObject]))
{
currentUID = [currentAttendee uidInContext: context];
if (currentUID)
[self _addOrUpdateEvent: newEvent
forUID: currentUID
owner: owner];
}
if ([self _shouldScheduleEvent: [newEvent organizer]])
[self sendEMailUsingTemplateNamed: @"Update"
forObject: [newEvent itipEntryWithMethod: @"request"]
previousObject: oldEvent
toAttendees: updateAttendees
withType: @"calendar:invitation-update"];
}
// This method scans the list of attendees.
- (NSException *) _handleAttendeesAvailability: (NSArray *) theAttendees
forEvent: (iCalEvent *) theEvent
{
iCalPerson *currentAttendee;
SOGoUser *user;
SOGoUserSettings *us;
NSMutableArray *unavailableAttendees;
NSEnumerator *enumerator;
NSString *currentUID, *ownerUID;
NSMutableString *reason;
NSDictionary *values;
NSMutableDictionary *value, *moduleSettings;
id whiteList;
int i, count;
i = count = 0;
// Build list of the attendees uids
unavailableAttendees = [[NSMutableArray alloc] init];
enumerator = [theAttendees objectEnumerator];
ownerUID = [[[self context] activeUser] login];
while ((currentAttendee = [enumerator nextObject]))
{
currentUID = [currentAttendee uidInContext: context];
if (currentUID)
{
user = [SOGoUser userWithLogin: currentUID];
us = [user userSettings];
moduleSettings = [us objectForKey:@"Calendar"];
// Check if the user prevented their account from beeing invited to events
if ([[moduleSettings objectForKey:@"PreventInvitations"] boolValue])
{
// Check if the user have a whiteList
whiteList = [moduleSettings objectForKey:@"PreventInvitationsWhitelist"];
// For backward <= 2.2.17 compatibility
if ([whiteList isKindOfClass: [NSString class]])
whiteList = [whiteList objectFromJSONString];
// If the filter have a hit, do not add the currentUID to the unavailableAttendees array
if (![whiteList objectForKey:ownerUID])
{
values = [NSDictionary dictionaryWithObject:[user cn] forKey:@"Cn"];
[unavailableAttendees addObject:values];
}
}
}
}
count = [unavailableAttendees count];
if (count > 0)
{
reason = [NSMutableString stringWithString:[self labelForKey: @"Inviting the following persons is prohibited:"]];
// Add all the unavailable users in the warning message
for (i = 0; i < count; i++)
{
value = [unavailableAttendees objectAtIndex:i];
[reason appendString:[value keysWithFormat: @"\n %{Cn}"]];
if (i < count-2)
[reason appendString:@", "];
}
[unavailableAttendees release];
return [NSException exceptionWithHTTPStatus:409 reason: reason];
}
[unavailableAttendees release];
return nil;
}
//
// This methods scans the list of attendees. If they are
// considered as resource, it checks for conflicting
// dates for the event and potentially auto-accept/decline
// the invitation.
//
// For normal attendees, it'll return an exception with
// conflicting dates, unless we force the save.//
// We check for between startDate + 1 second and
// endDate - 1 second
//
// Note that it doesn't matter if it changes the participation
// status since in case of an error, nothing will get saved.
//
- (NSException *) _handleAttendeesConflicts: (NSArray *) theAttendees
forEvent: (iCalEvent *) theEvent
force: (BOOL) forceSave
{
iCalPerson *currentAttendee;
NSMutableArray *attendees;
NSEnumerator *enumerator;
NSString *currentUID;
SOGoUser *user, *currentUser;
_resourceHasAutoAccepted = NO;
// Build a list of the attendees uids
attendees = [NSMutableArray arrayWithCapacity: [theAttendees count]];
enumerator = [theAttendees objectEnumerator];
while ((currentAttendee = [enumerator nextObject]))
{
currentUID = [currentAttendee uidInContext: context];
if (currentUID)
{
[attendees addObject: currentUID];
}
}
// If the active user is not the owner of the calendar, check possible conflict when
// the owner is a resource
currentUser = [context activeUser];
if (!activeUserIsOwner && ![currentUser isSuperUser])
{
[attendees addObject: owner];
}
enumerator = [attendees objectEnumerator];
while ((currentUID = [enumerator nextObject]))
{
NSCalendarDate *start, *end, *rangeStartDate, *rangeEndDate;
SOGoAppointmentFolder *folder;
NGCalendarDateRange *range;
NSMutableArray *fbInfo;
NSArray *allOccurences;
BOOL must_delete;
int i, j, delta;
user = [SOGoUser userWithLogin: currentUID];
// We get the start/end date for our conflict range. If the event to be added is recurring, we
// check for at least a year to start with.
start = [[theEvent startDate] dateByAddingYears: 0 months: 0 days: 0 hours: 0 minutes: 0 seconds: 1];
end = [[theEvent endDate] dateByAddingYears: ([theEvent isRecurrent] ? 1 : 0) months: 0 days: 0 hours: 0 minutes: 0 seconds: -1];
folder = [user personalCalendarFolderInContext: context];
// Deny access to the resource if the ACLs don't allow the user
if ([user isResource] && ![folder aclSQLListingFilter])
{
NSDictionary *values;
NSString *reason;
values = [NSDictionary dictionaryWithObjectsAndKeys:
[user cn], @"Cn",
[user systemEmail], @"SystemEmail", nil];
reason = [values keysWithFormat: [self labelForKey: @"Cannot access resource: \"%{Cn} %{SystemEmail}\""]];
return [NSException exceptionWithHTTPStatus:409 reason: reason];
}
fbInfo = [NSMutableArray arrayWithArray: [folder fetchFreeBusyInfosFrom: start
to: end]];
//
// We must also check here for repetitive events that don't overlap our event.
// We remove all events that don't overlap. The events here are already
// decomposed.
//
if ([theEvent isRecurrent])
allOccurences = [theEvent recurrenceRangesWithinCalendarDateRange: [NGCalendarDateRange calendarDateRangeWithStartDate: start
endDate: end]
firstInstanceCalendarDateRange: [NGCalendarDateRange calendarDateRangeWithStartDate: [theEvent startDate]
endDate: [theEvent endDate]]];
else
allOccurences = nil;
for (i = [fbInfo count]-1; i >= 0; i--)
{
// We MUST use the -uniqueChildWithTag method here because the event has been flattened, so its timezone has been
// modified in SOGoAppointmentFolder: -fixupCycleRecord: ....
rangeStartDate = [[fbInfo objectAtIndex: i] objectForKey: @"startDate"];
delta = [[rangeStartDate timeZoneDetail] timeZoneSecondsFromGMT] - [[[(iCalDateTime *)[theEvent uniqueChildWithTag: @"dtstart"] timeZone] periodForDate: [theEvent startDate]] secondsOffsetFromGMT];
rangeStartDate = [rangeStartDate dateByAddingYears: 0 months: 0 days: 0 hours: 0 minutes: 0 seconds: delta];
rangeEndDate = [[fbInfo objectAtIndex: i] objectForKey: @"endDate"];
delta = [[rangeEndDate timeZoneDetail] timeZoneSecondsFromGMT] - [[[(iCalDateTime *)[theEvent uniqueChildWithTag: @"dtend"] timeZone] periodForDate: [theEvent endDate]] secondsOffsetFromGMT];
rangeEndDate = [rangeEndDate dateByAddingYears: 0 months: 0 days: 0 hours: 0 minutes: 0 seconds: delta];
range = [NGCalendarDateRange calendarDateRangeWithStartDate: rangeStartDate
endDate: rangeEndDate];
// We first remove any occurences in the freebusy that corresponds to the
// current event. We do this to avoid raising a conflict if we move a 1 hour
// meeting from 12:00-13:00 to 12:15-13:15. We would overlap on ourself otherwise.
if ([[[fbInfo objectAtIndex: i] objectForKey: @"c_uid"] compare: [theEvent uid]] == NSOrderedSame)
{
[fbInfo removeObjectAtIndex: i];
continue;
}
// No need to check if the event isn't recurrent here as it's handled correctly
// when we compute the "end" date.
if ([allOccurences count])
{
must_delete = YES;
for (j = 0; j < [allOccurences count]; j++)
{
if ([range doesIntersectWithDateRange: [allOccurences objectAtIndex: j]])
{
must_delete = NO;
break;
}
}
if (must_delete)
[fbInfo removeObjectAtIndex: i];
}
}
// Find the attendee associated to the current UID
for (i = 0; i < [theAttendees count]; i++)
{
currentAttendee = [theAttendees objectAtIndex: i];
if ([[currentAttendee uidInContext: context] isEqualToString: currentUID])
break;
else
currentAttendee = nil;
}
if ([fbInfo count])
{
SOGoDateFormatter *formatter;
formatter = [[context activeUser] dateFormatterInContext: context];
if ([user isResource])
{
// If we always force the auto-accept if numberOfSimultaneousBookings <= 0 (ie., no limit
// is imposed) or if numberOfSimultaneousBookings is greater than the number of
// overlapping events
if ([user numberOfSimultaneousBookings] <= 0 ||
[user numberOfSimultaneousBookings] > [fbInfo count])
{
if (currentAttendee)
{
[[currentAttendee attributes] removeObjectForKey: @"RSVP"];
[currentAttendee setParticipationStatus: iCalPersonPartStatAccepted];
_resourceHasAutoAccepted = YES;
}
}
else
{
iCalCalendar *calendar;
NSDictionary *values, *info;
NSString *reason;
iCalEvent *event;
calendar = [iCalCalendar parseSingleFromSource: [[fbInfo objectAtIndex: 0] objectForKey: @"c_content"]];
event = [[calendar events] lastObject];
values = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat: @"%d", [user numberOfSimultaneousBookings]], @"NumberOfSimultaneousBookings",
[user cn], @"Cn",
[user systemEmail], @"SystemEmail",
([event summary] ? [event summary] : @""), @"EventTitle",
[formatter formattedDateAndTime: [[fbInfo objectAtIndex: 0] objectForKey: @"startDate"]], @"StartDate",
nil];
reason = [values keysWithFormat: [self labelForKey: @"Maximum number of simultaneous bookings (%{NumberOfSimultaneousBookings}) reached for resource \"%{Cn} %{SystemEmail}\". The conflicting event is \"%{EventTitle}\", and starts on %{StartDate}."]];
info = [NSDictionary dictionaryWithObject: reason forKey: @"reject"];
return [NSException exceptionWithHTTPStatus: 409
reason: [info jsonRepresentation]];
}
}
//
// We are dealing with a normal attendee. Lets check if we have conflicts, unless
// we are being asked to force the save anyway
//
else if (!forceSave)
{
NSMutableDictionary *info;
NSMutableArray *conflicts;
id o;
info = [NSMutableDictionary dictionary];
conflicts = [NSMutableArray array];
if (currentAttendee)
{
if ([currentAttendee cn])
[info setObject: [currentAttendee cn] forKey: @"attendee_name"];
if ([currentAttendee rfc822Email])
[info setObject: [currentAttendee rfc822Email] forKey: @"attendee_email"];
}
for (i = 0; i < [fbInfo count]; i++)
{
o = [fbInfo objectAtIndex: i];
[conflicts addObject: [NSDictionary dictionaryWithObjectsAndKeys: [formatter formattedDateAndTime: [o objectForKey: @"startDate"]], @"startDate",
[formatter formattedDateAndTime: [o objectForKey: @"endDate"]], @"endDate", nil]];
}
[info setObject: conflicts forKey: @"conflicts"];
return [NSException exceptionWithHTTPStatus: 409
reason: [info jsonRepresentation]];
}
} // if ([fbInfo count]) ...
else if (currentAttendee && [user isResource])
{
// No conflict, we auto-accept. We do this for resources automatically if no
// double-booking is observed. If it's not the desired behavior, just don't
// set the resource as one!
[[currentAttendee attributes] removeObjectForKey: @"RSVP"];
[currentAttendee setParticipationStatus: iCalPersonPartStatAccepted];
_resourceHasAutoAccepted = YES;
}
} // if ([user isResource]) ...
return nil;
}
//
//
//
- (NSException *) _handleAddedUsers: (NSArray *) attendees
fromEvent: (iCalEvent *) newEvent
force: (BOOL) forceSave
{
iCalPerson *currentAttendee;
NSEnumerator *enumerator;
NSString *currentUID;
NSException *e;
// We check for conflicts
if ((e = [self _handleAttendeesConflicts: attendees forEvent: newEvent force: forceSave]))
return e;
if ((e = [self _handleAttendeesAvailability: attendees forEvent: newEvent]))
return e;
enumerator = [attendees objectEnumerator];
while ((currentAttendee = [enumerator nextObject]))
{
currentUID = [currentAttendee uidInContext: context];
if (currentUID)
[self _addOrUpdateEvent: newEvent
forUID: currentUID
owner: owner];
}
return nil;
}
//
//
//
- (void) _addOrDeleteAttendees: (NSArray *) theAttendees
inRecurrenceExceptionsForEvent: (iCalEvent *) theEvent
add: (BOOL) shouldAdd
{
NSArray *events;
iCalEvent *e;
int i,j;
// We don't add/delete attendees to all recurrence exceptions if
// the modification was actually NOT made on the master event
if ([theEvent recurrenceId])
return;
events = [[theEvent parent] events];
for (i = 0; i < [events count]; i++)
{
e = [events objectAtIndex: i];
if ([e recurrenceId])
for (j = 0; j < [theAttendees count]; j++) {
if (shouldAdd) {
[e addToAttendees: [theAttendees objectAtIndex: j]];
}
else {
[e removeFromAttendees: [theAttendees objectAtIndex: j]];
}
}
}
}
//
//
//
- (NSException *) _handleUpdatedEvent: (iCalEvent *) newEvent
fromOldEvent: (iCalEvent *) oldEvent
force: (BOOL) forceSave
{
NSArray *addedAttendees, *deletedAttendees, *updatedAttendees;
iCalEventChanges *changes;
NSException *ex;
addedAttendees = nil;
deletedAttendees = nil;
updatedAttendees = nil;
changes = [newEvent getChangesRelativeToEvent: oldEvent];
if ([changes sequenceShouldBeIncreased])
{
// Set new attendees status to "needs action" and recompute changes when
// the list of attendees has changed. The list might have changed since
// by changing a major property of the event, we remove all the delegation
// chains to "other" attendees
if ([self _requireResponseFromAttendees: newEvent])
changes = [newEvent getChangesRelativeToEvent: oldEvent];
}
deletedAttendees = [changes deletedAttendees];
// We delete the attendees in all exception occurences, if
// the attendees were removed from the master event.
[self _addOrDeleteAttendees: deletedAttendees
inRecurrenceExceptionsForEvent: newEvent
add: NO];
if ([deletedAttendees count])
{
[self _handleRemovedUsers: deletedAttendees
withRecurrenceId: [newEvent recurrenceId]];
if ([self _shouldScheduleEvent: [newEvent organizer]])
[self sendEMailUsingTemplateNamed: @"Deletion"
forObject: [newEvent itipEntryWithMethod: @"cancel"]
previousObject: oldEvent
toAttendees: deletedAttendees
withType: @"calendar:cancellation"];
}
if ((ex = [self _handleAttendeesConflicts: [newEvent attendees] forEvent: newEvent force: forceSave]))
return ex;
if ((ex = [self _handleAttendeesAvailability: [newEvent attendees] forEvent: newEvent]))
return ex;
addedAttendees = [changes insertedAttendees];
// We insert the attendees in all exception occurences, if
// the attendees were added to the master event.
[self _addOrDeleteAttendees: addedAttendees
inRecurrenceExceptionsForEvent: newEvent
add: YES];
if ([changes sequenceShouldBeIncreased])
{
[newEvent increaseSequence];
// Update attendees calendars and send them an update
// notification by email. We ignore the newly added
// attendees as we don't want to send them invitation
// update emails
[self _handleSequenceUpdateInEvent: newEvent
ignoringAttendees: addedAttendees
fromOldEvent: oldEvent];
}
else
{
// If other attributes have changed, update the event
// in each attendee's calendar
if ([[changes updatedProperties] count])
{
NSEnumerator *enumerator;
iCalPerson *currentAttendee;
NSString *currentUID;
updatedAttendees = [newEvent attendees];
enumerator = [updatedAttendees objectEnumerator];
while ((currentAttendee = [enumerator nextObject]))
{
currentUID = [currentAttendee uidInContext: context];
if (currentUID)
[self _addOrUpdateEvent: newEvent
forUID: currentUID
owner: owner];
}
}
}
if ([addedAttendees count])
{
// Send an invitation to new attendees
if ((ex = [self _handleAddedUsers: addedAttendees fromEvent: newEvent force: forceSave]))
return ex;
if ([self _shouldScheduleEvent: [newEvent organizer]])
[self sendEMailUsingTemplateNamed: @"Invitation"
forObject: [newEvent itipEntryWithMethod: @"request"]
previousObject: oldEvent
toAttendees: addedAttendees
withType: @"calendar:invitation"];
}
if ([changes hasMajorChanges])
[self sendReceiptEmailForObject: newEvent
addedAttendees: addedAttendees
deletedAttendees: deletedAttendees
updatedAttendees: updatedAttendees
operation: EventUpdated];
return nil;
}
//
// Workflow : +----------------------+
// | |
// [saveComponent:]---> _handleAddedUsers:fromEvent: <-+ |
// | | v
// +------------> _handleUpdatedEvent:fromOldEvent: ---> _addOrUpdateEvent:forUID:owner: <-----------+
// | | ^ |
// v v | |
// _handleRemovedUsers:withRecurrenceId: _handleSequenceUpdateInEvent:ignoringAttendees:fromOldEvent: |
// | |
// | [DELETEAction:] |
// | | {_handleAdded/Updated...}<--+ |
// | v | |
// | [prepareDeleteOccurence:] [PUTAction:] |
// | | | | |
// v v v v |
// _removeEventFromUID:owner:withRecurrenceId: [changeParticipationStatus:withDelegate:forRecurrenceId:] |
// | | |
// | v |
// +------------------------> _handleAttendee:withDelegate:ownerUser:statusChange:inEvent: ---> [sendResponseToOrganizer:from:]
// |
// v
// _updateAttendee:withDelegate:ownerUser:forEventUID:withRecurrenceId:withSequence:forUID:shouldAddSentBy:
//
//
- (NSException *) saveComponent: (iCalEvent *) newEvent
{
return [self saveComponent: newEvent force: NO];
}
- (NSException *) saveComponent: (iCalEvent *) newEvent
force: (BOOL) forceSave
{
iCalEvent *oldEvent, *oldMasterEvent;
NSCalendarDate *recurrenceId;
NSString *recurrenceTime;
SOGoUser *ownerUser;
NSArray *attendees;
NSException *ex;
[[newEvent parent] setMethod: @""];
ownerUser = [SOGoUser userWithLogin: owner];
[self expandGroupsInEvent: newEvent];