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