e963b6d6ee33262480430334fe42cf9f04498173
[citadel.git] / citadel / server / modules / calendar / serv_calendar.c
1 // This module implements iCalendar object processing and the Calendar>
2 // room on a Citadel server.  It handles iCalendar objects using the
3 // iTIP protocol.  See RFCs 2445 and 2446.
4 //
5 // Copyright (c) 1987-2024 by the citadel.org team
6 //
7 // This program is open source software.  Use, duplication, or disclosure
8 // are subject to the terms of the GNU General Public License version 3.
9
10 #define PRODID "-//Citadel//NONSGML Citadel Calendar//EN"
11
12 #include "../../ctdl_module.h"
13 #include <libical/ical.h>
14 #include "../../msgbase.h"
15 #include "../../internet_addressing.h"
16 #include "serv_calendar.h"
17 #include "../../room_ops.h"
18 #include "../../euidindex.h"
19 #include "../../default_timezone.h"
20 #include "../../config.h"
21
22 struct ical_respond_data {
23         char desired_partnum[SIZ];
24         icalcomponent *cal;
25 };
26
27
28 // Utility function to create a new VCALENDAR component with some of the
29 // required fields already set the way we like them.
30 icalcomponent *icalcomponent_new_citadel_vcalendar(void) {
31         icalcomponent *encaps;
32
33         encaps = icalcomponent_new_vcalendar();
34         if (encaps == NULL) {
35                 syslog(LOG_ERR, "calendar: could not allocate component");
36                 return NULL;
37         }
38
39         // Set the Product ID
40         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
41
42         // Set the Version Number
43         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
44
45         return(encaps);
46 }
47
48
49 // Utility function to encapsulate a subcomponent into a full VCALENDAR
50 icalcomponent *ical_encapsulate_subcomponent(icalcomponent *subcomp) {
51         icalcomponent *encaps;
52
53         // If we're already looking at a full VCALENDAR component, don't bother ... just return itself.
54         if (icalcomponent_isa(subcomp) == ICAL_VCALENDAR_COMPONENT) {
55                 return subcomp;
56         }
57
58         // Encapsulate the VEVENT component into a complete VCALENDAR
59         encaps = icalcomponent_new_citadel_vcalendar();
60         if (encaps == NULL) return NULL;
61
62         // Encapsulate the subcomponent inside
63         icalcomponent_add_component(encaps, subcomp);
64
65         // Return the object we just created.
66         return(encaps);
67 }
68
69
70 // Write a calendar object into the specified user's calendar room.
71 // If the supplied user is NULL, this function writes the calendar object
72 // to the currently selected room.
73 void ical_write_to_cal(struct ctdluser *u, icalcomponent *cal) {
74         char *ser = NULL;
75         long serlen;
76         icalcomponent *encaps = NULL;
77         struct CtdlMessage *msg = NULL;
78         icalcomponent *tmp=NULL;
79
80         if (cal == NULL) return;
81
82         // If the supplied object is a subcomponent, encapsulate it in
83         // a full VCALENDAR component, and save that instead.
84         if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
85                 tmp = icalcomponent_new_clone(cal);
86                 encaps = ical_encapsulate_subcomponent(tmp);
87                 ical_write_to_cal(u, encaps);
88                 icalcomponent_free(tmp);
89                 icalcomponent_free(encaps);
90                 return;
91         }
92
93         ser = icalcomponent_as_ical_string_r(cal);
94         if (ser == NULL) return;
95
96         serlen = strlen(ser);
97
98         // If the caller supplied a user, write to that user's default calendar room
99         if (u) {
100                 CtdlWriteObject(                // This handy API function does all the work for us.
101                         USERCALENDARROOM,       // which room
102                         "text/calendar",        // MIME type
103                         ser,                    // data
104                         serlen + 1,             // length
105                         u,                      // which user
106                         0,                      // not binary
107                         0                       // no flags
108                 );
109         }
110
111         // If the caller did not supply a user, write to the currently selected room
112         if (!u) {
113                 struct CitContext *CCC = CC;
114                 StrBuf *MsgBody;
115
116                 msg = malloc(sizeof(struct CtdlMessage));
117                 memset(msg, 0, sizeof(struct CtdlMessage));
118                 msg->cm_magic = CTDLMESSAGE_MAGIC;
119                 msg->cm_anon_type = MES_NORMAL;
120                 msg->cm_format_type = 4;
121                 CM_SetField(msg, eAuthor, CCC->user.fullname);
122                 CM_SetField(msg, eOriginalRoom, CCC->room.QRname);
123
124                 MsgBody = NewStrBufPlain(NULL, serlen + 100);
125                 StrBufAppendBufPlain(MsgBody, HKEY("Content-type: text/calendar\r\n\r\n"), 0);
126                 StrBufAppendBufPlain(MsgBody, ser, serlen, 0);
127
128                 CM_SetAsFieldSB(msg, eMessageText, &MsgBody);
129         
130                 // Now write the data
131                 CtdlSubmitMsg(msg, NULL, "");
132                 CM_Free(msg);
133         }
134
135         // In either case, now we can free the serialized calendar object
136         free(ser);
137 }
138
139
140 // Send a reply to a meeting invitation.
141 //
142 // 'request' is the invitation to reply to.
143 // 'action' is the string "accept" or "decline" or "tentative".
144 void ical_send_a_reply(icalcomponent *request, char *action) {
145         icalcomponent *the_reply = NULL;
146         icalcomponent *vevent = NULL;
147         icalproperty *attendee = NULL;
148         char attendee_string[SIZ];
149         icalproperty *organizer = NULL;
150         char organizer_string[SIZ];
151         icalproperty *summary = NULL;
152         char summary_string[SIZ];
153         icalproperty *me_attend = NULL;
154         struct recptypes *recp = NULL;
155         icalparameter *partstat = NULL;
156         char *serialized_reply = NULL;
157         char *reply_message_text = NULL;
158         const char *ch;
159         struct CtdlMessage *msg = NULL;
160         struct recptypes *valid = NULL;
161
162         *organizer_string = '\0';
163         strcpy(summary_string, "Calendar item");
164
165         if (request == NULL) {
166                 syslog(LOG_ERR, "calendar: trying to reply to NULL event");
167                 return;
168         }
169
170         the_reply = icalcomponent_new_clone(request);
171         if (the_reply == NULL) {
172                 syslog(LOG_ERR, "calendar: cannot clone request");
173                 return;
174         }
175
176         // Change the method from REQUEST to REPLY
177         icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
178
179         vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
180         if (vevent != NULL) {
181                 // Hunt for attendees, removing ones that aren't us.
182                 // (Actually, remove them all, cloning our own one so we can
183                 // re-insert it later)
184                 while (attendee = icalcomponent_get_first_property(vevent, ICAL_ATTENDEE_PROPERTY), (attendee != NULL)) {
185                         ch = icalproperty_get_attendee(attendee);
186                         if ((ch != NULL) && !strncasecmp(ch, "MAILTO:", 7)) {
187                                 safestrncpy(attendee_string, ch + 7, sizeof (attendee_string));
188                                 string_trim(attendee_string);
189                                 recp = validate_recipients(attendee_string, NULL, 0);
190                                 if (recp != NULL) {
191                                         if (!strcasecmp(recp->recp_local, CC->user.fullname)) {
192                                                 if (me_attend) icalproperty_free(me_attend);
193                                                 me_attend = icalproperty_new_clone(attendee);
194                                         }
195                                         free_recipients(recp);
196                                 }
197                         }
198
199                         // Remove it...
200                         icalcomponent_remove_property(vevent, attendee);
201                         icalproperty_free(attendee);
202                 }
203
204                 // We found our own address in the attendee list.
205                 if (me_attend) {
206                         // Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE
207                         icalproperty_remove_parameter_by_kind(me_attend, ICAL_PARTSTAT_PARAMETER);
208
209                         if (!strcasecmp(action, "accept")) {
210                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
211                         }
212                         else if (!strcasecmp(action, "decline")) {
213                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
214                         }
215                         else if (!strcasecmp(action, "tentative")) {
216                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
217                         }
218
219                         if (partstat) icalproperty_add_parameter(me_attend, partstat);
220
221                         // Now insert it back into the vevent.
222                         icalcomponent_add_property(vevent, me_attend);
223                 }
224
225                 // Figure out who to send this thing to
226                 organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
227                 if (organizer != NULL) {
228                         if (icalproperty_get_organizer(organizer)) {
229                                 strcpy(organizer_string,
230                                         icalproperty_get_organizer(organizer) );
231                         }
232                 }
233                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
234                         strcpy(organizer_string, &organizer_string[7]);
235                         string_trim(organizer_string);
236                 }
237                 else {
238                         strcpy(organizer_string, "");
239                 }
240
241                 // Extract the summary string -- we'll use it as the message subject for the reply
242                 summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
243                 if (summary != NULL) {
244                         if (icalproperty_get_summary(summary)) {
245                                 strcpy(summary_string,
246                                         icalproperty_get_summary(summary) );
247                         }
248                 }
249         }
250
251         // Now generate the reply message and send it out.
252         serialized_reply = icalcomponent_as_ical_string_r(the_reply);
253         icalcomponent_free(the_reply);  // don't need this anymore
254         if (serialized_reply == NULL) return;
255
256         reply_message_text = malloc(strlen(serialized_reply) + SIZ);
257         if (reply_message_text != NULL) {
258                 sprintf(reply_message_text,
259                         "Content-type: text/calendar; charset=\"utf-8\"\r\n\r\n%s\r\n",
260                         serialized_reply
261                 );
262
263                 msg = CtdlMakeMessage(&CC->user,
264                         organizer_string,       // to
265                         "",                     // cc
266                         CC->room.QRname,
267                         0,
268                         FMT_RFC822,
269                         "",
270                         "",
271                         summary_string,         // Use the event SUMMARY as the message subject
272                         NULL,
273                         reply_message_text,
274                         NULL
275                 );
276         
277                 if (msg != NULL) {
278                         valid = validate_recipients(organizer_string, NULL, 0);
279                         CtdlSubmitMsg(msg, valid, "");
280                         CM_Free(msg);
281                         free_recipients(valid);
282                 }
283         }
284         free(serialized_reply);
285 }
286
287
288 // Callback function for mime parser that hunts for calendar content types
289 // and turns them into calendar objects.  If something is found, it is placed
290 // in ird->cal, and the caller now owns that memory and is responsible for freeing it.
291 void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
292                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
293                 char *cbid, void *cbuserdata) {
294
295         struct ical_respond_data *ird = NULL;
296
297         ird = (struct ical_respond_data *) cbuserdata;
298
299         // desired_partnum can be set to "_HUNT_" to have it just look for
300         // the first part with a content type of text/calendar.  Otherwise
301         // we have to only process the right one.
302         if (strcasecmp(ird->desired_partnum, "_HUNT_")) {
303                 if (strcasecmp(partnum, ird->desired_partnum)) {
304                         return;
305                 }
306         }
307
308         if (    (strcasecmp(cbtype, "text/calendar"))
309                 && (strcasecmp(cbtype, "application/ics"))
310         ) {
311                 return;
312         }
313
314         if (ird->cal != NULL) {
315                 icalcomponent_free(ird->cal);
316                 ird->cal = NULL;
317         }
318
319         ird->cal = icalcomponent_new_from_string(content);
320 }
321
322
323 // Respond to a meeting request.
324 void ical_respond(long msgnum, char *partnum, char *action) {
325         struct CtdlMessage *msg = NULL;
326         struct ical_respond_data ird;
327
328         if (
329                 (strcasecmp(action, "accept"))
330                 && (strcasecmp(action, "decline"))
331         ) {
332                 cprintf("%d Action must be 'accept' or 'decline'\n", ERROR + ILLEGAL_VALUE);
333                 return;
334         }
335
336         msg = CtdlFetchMessage(msgnum, 1);
337         if (msg == NULL) {
338                 cprintf("%d Message %ld not found.\n", ERROR + ILLEGAL_VALUE, (long)msgnum);
339                 return;
340         }
341
342         memset(&ird, 0, sizeof ird);
343         strcpy(ird.desired_partnum, partnum);
344         mime_parser(CM_RANGE(msg, eMessageText),
345                 *ical_locate_part,              // callback function
346                 NULL,
347                 NULL,
348                 (void *) &ird,                  // user data
349                 0
350         );
351
352         // We're done with the incoming message, because we now have a * calendar object in memory.
353         CM_Free(msg);
354
355         // Here is the real meat of this function.  Handle the event.
356         if (ird.cal != NULL) {
357                 // Save this in the user's calendar if necessary
358                 if (!strcasecmp(action, "accept")) {
359                         ical_write_to_cal(&CC->user, ird.cal);
360                 }
361
362                 // Send a reply if necessary
363                 if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
364                         ical_send_a_reply(ird.cal, action);
365                 }
366
367                 // We used to delete the invitation after handling it.
368                 // We don't do that anymore, but here is the code that handled it:
369                 // CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
370
371                 // Free the memory we allocated and return a response.
372                 icalcomponent_free(ird.cal);
373                 ird.cal = NULL;
374                 cprintf("%d ok\n", CIT_OK);
375                 return;
376         }
377         else {
378                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
379                 return;
380         }
381
382         // should never get here
383 }
384
385
386 // Figure out the UID of the calendar event being referred to in a
387 // REPLY object.  This function is recursive.
388 void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
389         icalcomponent *subcomponent;
390         icalproperty *p;
391
392         // If this object is a REPLY, then extract the UID.
393         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
394                 p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
395                 if (p != NULL) {
396                         strcpy(uidbuf, icalproperty_get_comment(p));
397                 }
398         }
399
400         // Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
401         // UID of the reply; we want the UID of the invitation being replied to.
402         for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
403                 subcomponent != NULL;
404                 subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT)
405         ) {
406                 ical_learn_uid_of_reply(uidbuf, subcomponent);
407         }
408 }
409
410
411 // ical_update_my_calendar_with_reply() refers to this callback function; when we
412 // locate the message containing the calendar event we're replying to, this function
413 // gets called.  It basically just sticks the message number in a supplied buffer.
414 void ical_hunt_for_event_to_update(long msgnum, void *data) {
415         long *msgnumptr;
416
417         msgnumptr = (long *) data;
418         *msgnumptr = msgnum;
419 }
420
421
422 struct original_event_container {
423         icalcomponent *c;
424 };
425
426 // Callback function for mime parser that hunts for calendar content types
427 // and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
428 // to fetch the object being updated)
429 void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
430                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
431                 char *cbid, void *cbuserdata) {
432
433         struct original_event_container *oec = NULL;
434
435         if (    (strcasecmp(cbtype, "text/calendar"))
436                 && (strcasecmp(cbtype, "application/ics"))
437         ) {
438                 return;
439         }
440         oec = (struct original_event_container *) cbuserdata;
441         if (oec->c != NULL) {
442                 icalcomponent_free(oec->c);
443         }
444         oec->c = icalcomponent_new_from_string(content);
445 }
446
447
448 // Merge updated attendee information from a REPLY into an existing event.
449 void ical_merge_attendee_reply(icalcomponent *event, icalcomponent *reply) {
450         icalcomponent *c;
451         icalproperty *e_attendee, *r_attendee;
452
453         // First things first.  If we're not looking at a VEVENT component,
454         // recurse through subcomponents until we find one.
455         if (icalcomponent_isa(event) != ICAL_VEVENT_COMPONENT) {
456                 for (c = icalcomponent_get_first_component(event, ICAL_VEVENT_COMPONENT);
457                         c != NULL;
458                         c = icalcomponent_get_next_component(event, ICAL_VEVENT_COMPONENT)
459                 ) {
460                         ical_merge_attendee_reply(c, reply);
461                 }
462                 return;
463         }
464
465         // Now do the same thing with the reply.
466         if (icalcomponent_isa(reply) != ICAL_VEVENT_COMPONENT) {
467                 for (c = icalcomponent_get_first_component(reply, ICAL_VEVENT_COMPONENT);
468                         c != NULL;
469                         c = icalcomponent_get_next_component(reply, ICAL_VEVENT_COMPONENT)
470                 ) {
471                         ical_merge_attendee_reply(event, c);
472                 }
473                 return;
474         }
475
476         // Clone the reply, because we're going to rip its guts out.
477         reply = icalcomponent_new_clone(reply);
478
479         // At this point we're looking at the correct subcomponents.
480         // Iterate through the attendees looking for a match.
481 STARTOVER:
482         for (e_attendee = icalcomponent_get_first_property(event, ICAL_ATTENDEE_PROPERTY);
483                 e_attendee != NULL;
484                 e_attendee = icalcomponent_get_next_property(event, ICAL_ATTENDEE_PROPERTY)
485         ) {
486
487                 for (r_attendee = icalcomponent_get_first_property(reply, ICAL_ATTENDEE_PROPERTY);
488                         r_attendee != NULL;
489                         r_attendee = icalcomponent_get_next_property(reply, ICAL_ATTENDEE_PROPERTY)
490                 ) {
491
492                         // Check to see if these two attendees match...
493                         const char *e, *r;
494                         e = icalproperty_get_attendee(e_attendee);
495                         r = icalproperty_get_attendee(r_attendee);
496
497                         if ((e != NULL) && (r != NULL) && !strcasecmp(e, r)) {
498                                 // ...and if they do, remove the attendee from the event
499                                 // and replace it with the attendee from the reply.  (The
500                                 // reply's copy will have the same address, but an updated
501                                 // status.)
502                                 icalcomponent_remove_property(event, e_attendee);
503                                 icalproperty_free(e_attendee);
504                                 icalcomponent_remove_property(reply, r_attendee);
505                                 icalcomponent_add_property(event, r_attendee);
506
507                                 // Since we diddled both sets of attendees, we have to start
508                                 // the iteration over again.  This will not create an infinite
509                                 // loop because we removed the attendee from the reply.  (That's
510                                 // why we cloned the reply, and that's what we mean by "ripping
511                                 // its guts out.")
512                                 goto STARTOVER;
513                         }
514         
515                 }
516         }
517
518         // Free the *clone* of the reply.
519         icalcomponent_free(reply);
520 }
521
522
523 // Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
524 // calendar event.  The object has already been deserialized for us; all
525 // we have to do here is hunt for the event in our calendar, merge in the
526 // updated attendee status, and save it again.
527 //
528 // This function returns 0 on success, 1 if the event was not found in the
529 // user's calendar, or 2 if an internal error occurred.
530 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
531         char uid[SIZ];
532         char hold_rm[ROOMNAMELEN];
533         long msgnum_being_replaced = 0;
534         struct CtdlMessage *msg = NULL;
535         struct original_event_container oec;
536         icalcomponent *original_event;
537         char *serialized_event = NULL;
538         char roomname[ROOMNAMELEN];
539         char *message_text = NULL;
540
541         // Figure out just what event it is we're dealing with
542         strcpy(uid, "--==<< InVaLiD uId >>==--");
543         ical_learn_uid_of_reply(uid, cal);
544         syslog(LOG_DEBUG, "calendar: UID of event being replied to is <%s>", uid);
545
546         strcpy(hold_rm, CC->room.QRname);       // save current room
547
548         if (CtdlGetRoom(&CC->room, USERCALENDARROOM) != 0) {
549                 CtdlGetRoom(&CC->room, hold_rm);
550                 syslog(LOG_ERR, "calendar: cannot get user calendar room");
551                 return(2);
552         }
553
554         // Look in the EUID index for a message with
555         // the Citadel EUID set to the value we're looking for.  Since
556         // Citadel always sets the message EUID to the iCalendar UID of
557         // the event, this will work.
558         msgnum_being_replaced = CtdlLocateMessageByEuid(uid, &CC->room);
559
560         CtdlGetRoom(&CC->room, hold_rm);        // return to saved room
561
562         syslog(LOG_DEBUG, "calendar: msgnum_being_replaced == %ld", msgnum_being_replaced);
563         if (msgnum_being_replaced == 0) {
564                 return(1);                      // no calendar event found
565         }
566
567         // Now we know the ID of the message containing the event being updated.
568         // We don't actually have to delete it; that'll get taken care of by the
569         // server when we save another event with the same UID.  This just gives
570         // us the ability to load the event into memory so we can diddle the attendees.
571         msg = CtdlFetchMessage(msgnum_being_replaced, 1);
572         if (msg == NULL) {
573                 return(2);                      // internal error
574         }
575         oec.c = NULL;
576         mime_parser(
577                 CM_RANGE(msg, eMessageText),
578                 *ical_locate_original_event,    // callback function
579                 NULL, NULL,
580                 &oec,                           // user data
581                 0
582         );
583         CM_Free(msg);
584
585         original_event = oec.c;
586         if (original_event == NULL) {
587                 syslog(LOG_ERR, "calendar: original_component is NULL");
588                 return(2);
589         }
590
591         // Merge the attendee's updated status into the event
592         ical_merge_attendee_reply(original_event, cal);
593
594         // Serialize it
595         serialized_event = icalcomponent_as_ical_string_r(original_event);
596         icalcomponent_free(original_event);     // Don't need this anymore.
597         if (serialized_event == NULL) return(2);
598
599         CtdlMailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
600
601         message_text = malloc(strlen(serialized_event) + SIZ);
602         if (message_text != NULL) {
603                 sprintf(message_text,
604                         "Content-type: text/calendar; charset=\"utf-8\"\r\n\r\n%s\r\n",
605                         serialized_event
606                 );
607
608                 msg = CtdlMakeMessage(&CC->user,
609                         "",                     // No recipient
610                         "",                     // No recipient
611                         roomname,
612                         0,
613                         FMT_RFC822,
614                         "",
615                         "",
616                         "",                     // no subject
617                         NULL,
618                         message_text,
619                         NULL
620                 );
621         
622                 if (msg != NULL) {
623                         CIT_ICAL->avoid_sending_invitations = 1;
624                         CtdlSubmitMsg(msg, NULL, roomname);
625                         CM_Free(msg);
626                         CIT_ICAL->avoid_sending_invitations = 0;
627                 }
628         }
629         free(serialized_event);
630         return(0);
631 }
632
633
634 // Handle an incoming RSVP for an event.  (This is the server subcommand part; it
635 // simply extracts the calendar object from the message, deserializes it, and
636 // passes it up to ical_update_my_calendar_with_reply() for processing.
637 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
638         struct CtdlMessage *msg = NULL;
639         struct ical_respond_data ird;
640         int ret;
641
642         if (
643                 (strcasecmp(action, "update"))
644                 && (strcasecmp(action, "ignore"))
645         ) {
646                 cprintf("%d Action must be 'update' or 'ignore'\n", ERROR + ILLEGAL_VALUE);
647                 return;
648         }
649
650         msg = CtdlFetchMessage(msgnum, 1);
651         if (msg == NULL) {
652                 cprintf("%d Message %ld not found.\n",
653                         ERROR + ILLEGAL_VALUE,
654                         (long)msgnum
655                 );
656                 return;
657         }
658
659         memset(&ird, 0, sizeof ird);
660         strcpy(ird.desired_partnum, partnum);
661         mime_parser(
662                 CM_RANGE(msg, eMessageText),
663                 *ical_locate_part,                      // callback function
664                 NULL,
665                 NULL,
666                 (void *) &ird,                          // user data
667                 0
668         );
669
670         // We're done with the incoming message, because we now have a
671         // calendar object in memory.
672         CM_Free(msg);
673
674         // Here is the real meat of this function.  Handle the event.
675         if (ird.cal != NULL) {
676                 // Update the user's calendar if necessary
677                 if (!strcasecmp(action, "update")) {
678                         ret = ical_update_my_calendar_with_reply(ird.cal);
679                         if (ret == 0) {
680                                 cprintf("%d Your calendar has been updated with this reply.\n", CIT_OK);
681                         }
682                         else if (ret == 1) {
683                                 cprintf("%d This event does not exist in your calendar.\n", ERROR + FILE_NOT_FOUND);
684                         }
685                         else {
686                                 cprintf("%d An internal error occurred.\n", ERROR + INTERNAL_ERROR);
687                         }
688                 }
689                 else {
690                         cprintf("%d This reply has been ignored.\n", CIT_OK);
691                 }
692
693                 // Now that we've processed this message, we don't need it
694                 // anymore.  So delete it.  (Don't do this anymore.)
695                 // CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
696
697                 // Free the memory we allocated and return a response.
698                 icalcomponent_free(ird.cal);
699                 ird.cal = NULL;
700                 return;
701         }
702         else {
703                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
704                 return;
705         }
706
707         // should never get here
708 }
709
710
711 // Search for a property in both the top level and in a VEVENT subcomponent
712 icalproperty *ical_ctdl_get_subprop(
713                 icalcomponent *cal,
714                 icalproperty_kind which_prop
715 ) {
716         icalproperty *p;
717         icalcomponent *c;
718
719         p = icalcomponent_get_first_property(cal, which_prop);
720         if (p == NULL) {
721                 c = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
722                 if (c != NULL) {
723                         p = icalcomponent_get_first_property(c, which_prop);
724                 }
725         }
726         return p;
727 }
728
729
730 // Check to see if two events overlap.  Returns nonzero if they do.
731 // (This function is used in both Citadel and WebCit.  If you change it in
732 // one place, change it in the other.  Better yet, put it in a library.)
733 int ical_ctdl_is_overlap(
734                         struct icaltimetype t1start,
735                         struct icaltimetype t1end,
736                         struct icaltimetype t2start,
737                         struct icaltimetype t2end
738 ) {
739         if (icaltime_is_null_time(t1start)) return(0);
740         if (icaltime_is_null_time(t2start)) return(0);
741
742         // if either event lacks end time, assume end = start
743         if (icaltime_is_null_time(t1end)) {
744                 memcpy(&t1end, &t1start, sizeof(struct icaltimetype));
745         }
746         else {
747                 if (t1end.is_date && icaltime_compare(t1start, t1end)) {
748
749                         // the end date is non-inclusive so adjust it by one
750                         // day because our test is inclusive, note that a day is
751                         // not too much because we are talking about all day
752                         // events
753                         // if start = end we assume that nevertheless the whole
754                         // day is meant
755
756                         icaltime_adjust(&t1end, -1, 0, 0, 0);   
757                 }
758         }
759
760         if (icaltime_is_null_time(t2end))
761                 memcpy(&t2end, &t2start, sizeof(struct icaltimetype));
762         else {
763                 if (t2end.is_date && icaltime_compare(t2start, t2end)) {
764                         icaltime_adjust(&t2end, -1, 0, 0, 0);   
765                 }
766         }
767
768         // First, check for all-day events
769         if (t1start.is_date || t2start.is_date) {
770                 // If event 1 ends before event 2 starts, we're in the clear.
771                 if (icaltime_compare_date_only(t1end, t2start) < 0) return(0);
772
773                 // If event 2 ends before event 1 starts, we're also ok.
774                 if (icaltime_compare_date_only(t2end, t1start) < 0) return(0);
775
776                 return(1);
777         }
778
779         // syslog(LOG_DEBUG, "Comparing t1start %d:%d t1end %d:%d t2start %d:%d t2end %d:%d",
780         //      t1start.hour, t1start.minute, t1end.hour, t1end.minute,
781         //      t2start.hour, t2start.minute, t2end.hour, t2end.minute);
782
783         // Now check for overlaps using date *and* time.
784
785         // If event 1 ends before event 2 starts, we're in the clear.
786         if (icaltime_compare(t1end, t2start) <= 0) return(0);
787         // syslog(LOG_DEBUG, "calendar: first passed");
788
789         // If event 2 ends before event 1 starts, we're also ok.
790         if (icaltime_compare(t2end, t1start) <= 0) return(0);
791         // syslog(LOG_DEBUG, "calendar: second passed");
792
793         // Otherwise, they overlap.
794         return(1);
795 }
796
797
798 // Phase 6 of "hunt for conflicts"
799 // called by ical_conflicts_phase5()
800 //
801 // Now both the proposed and existing events have been boiled down to start and end times.
802 // Check for overlap and output any conflicts.
803 //
804 // Returns nonzero if a conflict was reported.  This allows the caller to stop iterating.
805 int ical_conflicts_phase6(struct icaltimetype t1start,
806                         struct icaltimetype t1end,
807                         struct icaltimetype t2start,
808                         struct icaltimetype t2end,
809                         long existing_msgnum,
810                         char *conflict_event_uid,
811                         char *conflict_event_summary,
812                         char *compare_uid)
813 {
814         int conflict_reported = 0;
815
816         //      debugging cruft
817         //      time_t tt;
818         //      tt = icaltime_as_timet_with_zone(t1start, t1start.zone);
819         //      syslog(LOG_DEBUG, "PROPOSED START: %s", ctime(&tt));
820         //      tt = icaltime_as_timet_with_zone(t1end, t1end.zone);
821         //      syslog(LOG_DEBUG, "  PROPOSED END: %s", ctime(&tt));
822         //      tt = icaltime_as_timet_with_zone(t2start, t2start.zone);
823         //      syslog(LOG_DEBUG, "EXISTING START: %s", ctime(&tt));
824         //      tt = icaltime_as_timet_with_zone(t2end, t2end.zone);
825         //      syslog(LOG_DEBUG, "  EXISTING END: %s", ctime(&tt));
826         //      debugging cruft
827
828         // compare and output
829
830         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
831                 cprintf("%ld||%s|%s|%d|\n",
832                         existing_msgnum,
833                         conflict_event_uid,
834                         conflict_event_summary,
835                         (       (!IsEmptyStr(compare_uid)
836                                 &&(!strcasecmp(compare_uid,
837                                 conflict_event_uid))) ? 1 : 0
838                                 )
839                         );
840                 conflict_reported = 1;
841         }
842
843         return(conflict_reported);
844 }
845
846
847 // Phase 5 of "hunt for conflicts"
848 // Called by ical_conflicts_phase4()
849 //
850 // We have the proposed event boiled down to start and end times.
851 // Now check it against an existing event. 
852 void ical_conflicts_phase5(struct icaltimetype t1start,
853                         struct icaltimetype t1end,
854                         icalcomponent *existing_event,
855                         long existing_msgnum,
856                         char *compare_uid)
857 {
858         char conflict_event_uid[SIZ];
859         char conflict_event_summary[SIZ];
860         struct icaltimetype t2start, t2end;
861         icalproperty *p;
862
863         // recur variables 
864         icalproperty *rrule = NULL;
865         struct icalrecurrencetype recur;
866         icalrecur_iterator *ritr = NULL;
867         struct icaldurationtype dur;
868         int num_recur = 0;
869
870         // initialization 
871         strcpy(conflict_event_uid, "");
872         strcpy(conflict_event_summary, "");
873         t2start = icaltime_null_time();
874         t2end = icaltime_null_time();
875
876         // existing event stuff 
877         p = ical_ctdl_get_subprop(existing_event, ICAL_DTSTART_PROPERTY);
878         if (p == NULL) return;
879         if (p != NULL) t2start = icalproperty_get_dtstart(p);
880         if (icaltime_is_utc(t2start)) {
881                 t2start.zone = icaltimezone_get_utc_timezone();
882         }
883         else {
884                 t2start.zone = icalcomponent_get_timezone(existing_event,
885                         icalparameter_get_tzid(
886                                 icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
887                         )
888                 );
889                 if (!t2start.zone) {
890                         t2start.zone = get_default_icaltimezone();
891                 }
892         }
893
894         p = ical_ctdl_get_subprop(existing_event, ICAL_DTEND_PROPERTY);
895         if (p != NULL) {
896                 t2end = icalproperty_get_dtend(p);
897
898                 if (icaltime_is_utc(t2end)) {
899                         t2end.zone = icaltimezone_get_utc_timezone();
900                 }
901                 else {
902                         t2end.zone = icalcomponent_get_timezone(existing_event,
903                                 icalparameter_get_tzid(icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER))
904                         );
905                         if (!t2end.zone) {
906                                 t2end.zone = get_default_icaltimezone();
907                         }
908                 }
909                 dur = icaltime_subtract(t2end, t2start);
910         }
911         else {
912                 memset (&dur, 0, sizeof(struct icaldurationtype));
913         }
914
915         rrule = ical_ctdl_get_subprop(existing_event, ICAL_RRULE_PROPERTY);
916         if (rrule) {
917                 recur = icalproperty_get_rrule(rrule);
918                 ritr = icalrecur_iterator_new(recur, t2start);
919         }
920
921         do {
922                 p = ical_ctdl_get_subprop(existing_event, ICAL_UID_PROPERTY);
923                 if (p != NULL) {
924                         strcpy(conflict_event_uid, icalproperty_get_comment(p));
925                 }
926         
927                 p = ical_ctdl_get_subprop(existing_event, ICAL_SUMMARY_PROPERTY);
928                 if (p != NULL) {
929                         strcpy(conflict_event_summary, icalproperty_get_comment(p));
930                 }
931         
932                 if (ical_conflicts_phase6(t1start, t1end, t2start, t2end,
933                         existing_msgnum, conflict_event_uid, conflict_event_summary, compare_uid)) {
934                         num_recur = MAX_RECUR + 1;      // force it out of scope, no need to continue 
935                 }
936
937                 if (rrule) {
938                         t2start = icalrecur_iterator_next(ritr);
939                         if (!icaltime_is_null_time(t2end)) {
940                                 const icaltimezone *hold_zone = t2end.zone;
941                                 t2end = icaltime_add(t2start, dur);
942                                 t2end.zone = hold_zone;
943                         }
944                         ++num_recur;
945                 }
946
947                 if (icaltime_compare(t2start, t1end) < 0) {
948                         num_recur = MAX_RECUR + 1;      // force it out of scope
949                 }
950
951         } while ( (rrule) && (!icaltime_is_null_time(t2start)) && (num_recur < MAX_RECUR) );
952         icalrecur_iterator_free(ritr);
953 }
954
955
956 // Phase 4 of "hunt for conflicts"
957 // Called by ical_hunt_for_conflicts_backend()
958 //
959 // At this point we've got it boiled down to two icalcomponent events in memory.
960 // If they conflict, output something to the client.
961 void ical_conflicts_phase4(icalcomponent *proposed_event,
962                 icalcomponent *existing_event,
963                 long existing_msgnum)
964 {
965         struct icaltimetype t1start, t1end;
966         icalproperty *p;
967         char compare_uid[SIZ];
968
969         // recur variables
970         icalproperty *rrule = NULL;
971         struct icalrecurrencetype recur;
972         icalrecur_iterator *ritr = NULL;
973         struct icaldurationtype dur;
974         int num_recur = 0;
975
976         // initialization
977         t1end = icaltime_null_time();
978         *compare_uid = '\0';
979
980         // proposed event stuff
981
982         p = ical_ctdl_get_subprop(proposed_event, ICAL_DTSTART_PROPERTY);
983         if (p == NULL)
984                 return;
985         else
986                 t1start = icalproperty_get_dtstart(p);
987
988         if (icaltime_is_utc(t1start)) {
989                 t1start.zone = icaltimezone_get_utc_timezone();
990         }
991         else {
992                 t1start.zone = icalcomponent_get_timezone(proposed_event,
993                         icalparameter_get_tzid(
994                                 icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
995                         )
996                 );
997                 if (!t1start.zone) {
998                         t1start.zone = get_default_icaltimezone();
999                 }
1000         }
1001         
1002         p = ical_ctdl_get_subprop(proposed_event, ICAL_DTEND_PROPERTY);
1003         if (p != NULL) {
1004                 t1end = icalproperty_get_dtend(p);
1005
1006                 if (icaltime_is_utc(t1end)) {
1007                         t1end.zone = icaltimezone_get_utc_timezone();
1008                 }
1009                 else {
1010                         t1end.zone = icalcomponent_get_timezone(proposed_event,
1011                                 icalparameter_get_tzid(
1012                                         icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
1013                                 )
1014                         );
1015                         if (!t1end.zone) {
1016                                 t1end.zone = get_default_icaltimezone();
1017                         }
1018                 }
1019
1020                 dur = icaltime_subtract(t1end, t1start);
1021         }
1022         else {
1023                 memset (&dur, 0, sizeof(struct icaldurationtype));
1024         }
1025
1026         rrule = ical_ctdl_get_subprop(proposed_event, ICAL_RRULE_PROPERTY);
1027         if (rrule) {
1028                 recur = icalproperty_get_rrule(rrule);
1029                 ritr = icalrecur_iterator_new(recur, t1start);
1030         }
1031
1032         p = ical_ctdl_get_subprop(proposed_event, ICAL_UID_PROPERTY);
1033         if (p != NULL) {
1034                 strcpy(compare_uid, icalproperty_get_comment(p));
1035         }
1036
1037         do {
1038                 ical_conflicts_phase5(t1start, t1end, existing_event, existing_msgnum, compare_uid);
1039
1040                 if (rrule) {
1041                         t1start = icalrecur_iterator_next(ritr);
1042                         if (!icaltime_is_null_time(t1end)) {
1043                                 const icaltimezone *hold_zone = t1end.zone;
1044                                 t1end = icaltime_add(t1start, dur);
1045                                 t1end.zone = hold_zone;
1046                         }
1047                         ++num_recur;
1048                 }
1049
1050         } while ( (rrule) && (!icaltime_is_null_time(t1start)) && (num_recur < MAX_RECUR) );
1051         icalrecur_iterator_free(ritr);
1052 }
1053
1054
1055 // Phase 3 of "hunt for conflicts"
1056 // Called by ical_hunt_for_conflicts()
1057 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
1058         icalcomponent *proposed_event;
1059         struct CtdlMessage *msg = NULL;
1060         struct ical_respond_data ird;
1061
1062         proposed_event = (icalcomponent *)data;
1063
1064         msg = CtdlFetchMessage(msgnum, 1);
1065         if (msg == NULL) return;
1066         memset(&ird, 0, sizeof ird);
1067         strcpy(ird.desired_partnum, "_HUNT_");
1068         mime_parser(CM_RANGE(msg, eMessageText),
1069                 *ical_locate_part,              // callback function
1070                 NULL,
1071                 NULL,
1072                 (void *) &ird,                  // user data
1073                 0
1074         );
1075         CM_Free(msg);
1076
1077         if (ird.cal == NULL) return;
1078
1079         ical_conflicts_phase4(proposed_event, ird.cal, msgnum);
1080         icalcomponent_free(ird.cal);
1081 }
1082
1083
1084 // Phase 2 of "hunt for conflicts" operation.
1085 // At this point we have a calendar object which represents the VEVENT that
1086 // is proposed for addition to the calendar.  Now hunt through the user's
1087 // calendar room, and output zero or more existing VEVENTs which conflict
1088 // with this one.
1089 void ical_hunt_for_conflicts(icalcomponent *cal) {
1090         char hold_rm[ROOMNAMELEN];
1091
1092         strcpy(hold_rm, CC->room.QRname);       // save current room
1093
1094         if (CtdlGetRoom(&CC->room, USERCALENDARROOM) != 0) {
1095                 CtdlGetRoom(&CC->room, hold_rm);
1096                 cprintf("%d You do not have a calendar.\n", ERROR + ROOM_NOT_FOUND);
1097                 return;
1098         }
1099
1100         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
1101
1102         CtdlForEachMessage(MSGS_ALL, 0, NULL,
1103                 NULL,
1104                 NULL,
1105                 ical_hunt_for_conflicts_backend,
1106                 (void *) cal
1107         );
1108
1109         cprintf("000\n");
1110         CtdlGetRoom(&CC->room, hold_rm);        // return to saved room
1111
1112 }
1113
1114
1115 /*
1116  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
1117  */
1118 void ical_conflicts(long msgnum, char *partnum) {
1119         struct CtdlMessage *msg = NULL;
1120         struct ical_respond_data ird;
1121
1122         msg = CtdlFetchMessage(msgnum, 1);
1123         if (msg == NULL) {
1124                 cprintf("%d Message %ld not found\n",
1125                         ERROR + ILLEGAL_VALUE,
1126                         (long)msgnum
1127                 );
1128                 return;
1129         }
1130
1131         memset(&ird, 0, sizeof ird);
1132         strcpy(ird.desired_partnum, partnum);
1133         mime_parser(
1134                 CM_RANGE(msg, eMessageText),
1135                 *ical_locate_part,              // callback function
1136                 NULL,
1137                 NULL,
1138                 (void *) &ird,                  // user data
1139                 0
1140         );
1141
1142         CM_Free(msg);
1143
1144         if (ird.cal != NULL) {
1145                 ical_hunt_for_conflicts(ird.cal);
1146                 icalcomponent_free(ird.cal);
1147                 return;
1148         }
1149
1150         cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
1151 }
1152
1153
1154 // Look for busy time in a VEVENT and add it to the supplied VFREEBUSY.
1155 //
1156 // fb                   The VFREEBUSY component to which we are appending
1157 // top_level_cal        The top-level VCALENDAR component which contains a VEVENT to be added
1158 void ical_add_to_freebusy(icalcomponent *fb, icalcomponent *top_level_cal) {
1159         icalcomponent *cal;
1160         icalproperty *p;
1161         icalvalue *v;
1162         struct icalperiodtype this_event_period = icalperiodtype_null_period();
1163         icaltimetype dtstart;
1164         icaltimetype dtend;
1165
1166         // recur variables
1167         icalproperty *rrule = NULL;
1168         struct icalrecurrencetype recur;
1169         icalrecur_iterator *ritr = NULL;
1170         struct icaldurationtype dur;
1171         int num_recur = 0;
1172
1173         if (!top_level_cal) return;
1174
1175         // Find the VEVENT component containing an event
1176         cal = icalcomponent_get_first_component(top_level_cal, ICAL_VEVENT_COMPONENT);
1177         if (!cal) return;
1178
1179         // If this event is not opaque, the user isn't publishing it as
1180         // busy time, so don't bother doing anything else.
1181         p = icalcomponent_get_first_property(cal, ICAL_TRANSP_PROPERTY);
1182         if (p != NULL) {
1183                 v = icalproperty_get_value(p);
1184                 if (v != NULL) {
1185                         if (icalvalue_get_transp(v) != ICAL_TRANSP_OPAQUE) {
1186                                 return;
1187                         }
1188                 }
1189         }
1190
1191         // Now begin calculating the event start and end times.
1192         p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
1193         if (!p) return;
1194         dtstart = icalproperty_get_dtstart(p);
1195
1196         if (icaltime_is_utc(dtstart)) {
1197                 dtstart.zone = icaltimezone_get_utc_timezone();
1198         }
1199         else {
1200                 dtstart.zone = icalcomponent_get_timezone(top_level_cal,
1201                         icalparameter_get_tzid(
1202                                 icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
1203                         )
1204                 );
1205                 if (!dtstart.zone) {
1206                         dtstart.zone = get_default_icaltimezone();
1207                 }
1208         }
1209
1210         dtend = icalcomponent_get_dtend(cal);
1211         if (!icaltime_is_null_time(dtend)) {
1212                 dur = icaltime_subtract(dtend, dtstart);
1213         }
1214         else {
1215                 memset (&dur, 0, sizeof(struct icaldurationtype));
1216         }
1217
1218         // Is a recurrence specified?  If so, get ready to process it...
1219         rrule = ical_ctdl_get_subprop(cal, ICAL_RRULE_PROPERTY);
1220         if (rrule) {
1221                 recur = icalproperty_get_rrule(rrule);
1222                 ritr = icalrecur_iterator_new(recur, dtstart);
1223         }
1224
1225         do {
1226                 // Convert the DTSTART and DTEND properties to an icalperiod.
1227                 this_event_period.start = dtstart;
1228         
1229                 if (!icaltime_is_null_time(dtend)) {
1230                         this_event_period.end = dtend;
1231                 }
1232
1233                 // Convert the timestamps to UTC.  It's ok to do this because we've already expanded
1234                 // recurrences and this data is never going to get used again.
1235                 this_event_period.start = icaltime_convert_to_zone(
1236                         this_event_period.start,
1237                         icaltimezone_get_utc_timezone()
1238                 );
1239                 this_event_period.end = icaltime_convert_to_zone(
1240                         this_event_period.end,
1241                         icaltimezone_get_utc_timezone()
1242                 );
1243         
1244                 // Now add it.
1245                 icalcomponent_add_property(fb, icalproperty_new_freebusy(this_event_period));
1246
1247                 // Make sure the DTSTART property of the freebusy *list* is set to
1248                 // the DTSTART property of the *earliest event*.
1249                 p = icalcomponent_get_first_property(fb, ICAL_DTSTART_PROPERTY);
1250                 if (p == NULL) {
1251                         icalcomponent_set_dtstart(fb, this_event_period.start);
1252                 }
1253                 else {
1254                         if (icaltime_compare(this_event_period.start, icalcomponent_get_dtstart(fb)) < 0) {
1255                                 icalcomponent_set_dtstart(fb, this_event_period.start);
1256                         }
1257                 }
1258         
1259                 // Make sure the DTEND property of the freebusy *list* is set to
1260                 // the DTEND property of the *latest event*.
1261                 p = icalcomponent_get_first_property(fb, ICAL_DTEND_PROPERTY);
1262                 if (p == NULL) {
1263                         icalcomponent_set_dtend(fb, this_event_period.end);
1264                 }
1265                 else {
1266                         if (icaltime_compare(this_event_period.end, icalcomponent_get_dtend(fb)) > 0) {
1267                                 icalcomponent_set_dtend(fb, this_event_period.end);
1268                         }
1269                 }
1270
1271                 if (rrule) {
1272                         dtstart = icalrecur_iterator_next(ritr);
1273                         if (!icaltime_is_null_time(dtend)) {
1274                                 dtend = icaltime_add(dtstart, dur);
1275                                 dtend.zone = dtstart.zone;
1276                         }
1277                         ++num_recur;
1278                 }
1279
1280         } while ( (rrule) && (!icaltime_is_null_time(dtstart)) && (num_recur < MAX_RECUR) ) ;
1281         icalrecur_iterator_free(ritr);
1282 }
1283
1284
1285 /*
1286  * Backend for ical_freebusy()
1287  *
1288  * This function simply loads the messages in the user's calendar room,
1289  * which contain VEVENTs, then strips them of all non-freebusy data, and
1290  * adds them to the supplied VCALENDAR.
1291  *
1292  */
1293 void ical_freebusy_backend(long msgnum, void *data) {
1294         icalcomponent *fb;
1295         struct CtdlMessage *msg = NULL;
1296         struct ical_respond_data ird;
1297
1298         fb = (icalcomponent *)data;             // User-supplied data will be the VFREEBUSY component
1299
1300         msg = CtdlFetchMessage(msgnum, 1);
1301         if (msg == NULL) return;
1302         memset(&ird, 0, sizeof ird);
1303         strcpy(ird.desired_partnum, "_HUNT_");
1304         mime_parser(
1305                 CM_RANGE(msg, eMessageText),
1306                 *ical_locate_part,              // callback function
1307                 NULL,
1308                 NULL,
1309                 (void *) &ird,                  // user data
1310                 0
1311         );
1312         CM_Free(msg);
1313
1314         if (ird.cal) {
1315                 ical_add_to_freebusy(fb, ird.cal);              // Add VEVENT times to VFREEBUSY
1316                 icalcomponent_free(ird.cal);
1317         }
1318 }
1319
1320
1321 // Grab another user's free/busy times
1322 void ical_freebusy(char *who) {
1323         struct ctdluser usbuf;
1324         char calendar_room_name[ROOMNAMELEN];
1325         char hold_rm[ROOMNAMELEN];
1326         char *serialized_request = NULL;
1327         icalcomponent *encaps = NULL;
1328         icalcomponent *fb = NULL;
1329         int found_user = (-1);
1330         struct recptypes *recp = NULL;
1331         char buf[256];
1332         char host[256];
1333         char type[256];
1334         int i = 0;
1335         int config_lines = 0;
1336
1337         // First try an exact match.
1338         found_user = CtdlGetUser(&usbuf, who);
1339
1340         // If not found, try it as an unqualified email address.
1341         if (found_user != 0) {
1342                 strcpy(buf, who);
1343                 recp = validate_recipients(buf, NULL, 0);
1344                 syslog(LOG_DEBUG, "calendar: trying <%s>", buf);
1345                 if (recp != NULL) {
1346                         if (recp->num_local == 1) {
1347                                 found_user = CtdlGetUser(&usbuf, recp->recp_local);
1348                         }
1349                         free_recipients(recp);
1350                 }
1351         }
1352
1353         // If still not found, try it as an address qualified with the primary FQDN of this Citadel node.
1354         if (found_user != 0) {
1355                 snprintf(buf, sizeof buf, "%s@%s", who, CtdlGetConfigStr("c_fqdn"));
1356                 syslog(LOG_DEBUG, "calendar: trying <%s>", buf);
1357                 recp = validate_recipients(buf, NULL, 0);
1358                 if (recp != NULL) {
1359                         if (recp->num_local == 1) {
1360                                 found_user = CtdlGetUser(&usbuf, recp->recp_local);
1361                         }
1362                         free_recipients(recp);
1363                 }
1364         }
1365
1366         // Still not found?  Try qualifying it with every domain we might have addresses in.
1367         if (found_user != 0) {
1368                 config_lines = num_tokens(inetcfg, '\n');
1369                 for (i=0; ((i < config_lines) && (found_user != 0)); ++i) {
1370                         extract_token(buf, inetcfg, i, '\n', sizeof buf);
1371                         extract_token(host, buf, 0, '|', sizeof host);
1372                         extract_token(type, buf, 1, '|', sizeof type);
1373
1374                         if (    (!strcasecmp(type, "localhost"))
1375                                 || (!strcasecmp(type, "directory"))
1376                         ) {
1377                                 snprintf(buf, sizeof buf, "%s@%s", who, host);
1378                                 syslog(LOG_DEBUG, "calendar: trying <%s>", buf);
1379                                 recp = validate_recipients(buf, NULL, 0);
1380                                 if (recp != NULL) {
1381                                         if (recp->num_local == 1) {
1382                                                 found_user = CtdlGetUser(&usbuf, recp->recp_local);
1383                                         }
1384                                         free_recipients(recp);
1385                                 }
1386                         }
1387                 }
1388         }
1389
1390         if (found_user != 0) {
1391                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1392                 return;
1393         }
1394
1395         CtdlMailboxName(calendar_room_name, sizeof calendar_room_name, &usbuf, USERCALENDARROOM);
1396
1397         strcpy(hold_rm, CC->room.QRname);       // save current room
1398
1399         if (CtdlGetRoom(&CC->room, calendar_room_name) != 0) {
1400                 cprintf("%d Cannot open calendar\n", ERROR + ROOM_NOT_FOUND);
1401                 CtdlGetRoom(&CC->room, hold_rm);
1402                 return;
1403         }
1404
1405         // Create a VFREEBUSY subcomponent
1406         syslog(LOG_DEBUG, "calendar: creating VFREEBUSY component");
1407         fb = icalcomponent_new_vfreebusy();
1408         if (fb == NULL) {
1409                 cprintf("%d Internal error: cannot allocate memory.\n", ERROR + INTERNAL_ERROR);
1410                 CtdlGetRoom(&CC->room, hold_rm);
1411                 return;
1412         }
1413
1414         // Set the method to PUBLISH
1415         icalcomponent_set_method(fb, ICAL_METHOD_PUBLISH);
1416
1417         // Set the DTSTAMP to right now.
1418         icalcomponent_set_dtstamp(fb, icaltime_from_timet_with_zone(time(NULL), 0, icaltimezone_get_utc_timezone()));
1419
1420         // Add the user's email address as ORGANIZER
1421         sprintf(buf, "MAILTO:%s", who);
1422         if (strchr(buf, '@') == NULL) {
1423                 strcat(buf, "@");
1424                 strcat(buf, CtdlGetConfigStr("c_fqdn"));
1425         }
1426         for (i=0; buf[i]; ++i) {
1427                 if (buf[i]==' ') buf[i] = '_';
1428         }
1429         icalcomponent_add_property(fb, icalproperty_new_organizer(buf));
1430
1431         // Add busy time from events
1432         syslog(LOG_DEBUG, "calendar: adding busy time from events");
1433         CtdlForEachMessage(MSGS_ALL, 0, NULL, NULL, NULL, ical_freebusy_backend, (void *)fb );
1434
1435         // If values for DTSTART and DTEND are still not present, set them
1436         // to yesterday and tomorrow as default values.
1437         if (icalcomponent_get_first_property(fb, ICAL_DTSTART_PROPERTY) == NULL) {
1438                 icalcomponent_set_dtstart(fb, icaltime_from_timet_with_zone(time(NULL)-86400L, 0, icaltimezone_get_utc_timezone()));
1439         }
1440         if (icalcomponent_get_first_property(fb, ICAL_DTEND_PROPERTY) == NULL) {
1441                 icalcomponent_set_dtend(fb, icaltime_from_timet_with_zone(time(NULL)+86400L, 0, icaltimezone_get_utc_timezone()));
1442         }
1443
1444         // Put the freebusy component into the calendar component
1445         syslog(LOG_DEBUG, "calendar: encapsulating");
1446         encaps = ical_encapsulate_subcomponent(fb);
1447         if (encaps == NULL) {
1448                 icalcomponent_free(fb);
1449                 cprintf("%d Internal error: cannot allocate memory.\n",
1450                         ERROR + INTERNAL_ERROR);
1451                 CtdlGetRoom(&CC->room, hold_rm);
1452                 return;
1453         }
1454
1455         // Set the method to PUBLISH
1456         syslog(LOG_DEBUG, "calendar: setting method");
1457         icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1458
1459         // Serialize it
1460         syslog(LOG_DEBUG, "calendar: serializing");
1461         serialized_request = icalcomponent_as_ical_string_r(encaps);
1462         icalcomponent_free(encaps);     // Don't need this anymore.
1463
1464         cprintf("%d Free/busy for %s\n", LISTING_FOLLOWS, usbuf.fullname);
1465         if (serialized_request != NULL) {
1466                 client_write(serialized_request, strlen(serialized_request));
1467                 free(serialized_request);
1468         }
1469         cprintf("\n000\n");
1470
1471         // Go back to the room from which we came...
1472         CtdlGetRoom(&CC->room, hold_rm);
1473 }
1474
1475
1476 /*
1477  * Backend for ical_getics()
1478  * 
1479  * This is a ForEachMessage() callback function that searches the current room
1480  * for calendar events and adds them each into one big calendar component.
1481  */
1482 void ical_getics_backend(long msgnum, void *data) {
1483         icalcomponent *encaps, *c;
1484         struct CtdlMessage *msg = NULL;
1485         struct ical_respond_data ird;
1486
1487         encaps = (icalcomponent *)data;
1488         if (encaps == NULL) return;
1489
1490         /* Look for the calendar event... */
1491
1492         msg = CtdlFetchMessage(msgnum, 1);
1493         if (msg == NULL) return;
1494         memset(&ird, 0, sizeof ird);
1495         strcpy(ird.desired_partnum, "_HUNT_");
1496         mime_parser(
1497                 CM_RANGE(msg, eMessageText),
1498                 *ical_locate_part,              /* callback function */
1499                 NULL,
1500                 NULL,
1501                 (void *) &ird,                  /* user data */
1502                 0
1503         );
1504         CM_Free(msg);
1505
1506         if (ird.cal == NULL) return;
1507
1508         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1509          * are responsible for "the_request"'s memory -- it will be freed
1510          * when we free "encaps".
1511          */
1512
1513         /* If the top-level component is *not* a VCALENDAR, we can drop it right
1514          * in.  This will almost never happen.
1515          */
1516         if (icalcomponent_isa(ird.cal) != ICAL_VCALENDAR_COMPONENT) {
1517                 icalcomponent_add_component(encaps, ird.cal);
1518         }
1519         /*
1520          * In the more likely event that we're looking at a VCALENDAR with the VEVENT
1521          * and other components encapsulated inside, we have to extract them.
1522          */
1523         else {
1524                 for (c = icalcomponent_get_first_component(ird.cal, ICAL_ANY_COMPONENT);
1525                         (c != NULL);
1526                         c = icalcomponent_get_next_component(ird.cal, ICAL_ANY_COMPONENT)
1527                 ) {
1528
1529                         /* For VTIMEZONE components, suppress duplicates of the same tzid */
1530
1531                         if (icalcomponent_isa(c) == ICAL_VTIMEZONE_COMPONENT) {
1532                                 icalproperty *p = icalcomponent_get_first_property(c, ICAL_TZID_PROPERTY);
1533                                 if (p) {
1534                                         const char *tzid = icalproperty_get_tzid(p);
1535                                         if (!icalcomponent_get_timezone(encaps, tzid)) {
1536                                                 icalcomponent_add_component(encaps,
1537                                                                         icalcomponent_new_clone(c));
1538                                         }
1539                                 }
1540                         }
1541
1542                         /* All other types of components can go in verbatim */
1543                         else {
1544                                 icalcomponent_add_component(encaps, icalcomponent_new_clone(c));
1545                         }
1546                 }
1547                 icalcomponent_free(ird.cal);
1548         }
1549 }
1550
1551
1552 // Retrieve all of the calendar items in the current room, and output them
1553 // as a single icalendar object.
1554 void ical_getics(void) {
1555         icalcomponent *encaps = NULL;
1556         char *ser = NULL;
1557
1558         if (    (CC->room.QRdefaultview != VIEW_CALENDAR)
1559                 &&(CC->room.QRdefaultview != VIEW_TASKS)
1560         ) {
1561                 cprintf("%d Not a calendar room\n", ERROR+NOT_HERE);
1562                 return;         /* This room does not contain a calendar. */
1563         }
1564
1565         encaps = icalcomponent_new_vcalendar();
1566         if (encaps == NULL) {
1567                 syslog(LOG_ERR, "calendar: could not allocate component!");
1568                 cprintf("%d Could not allocate memory\n", ERROR+INTERNAL_ERROR);
1569                 return;
1570         }
1571
1572         cprintf("%d one big calendar\n", LISTING_FOLLOWS);
1573
1574         /* Set the Product ID */
1575         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1576
1577         /* Set the Version Number */
1578         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1579
1580         /* Set the method to PUBLISH */
1581         icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1582
1583         /* Now go through the room encapsulating all calendar items. */
1584         CtdlForEachMessage(MSGS_ALL, 0, NULL,
1585                 NULL,
1586                 NULL,
1587                 ical_getics_backend,
1588                 (void *) encaps
1589         );
1590
1591         ser = icalcomponent_as_ical_string_r(encaps);
1592         icalcomponent_free(encaps);                     /* Don't need this anymore. */
1593         client_write(ser, strlen(ser));
1594         free(ser);
1595         cprintf("\n000\n");
1596 }
1597
1598
1599 // Helper callback function for ical_putics() to discover which TZID's we need.
1600 // Simply put the tzid name string into a hash table.  After the callbacks are
1601 // done we'll go through them and attach the ones that we have.
1602 void ical_putics_grabtzids(icalparameter *param, void *data) {
1603         const char *tzid = icalparameter_get_tzid(param);
1604         HashList *keys = (HashList *) data;
1605         
1606         if ( (keys) && (tzid) && (!IsEmptyStr(tzid)) ) {
1607                 Put(keys, tzid, strlen(tzid), strdup(tzid), NULL);
1608         }
1609 }
1610
1611
1612 // Delete all of the calendar items in the current room, and replace them
1613 // with calendar items from a client-supplied data stream.
1614 void ical_putics(void) {
1615         char *calstream = NULL;
1616         icalcomponent *cal;
1617         icalcomponent *c;
1618         icalcomponent *encaps = NULL;
1619         HashList *tzidlist = NULL;
1620         HashPos *HashPos;
1621         void *Value;
1622         const char *Key;
1623         long len;
1624
1625         // Only allow this operation if we're in a room containing a calendar or tasks view
1626         if (    (CC->room.QRdefaultview != VIEW_CALENDAR)
1627                 && (CC->room.QRdefaultview != VIEW_TASKS)
1628         ) {
1629                 cprintf("%d Not a calendar room\n", ERROR+NOT_HERE);
1630                 return;
1631         }
1632
1633         // Only allow this operation if we have permission to overwrite the existing calendar
1634         if (!CtdlDoIHavePermissionToDeleteMessagesFromThisRoom()) {
1635                 cprintf("%d Permission denied.\n", ERROR+HIGHER_ACCESS_REQUIRED);
1636                 return;
1637         }
1638
1639         cprintf("%d Transmit data now\n", SEND_LISTING);
1640         calstream = CtdlReadMessageBody(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
1641         if (calstream == NULL) {
1642                 return;
1643         }
1644
1645         cal = icalcomponent_new_from_string(calstream);
1646         free(calstream);
1647
1648         /* We got our data stream -- now do something with it. */
1649
1650         /* Delete the existing messages in the room, because we are overwriting
1651          * the entire calendar with an entire new (or updated) calendar.
1652          * (Careful: this opens an S_ROOMS critical section!)
1653          */
1654         CtdlDeleteMessages(CC->room.QRname, NULL, 0, "");
1655
1656         /* If the top-level component is *not* a VCALENDAR, we can drop it right
1657          * in.  This will almost never happen.
1658          */
1659         if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
1660                 ical_write_to_cal(NULL, cal);
1661         }
1662         /*
1663          * In the more likely event that we're looking at a VCALENDAR with the VEVENT
1664          * and other components encapsulated inside, we have to extract them.
1665          */
1666         else {
1667                 for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1668                         (c != NULL);
1669                         c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
1670                 ) {
1671
1672                         /* Non-VTIMEZONE components each get written as individual messages.
1673                          * But we also need to attach the relevant VTIMEZONE components to them.
1674                          */
1675                         if (    (icalcomponent_isa(c) != ICAL_VTIMEZONE_COMPONENT)
1676                                 && (encaps = icalcomponent_new_vcalendar())
1677                         ) {
1678                                 icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1679                                 icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1680                                 icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1681
1682                                 /* Attach any needed timezones here */
1683                                 tzidlist = NewHash(1, NULL);
1684                                 if (tzidlist) {
1685                                         icalcomponent_foreach_tzid(c, ical_putics_grabtzids, tzidlist);
1686                                 }
1687                                 HashPos = GetNewHashPos(tzidlist, 0);
1688
1689                                 while (GetNextHashPos(tzidlist, HashPos, &len, &Key, &Value)) {
1690                                         syslog(LOG_DEBUG, "calendar: attaching timezone '%s'", (char*) Value);
1691                                         icaltimezone *t = NULL;
1692
1693                                         /* First look for a timezone attached to the original calendar */
1694                                         t = icalcomponent_get_timezone(cal, Value);
1695
1696                                         /* Try built-in tzdata if the right one wasn't attached */
1697                                         if (!t) {
1698                                                 t = icaltimezone_get_builtin_timezone(Value);
1699                                         }
1700
1701                                         /* I've got a valid timezone to attach. */
1702                                         if (t) {
1703                                                 icalcomponent_add_component(encaps,
1704                                                         icalcomponent_new_clone(
1705                                                                 icaltimezone_get_component(t)
1706                                                         )
1707                                                 );
1708                                         }
1709
1710                                 }
1711                                 DeleteHashPos(&HashPos);
1712                                 DeleteHash(&tzidlist);
1713
1714                                 /* Now attach the component itself (usually a VEVENT or VTODO) */
1715                                 icalcomponent_add_component(encaps, icalcomponent_new_clone(c));
1716
1717                                 /* Write it to the message store */
1718                                 ical_write_to_cal(NULL, encaps);
1719                                 icalcomponent_free(encaps);
1720                         }
1721                 }
1722         }
1723
1724         icalcomponent_free(cal);
1725 }
1726
1727
1728 /*
1729  * All Citadel calendar commands from the client come through here.
1730  */
1731 void cmd_ical(char *argbuf) {
1732         char subcmd[64];
1733         long msgnum;
1734         char partnum[256];
1735         char action[256];
1736         char who[256];
1737
1738         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1739
1740         /* Allow "test" and "freebusy" subcommands without logging in. */
1741
1742         if (!strcasecmp(subcmd, "test")) {
1743                 cprintf("%d This server supports calendaring\n", CIT_OK);
1744                 return;
1745         }
1746
1747         if (!strcasecmp(subcmd, "freebusy")) {
1748                 extract_token(who, argbuf, 1, '|', sizeof who);
1749                 ical_freebusy(who);
1750                 return;
1751         }
1752
1753         if (!strcasecmp(subcmd, "sgi")) {
1754                 CIT_ICAL->server_generated_invitations = (extract_int(argbuf, 1) ? 1 : 0) ;
1755                 cprintf("%d %d\n", CIT_OK, CIT_ICAL->server_generated_invitations);
1756                 return;
1757         }
1758
1759         if (CtdlAccessCheck(ac_logged_in)) return;
1760
1761         if (!strcasecmp(subcmd, "respond")) {
1762                 msgnum = extract_long(argbuf, 1);
1763                 extract_token(partnum, argbuf, 2, '|', sizeof partnum);
1764                 extract_token(action, argbuf, 3, '|', sizeof action);
1765                 ical_respond(msgnum, partnum, action);
1766                 return;
1767         }
1768
1769         if (!strcasecmp(subcmd, "handle_rsvp")) {
1770                 msgnum = extract_long(argbuf, 1);
1771                 extract_token(partnum, argbuf, 2, '|', sizeof partnum);
1772                 extract_token(action, argbuf, 3, '|', sizeof action);
1773                 ical_handle_rsvp(msgnum, partnum, action);
1774                 return;
1775         }
1776
1777         if (!strcasecmp(subcmd, "conflicts")) {
1778                 msgnum = extract_long(argbuf, 1);
1779                 extract_token(partnum, argbuf, 2, '|', sizeof partnum);
1780                 ical_conflicts(msgnum, partnum);
1781                 return;
1782         }
1783
1784         if (!strcasecmp(subcmd, "getics")) {
1785                 ical_getics();
1786                 return;
1787         }
1788
1789         if (!strcasecmp(subcmd, "putics")) {
1790                 ical_putics();
1791                 return;
1792         }
1793
1794         cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1795 }
1796
1797
1798 /*
1799  * We don't know if the calendar room exists so we just create it at login
1800  */
1801 void ical_CtdlCreateRoom(void) {
1802         struct ctdlroom qr;
1803         struct visit vbuf;
1804
1805         /* Create the calendar room if it doesn't already exist */
1806         CtdlCreateRoom(USERCALENDARROOM, 4, "", 0, 1, 0, VIEW_CALENDAR);
1807
1808         /* Set expiration policy to manual; otherwise objects will be lost! */
1809         if (CtdlGetRoomLock(&qr, USERCALENDARROOM)) {
1810                 syslog(LOG_ERR, "calendar: couldn't get the user calendar room");
1811                 return;
1812         }
1813         qr.QRep.expire_mode = EXPIRE_MANUAL;
1814         qr.QRdefaultview = VIEW_CALENDAR;       /* 3 = calendar view */
1815         CtdlPutRoomLock(&qr);
1816
1817         /* Set the view to a calendar view */
1818         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1819         vbuf.v_view = VIEW_CALENDAR;
1820         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1821
1822         /* Create the tasks list room if it doesn't already exist */
1823         CtdlCreateRoom(USERTASKSROOM, 4, "", 0, 1, 0, VIEW_TASKS);
1824
1825         /* Set expiration policy to manual; otherwise objects will be lost! */
1826         if (CtdlGetRoomLock(&qr, USERTASKSROOM)) {
1827                 syslog(LOG_ERR, "calendar: couldn't get the user calendar room!");
1828                 return;
1829         }
1830         qr.QRep.expire_mode = EXPIRE_MANUAL;
1831         qr.QRdefaultview = VIEW_TASKS;
1832         CtdlPutRoomLock(&qr);
1833
1834         /* Set the view to a task list view */
1835         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1836         vbuf.v_view = VIEW_TASKS;
1837         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1838
1839         /* Create the notes room if it doesn't already exist */
1840         CtdlCreateRoom(USERNOTESROOM, 4, "", 0, 1, 0, VIEW_NOTES);
1841
1842         /* Set expiration policy to manual; otherwise objects will be lost! */
1843         if (CtdlGetRoomLock(&qr, USERNOTESROOM)) {
1844                 syslog(LOG_ERR, "calendar: couldn't get the user calendar room!");
1845                 return;
1846         }
1847         qr.QRep.expire_mode = EXPIRE_MANUAL;
1848         qr.QRdefaultview = VIEW_NOTES;
1849         CtdlPutRoomLock(&qr);
1850
1851         /* Set the view to a notes view */
1852         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1853         vbuf.v_view = VIEW_NOTES;
1854         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1855
1856         return;
1857 }
1858
1859
1860 /*
1861  * ical_send_out_invitations() is called by ical_saving_vevent() when it finds a VEVENT.
1862  *
1863  * top_level_cal is the highest available level calendar object.
1864  * cal is the subcomponent containing the VEVENT.
1865  *
1866  * Note: if you change the encapsulation code here, change it in WebCit's ical_encapsulate_subcomponent()
1867  */
1868 void ical_send_out_invitations(icalcomponent *top_level_cal, icalcomponent *cal) {
1869         icalcomponent *the_request = NULL;
1870         char *serialized_request = NULL;
1871         icalcomponent *encaps = NULL;
1872         char *request_message_text = NULL;
1873         struct CtdlMessage *msg = NULL;
1874         struct recptypes *valid = NULL;
1875         char attendees_string[SIZ];
1876         int num_attendees = 0;
1877         char this_attendee[256];
1878         icalproperty *attendee = NULL;
1879         char summary_string[SIZ];
1880         icalproperty *summary = NULL;
1881         size_t reqsize;
1882         icalproperty *p;
1883         struct icaltimetype t;
1884         const icaltimezone *attached_zones[5] = { NULL, NULL, NULL, NULL, NULL };
1885         int i;
1886         const icaltimezone *z;
1887         int num_zones_attached = 0;
1888         int zone_already_attached;
1889         icalparameter *tzidp = NULL;
1890         const char *tzidc = NULL;
1891
1892         if (cal == NULL) {
1893                 syslog(LOG_ERR, "calendar: trying to reply to NULL event?");
1894                 return;
1895         }
1896
1897         /* If this is a VCALENDAR component, look for a VEVENT subcomponent. */
1898         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1899                 ical_send_out_invitations(top_level_cal,
1900                         icalcomponent_get_first_component(
1901                                 cal, ICAL_VEVENT_COMPONENT
1902                         )
1903                 );
1904                 return;
1905         }
1906
1907         /* Clone the event */
1908         the_request = icalcomponent_new_clone(cal);
1909         if (the_request == NULL) {
1910                 syslog(LOG_ERR, "calendar: cannot clone calendar object");
1911                 return;
1912         }
1913
1914         /* Extract the summary string -- we'll use it as the
1915          * message subject for the request
1916          */
1917         strcpy(summary_string, "Meeting request");
1918         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
1919         if (summary != NULL) {
1920                 if (icalproperty_get_summary(summary)) {
1921                         strcpy(summary_string,
1922                                 icalproperty_get_summary(summary) );
1923                 }
1924         }
1925
1926         /* Determine who the recipients of this message are (the attendees) */
1927         strcpy(attendees_string, "");
1928         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
1929                 const char *ch = icalproperty_get_attendee(attendee);
1930                 if ((ch != NULL) && !strncasecmp(ch, "MAILTO:", 7)) {
1931                         safestrncpy(this_attendee, ch + 7, sizeof(this_attendee));
1932                         
1933                         if (!CtdlIsMe(this_attendee, sizeof this_attendee)) {   /* don't send an invitation to myself! */
1934                                 snprintf(&attendees_string[strlen(attendees_string)],
1935                                          sizeof(attendees_string) - strlen(attendees_string),
1936                                          "%s, ",
1937                                          this_attendee
1938                                         );
1939                                 ++num_attendees;
1940                         }
1941                 }
1942         }
1943
1944         syslog(LOG_DEBUG, "calendar: <%d> attendees: <%s>", num_attendees, attendees_string);
1945
1946         /* If there are no attendees, there are no invitations to send, so...
1947          * don't bother putting one together!  Punch out, Maverick!
1948          */
1949         if (num_attendees == 0) {
1950                 icalcomponent_free(the_request);
1951                 return;
1952         }
1953
1954         /* Encapsulate the VEVENT component into a complete VCALENDAR */
1955         encaps = icalcomponent_new_vcalendar();
1956         if (encaps == NULL) {
1957                 syslog(LOG_ERR, "calendar: could not allocate component!");
1958                 icalcomponent_free(the_request);
1959                 return;
1960         }
1961
1962         /* Set the Product ID */
1963         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1964
1965         /* Set the Version Number */
1966         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1967
1968         /* Set the method to REQUEST */
1969         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
1970
1971         /* Look for properties containing timezone parameters, to see if we need to attach VTIMEZONEs */
1972         for (p = icalcomponent_get_first_property(the_request, ICAL_ANY_PROPERTY);
1973                 p != NULL;
1974                 p = icalcomponent_get_next_property(the_request, ICAL_ANY_PROPERTY)
1975         ) {
1976                 if (    (icalproperty_isa(p) == ICAL_COMPLETED_PROPERTY)
1977                         || (icalproperty_isa(p) == ICAL_CREATED_PROPERTY)
1978                         || (icalproperty_isa(p) == ICAL_DATEMAX_PROPERTY)
1979                         || (icalproperty_isa(p) == ICAL_DATEMIN_PROPERTY)
1980                         || (icalproperty_isa(p) == ICAL_DTEND_PROPERTY)
1981                         || (icalproperty_isa(p) == ICAL_DTSTAMP_PROPERTY)
1982                         || (icalproperty_isa(p) == ICAL_DTSTART_PROPERTY)
1983                         || (icalproperty_isa(p) == ICAL_DUE_PROPERTY)
1984                         || (icalproperty_isa(p) == ICAL_EXDATE_PROPERTY)
1985                         || (icalproperty_isa(p) == ICAL_LASTMODIFIED_PROPERTY)
1986                         || (icalproperty_isa(p) == ICAL_MAXDATE_PROPERTY)
1987                         || (icalproperty_isa(p) == ICAL_MINDATE_PROPERTY)
1988                         || (icalproperty_isa(p) == ICAL_RECURRENCEID_PROPERTY)
1989                 ) {
1990                         t = icalproperty_get_dtstart(p);        // it's safe to use dtstart for all of them
1991
1992                         /* Determine the tzid in order for some of the conditions below to work */
1993                         tzidp = icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER);
1994                         if (tzidp) {
1995                                 tzidc = icalparameter_get_tzid(tzidp);
1996                         }
1997                         else {
1998                                 tzidc = NULL;
1999                         }
2000
2001                         /* First see if there's a timezone attached to the data structure itself */
2002                         if (icaltime_is_utc(t)) {
2003                                 z = icaltimezone_get_utc_timezone();
2004                         }
2005                         else {
2006                                 z = icaltime_get_timezone(t);
2007                         }
2008
2009                         /* If not, try to determine the tzid from the parameter using attached zones */
2010                         if ((!z) && (tzidc)) {
2011                                 z = icalcomponent_get_timezone(top_level_cal, tzidc);
2012                         }
2013
2014                         /* Still no good?  Try our internal database */
2015                         if ((!z) && (tzidc)) {
2016                                 z = icaltimezone_get_builtin_timezone_from_tzid(tzidc);
2017                         }
2018
2019                         if (z) {
2020                                 /* We have a valid timezone.  Good.  Now we need to attach it. */
2021
2022                                 zone_already_attached = 0;
2023                                 for (i=0; i<5; ++i) {
2024                                         if (z == attached_zones[i]) {
2025                                                 /* We've already got this one, no need to attach another. */
2026                                                 ++zone_already_attached;
2027                                         }
2028                                 }
2029                                 if ((!zone_already_attached) && (num_zones_attached < 5)) {
2030                                         /* This is a new one, so attach it. */
2031                                         attached_zones[num_zones_attached++] = z;
2032                                 }
2033
2034                                 icalproperty_set_parameter(p, icalparameter_new_tzid(icaltimezone_get_tzid(z))
2035                                 );
2036                         }
2037                 }
2038         }
2039
2040         /* Encapsulate any timezones we need */
2041         if (num_zones_attached > 0) for (i=0; i<num_zones_attached; ++i) {
2042                 icalcomponent *zc;
2043                 zc = icalcomponent_new_clone(icaltimezone_get_component(attached_zones[i]));
2044                 icalcomponent_add_component(encaps, zc);
2045         }
2046
2047         /* Here we go: encapsulate the VEVENT into the VCALENDAR.  We now no longer
2048          * are responsible for "the_request"'s memory -- it will be freed
2049          * when we free "encaps".
2050          */
2051         icalcomponent_add_component(encaps, the_request);
2052
2053         /* Serialize it */
2054         serialized_request = icalcomponent_as_ical_string_r(encaps);
2055         icalcomponent_free(encaps);     /* Don't need this anymore. */
2056         if (serialized_request == NULL) return;
2057
2058         reqsize = strlen(serialized_request) + SIZ;
2059         request_message_text = malloc(reqsize);
2060         if (request_message_text != NULL) {
2061                 snprintf(request_message_text, reqsize,
2062                         "Content-type: text/calendar\r\n\r\n%s\r\n",
2063                         serialized_request
2064                 );
2065
2066                 msg = CtdlMakeMessage(
2067                         &CC->user,
2068                         NULL,                   /* No single recipient here */
2069                         NULL,                   /* No single recipient here */
2070                         CC->room.QRname,
2071                         0,
2072                         FMT_RFC822,
2073                         NULL,
2074                         NULL,
2075                         summary_string,         /* Use summary for subject */
2076                         NULL,
2077                         request_message_text,
2078                         NULL
2079                 );
2080         
2081                 if (msg != NULL) {
2082                         valid = validate_recipients(attendees_string, NULL, 0);
2083                         CtdlSubmitMsg(msg, valid, "");
2084                         CM_Free(msg);
2085                         free_recipients(valid);
2086                 }
2087         }
2088         free(serialized_request);
2089 }
2090
2091
2092 /*
2093  * When a calendar object is being saved, determine whether it's a VEVENT
2094  * and the user saving it is the organizer.  If so, send out invitations
2095  * to any listed attendees.
2096  *
2097  * This function is recursive.  The caller can simply supply the same object
2098  * as both arguments.  When it recurses it will alter the second argument
2099  * while holding on to the top level object.  This allows us to go back and
2100  * grab things like time zones which might be attached.
2101  *
2102  */
2103 void ical_saving_vevent(icalcomponent *top_level_cal, icalcomponent *cal) {
2104         icalcomponent *c;
2105         icalproperty *organizer = NULL;
2106         char organizer_string[SIZ];
2107
2108         syslog(LOG_DEBUG, "calendar: ical_saving_vevent() has been called");
2109
2110         /* Don't send out invitations unless the client wants us to. */
2111         if (CIT_ICAL->server_generated_invitations == 0) {
2112                 return;
2113         }
2114
2115         /* Don't send out invitations if we've been asked not to. */
2116         if (CIT_ICAL->avoid_sending_invitations > 0) {
2117                 return;
2118         }
2119
2120         strcpy(organizer_string, "");
2121         /*
2122          * The VEVENT subcomponent is the one we're interested in.
2123          * Send out invitations if, and only if, this user is the Organizer.
2124          */
2125         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
2126                 organizer = icalcomponent_get_first_property(cal, ICAL_ORGANIZER_PROPERTY);
2127                 if (organizer != NULL) {
2128                         if (icalproperty_get_organizer(organizer)) {
2129                                 strcpy(organizer_string,
2130                                         icalproperty_get_organizer(organizer));
2131                         }
2132                 }
2133                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
2134                         strcpy(organizer_string, &organizer_string[7]);
2135                         string_trim(organizer_string);
2136                         /*
2137                          * If the user saving the event is listed as the
2138                          * organizer, then send out invitations.
2139                          */
2140                         if (CtdlIsMe(organizer_string, sizeof organizer_string)) {
2141                                 ical_send_out_invitations(top_level_cal, cal);
2142                         }
2143                 }
2144         }
2145
2146         /* If the component has subcomponents, recurse through them. */
2147         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
2148                 (c != NULL);
2149                 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
2150         ) {
2151                 /* Recursively process subcomponent */
2152                 ical_saving_vevent(top_level_cal, c);
2153         }
2154
2155 }
2156
2157
2158 /*
2159  * Back end for ical_obj_beforesave()
2160  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
2161  * the summary of the event (becomes message subject),
2162  * and the start time (becomes message date/time).
2163  */
2164 void ical_obj_beforesave_backend(char *name, char *filename, char *partnum,
2165                 char *disp, void *content, char *cbtype, char *cbcharset, size_t length,
2166                 char *encoding, char *cbid, void *cbuserdata)
2167 {
2168         const char* pch;
2169         icalcomponent *cal, *nested_event, *nested_todo, *whole_cal;
2170         icalproperty *p;
2171         char new_uid[256] = "";
2172         struct CtdlMessage *msg = (struct CtdlMessage *) cbuserdata;
2173
2174         if (!msg) return;
2175
2176         /* We're only interested in calendar data. */
2177         if (    (strcasecmp(cbtype, "text/calendar"))
2178                 && (strcasecmp(cbtype, "application/ics"))
2179         ) {
2180                 return;
2181         }
2182
2183         // Hunt for the UID and drop it in the "user data" pointer for the MIME parser.
2184         // When ical_obj_beforesave() sees it there, it'll set the Exclusive msgid to that string.
2185         whole_cal = icalcomponent_new_from_string(content);
2186         cal = whole_cal;
2187         if (cal != NULL) {
2188                 if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
2189                         nested_event = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
2190                         if (nested_event != NULL) {
2191                                 cal = nested_event;
2192                         }
2193                         else {
2194                                 nested_todo = icalcomponent_get_first_component( cal, ICAL_VTODO_COMPONENT);
2195                                 if (nested_todo != NULL) {
2196                                         cal = nested_todo;
2197                                 }
2198                         }
2199                 }
2200
2201                 if (cal != NULL) {
2202
2203                         /* Set the message EUID to the iCalendar UID */
2204
2205                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
2206                         if (p == NULL) {
2207                                 /* If there's no uid we must generate one */
2208                                 generate_uuid(new_uid);
2209                                 icalcomponent_add_property(cal, icalproperty_new_uid(new_uid));
2210                                 p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
2211                         }
2212                         if (p != NULL) {
2213                                 pch = icalproperty_get_comment(p);
2214                                 if (!IsEmptyStr(pch)) {
2215                                         CM_SetField(msg, eExclusiveID, pch);
2216                                         syslog(LOG_DEBUG, "calendar: saving calendar UID <%s>", pch);
2217                                 }
2218                         }
2219
2220                         /* Set the message subject to the iCalendar summary */
2221
2222                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
2223                         if (p != NULL) {
2224                                 pch = icalproperty_get_comment(p);
2225                                 if (!IsEmptyStr(pch)) {
2226                                         char *subj;
2227
2228                                         subj = rfc2047encode(pch, strlen(pch));
2229                                         CM_SetAsField(msg, eMsgSubject, &subj, strlen(subj));
2230                                 }
2231                         }
2232
2233                         /* Set the message date/time to the iCalendar start time */
2234
2235                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
2236                         if (p != NULL) {
2237                                 time_t idtstart;
2238                                 idtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
2239                                 if (idtstart > 0) {
2240                                         CM_SetFieldLONG(msg, eTimestamp, idtstart);
2241                                 }
2242                         }
2243
2244                 }
2245                 icalcomponent_free(cal);
2246                 if (whole_cal != cal) {
2247                         icalcomponent_free(whole_cal);
2248                 }
2249         }
2250 }
2251
2252
2253 /*
2254  * See if we need to prevent the object from being saved (we don't allow
2255  * MIME types other than text/calendar in "calendar" or "tasks" rooms).
2256  *
2257  * If the message is being saved, we also set various message header fields
2258  * using data found in the iCalendar object.
2259  */
2260 int ical_obj_beforesave(struct CtdlMessage *msg, struct recptypes *recp) {
2261         /* First determine if this is a calendar or tasks room */
2262         if (    (CC->room.QRdefaultview != VIEW_CALENDAR)
2263                 && (CC->room.QRdefaultview != VIEW_TASKS)
2264         ) {
2265                 return(0);              /* Not an iCalendar-centric room */
2266         }
2267
2268         /* It must be an RFC822 message! */
2269         if (msg->cm_format_type != 4) {
2270                 syslog(LOG_DEBUG, "calendar: rejecting non-RFC822 message");
2271                 return(1);              /* You tried to save a non-RFC822 message! */
2272         }
2273
2274         if (CM_IsEmpty(msg, eMessageText)) {
2275                 return(1);              /* You tried to save a null message! */
2276         }
2277
2278         /* Do all of our lovely back-end parsing */
2279         mime_parser(
2280                 CM_RANGE(msg, eMessageText),
2281                 *ical_obj_beforesave_backend,
2282                 NULL,
2283                 NULL,
2284                 (void *)msg,
2285                 0
2286         );
2287
2288         return(0);
2289 }
2290
2291
2292 /*
2293  * Things we need to do after saving a calendar event.
2294  */
2295 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
2296                 char *disp, void *content, char *cbtype, char *cbcharset, size_t length,
2297                 char *encoding, char *cbid, void *cbuserdata)
2298 {
2299         icalcomponent *cal;
2300
2301         /* We're only interested in calendar items here. */
2302         if (    (strcasecmp(cbtype, "text/calendar"))
2303                 && (strcasecmp(cbtype, "application/ics"))
2304         ) {
2305                 return;
2306         }
2307
2308         /* Hunt for the UID and drop it in
2309          * the "user data" pointer for the MIME parser.  When
2310          * ical_obj_beforesave() sees it there, it'll set the Exclusive msgid
2311          * to that string.
2312          */
2313         if (    (!strcasecmp(cbtype, "text/calendar"))
2314                 || (!strcasecmp(cbtype, "application/ics"))
2315         ) {
2316                 cal = icalcomponent_new_from_string(content);
2317                 if (cal != NULL) {
2318                         ical_saving_vevent(cal, cal);
2319                         icalcomponent_free(cal);
2320                 }
2321         }
2322 }
2323
2324
2325 /* 
2326  * Things we need to do after saving a calendar event.
2327  * (This will start back end tasks such as automatic generation of invitations,
2328  * if such actions are appropriate.)
2329  */
2330 int ical_obj_aftersave(struct CtdlMessage *msg, struct recptypes *recp) {
2331         char roomname[ROOMNAMELEN];
2332
2333         /*
2334          * If this isn't the Calendar> room, no further action is necessary.
2335          */
2336
2337         /* First determine if this is our room */
2338         CtdlMailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
2339         if (strcasecmp(roomname, CC->room.QRname)) {
2340                 return(0);      /* Not the Calendar room -- don't do anything. */
2341         }
2342
2343         // It must be an RFC822 message!
2344         if (msg->cm_format_type != 4) return(1);
2345
2346         // Reject null messages
2347         if (CM_IsEmpty(msg, eMessageText)) return(1);
2348         
2349         // Now recurse through it looking for our icalendar data
2350         mime_parser(
2351                 CM_RANGE(msg, eMessageText),
2352                 *ical_obj_aftersave_backend,
2353                 NULL,
2354                 NULL,
2355                 NULL,
2356                 0
2357         );
2358
2359         return(0);
2360 }
2361
2362
2363 void ical_session_startup(void) {
2364         CIT_ICAL = malloc(sizeof(struct cit_ical));
2365         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
2366 }
2367
2368
2369 void ical_session_shutdown(void) {
2370         free(CIT_ICAL);
2371 }
2372
2373
2374 // Back end for ical_fixed_output()
2375 void ical_fixed_output_backend(icalcomponent *cal, int recursion_level) {
2376         icalcomponent *c;
2377         icalproperty *p;
2378         char buf[256];
2379         const char *ch;
2380
2381         p = icalcomponent_get_first_property(cal, ICAL_SUMMARY_PROPERTY);
2382         if (p != NULL) {
2383                 cprintf("%s\n", (const char *)icalproperty_get_comment(p));
2384         }
2385
2386         p = icalcomponent_get_first_property(cal, ICAL_LOCATION_PROPERTY);
2387         if (p != NULL) {
2388                 cprintf("%s\n", (const char *)icalproperty_get_comment(p));
2389         }
2390
2391         p = icalcomponent_get_first_property(cal, ICAL_DESCRIPTION_PROPERTY);
2392         if (p != NULL) {
2393                 cprintf("%s\n", (const char *)icalproperty_get_comment(p));
2394         }
2395
2396         // If the component has attendees, iterate through them.
2397         for (p = icalcomponent_get_first_property(cal, ICAL_ATTENDEE_PROPERTY); (p != NULL); p = icalcomponent_get_next_property(cal, ICAL_ATTENDEE_PROPERTY)) {
2398                 ch =  icalproperty_get_attendee(p);
2399                 if ((ch != NULL) && !strncasecmp(ch, "MAILTO:", 7)) {
2400
2401                         // screen name or email address
2402                         safestrncpy(buf, ch + 7, sizeof(buf));
2403                         string_trim(buf);
2404                         cprintf("%s ", buf);
2405                 }
2406                 cprintf("\n");
2407         }
2408
2409         // If the component has subcomponents, recurse through them.
2410         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
2411                 (c != 0);
2412                 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
2413         ) {
2414                 // Recursively process subcomponent 
2415                 ical_fixed_output_backend(c, recursion_level+1);
2416         }
2417 }
2418
2419
2420 // Function to output iCalendar data as plain text.  Nobody uses MSG0
2421 // anymore, so really this is just so we expose the vCard data to the full
2422 // text indexer.
2423 void ical_fixed_output(char *ptr, int len) {
2424         icalcomponent *cal;
2425         char *stringy_cal;
2426
2427         stringy_cal = malloc(len + 1);
2428         safestrncpy(stringy_cal, ptr, len + 1);
2429         cal = icalcomponent_new_from_string(stringy_cal);
2430         free(stringy_cal);
2431
2432         if (cal == NULL) {
2433                 return;
2434         }
2435
2436         ical_fixed_output_backend(cal, 0);
2437
2438         // Free the memory we obtained from libical's constructor
2439         icalcomponent_free(cal);
2440 }
2441
2442
2443 // Initialization function, called from modules_init.c
2444 char *ctdl_module_init_calendar(void) {
2445         if (!threading) {
2446
2447                 // Tell libical to return errors instead of aborting if it gets bad data.
2448                 // If this library call is not found, you need to upgrade libical.
2449                 icalerror_set_errors_are_fatal(0);
2450
2451                 // Use our own application prefix in tzid's generated from system tzdata
2452                 icaltimezone_set_tzid_prefix("/citadel.org/");
2453
2454                 // Initialize our hook functions
2455                 CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
2456                 CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
2457                 CtdlRegisterSessionHook(ical_CtdlCreateRoom, EVT_LOGIN, PRIO_LOGIN + 1);
2458                 CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCalendar commands");
2459                 CtdlRegisterSessionHook(ical_session_startup, EVT_START, PRIO_START + 1);
2460                 CtdlRegisterSessionHook(ical_session_shutdown, EVT_STOP, PRIO_STOP + 80);
2461                 CtdlRegisterFixedOutputHook("text/calendar", ical_fixed_output);
2462                 CtdlRegisterFixedOutputHook("application/ics", ical_fixed_output);
2463         }
2464
2465         // return our module name for the log
2466         return "calendar";
2467 }