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