* Renamed "struct user" to "struct ctdluser"
[citadel.git] / citadel / serv_calendar.c
index 2142a9bda931d279cf105d7efd9248e92a710f2b..849eacb70e6fd3f93172c57b9b04719444d09488 100644 (file)
@@ -7,6 +7,8 @@
  *
  */
 
+#define PRODID "-//Citadel//NONSGML Citadel Calendar//EN"
+
 #include "sysdep.h"
 #include <unistd.h>
 #include <sys/types.h>
 #ifdef HAVE_STRINGS_H
 #include <strings.h>
 #endif
-#include "serv_calendar.h"
 #include "citadel.h"
 #include "server.h"
 #include "citserver.h"
 #include "sysdep_decls.h"
 #include "support.h"
 #include "config.h"
-#include "dynloader.h"
+#include "serv_extensions.h"
 #include "user_ops.h"
 #include "room_ops.h"
 #include "tools.h"
 #include "msgbase.h"
 #include "mime_parser.h"
-#ifdef HAVE_ICAL_H
-#include <ical.h>
-#endif
+#include "serv_calendar.h"
 
+#ifdef CITADEL_WITH_CALENDAR_SERVICE
 
-#ifdef HAVE_ICAL_H
+#include <ical.h>
+#include "ical_dezonify.h"
 
 struct ical_respond_data {
        char desired_partnum[SIZ];
        icalcomponent *cal;
 };
 
+/* Session-local data for calendaring. */
+long SYM_CIT_ICAL;
+
+
+/*
+ * Utility function to create a new VCALENDAR component with some of the
+ * required fields already set the way we like them.
+ */
+icalcomponent *icalcomponent_new_citadel_vcalendar(void) {
+       icalcomponent *encaps;
+
+       encaps = icalcomponent_new_vcalendar();
+       if (encaps == NULL) {
+               lprintf(3, "Error at %s:%d - could not allocate component!\n",
+                       __FILE__, __LINE__);
+               return NULL;
+       }
+
+       /* Set the Product ID */
+       icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
+
+       /* Set the Version Number */
+       icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
+
+       return(encaps);
+}
+
+
+/*
+ * Utility function to encapsulate a subcomponent into a full VCALENDAR
+ */
+icalcomponent *ical_encapsulate_subcomponent(icalcomponent *subcomp) {
+       icalcomponent *encaps;
+
+       /* If we're already looking at a full VCALENDAR component,
+        * don't bother ... just return itself.
+        */
+       if (icalcomponent_isa(subcomp) == ICAL_VCALENDAR_COMPONENT) {
+               return subcomp;
+       }
+
+       /* Encapsulate the VEVENT component into a complete VCALENDAR */
+       encaps = icalcomponent_new_citadel_vcalendar();
+       if (encaps == NULL) return NULL;
+
+       /* Encapsulate the subcomponent inside */
+       icalcomponent_add_component(encaps, subcomp);
+
+       /* Convert all timestamps to UTC so we don't have to deal with
+        * stupid VTIMEZONE crap.
+        */
+       ical_dezonify(encaps);
+
+       /* Return the object we just created. */
+       return(encaps);
+}
 
 
 
 
 /*
- * Write our config to disk
+ * Write a calendar object into the specified user's calendar room.
+ * 
+ * ok
  */
-void ical_write_to_cal(struct usersupp *u, icalcomponent *cal) {
-        char temp[PATH_MAX];
-        FILE *fp;
+void ical_write_to_cal(struct ctdluser *u, icalcomponent *cal) {
+       char temp[PATH_MAX];
+       FILE *fp;
        char *ser;
+       icalcomponent *encaps;
+
+       if (cal == NULL) return;
+
+       /* If the supplied object is a subcomponent, encapsulate it in
+        * a full VCALENDAR component, and save that instead.
+        */
+       if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
+               encaps = ical_encapsulate_subcomponent(
+                       icalcomponent_new_clone(cal)
+               );
+               ical_write_to_cal(u, encaps);
+               icalcomponent_free(encaps);
+               return;
+       }
 
-        strcpy(temp, tmpnam(NULL));
+       strcpy(temp, tmpnam(NULL));
        ser = icalcomponent_as_ical_string(cal);
        if (ser == NULL) return;
 
        /* Make a temp file out of it */
-        fp = fopen(temp, "w");
-        if (fp == NULL) return;
+       fp = fopen(temp, "w");
+       if (fp == NULL) return;
        fwrite(ser, strlen(ser), 1, fp);
-        fclose(fp);
+       fclose(fp);
 
-        /* This handy API function does all the work for us.
-        * NOTE: normally we would want to set that last argument to 1, to
-        * force the system to delete the user's old vCard.  But it doesn't
-        * have to, because the vcard_upload_beforesave() hook above
-        * is going to notice what we're trying to do, and delete the old vCard.
+       /* This handy API function does all the work for us.
         */
-        CtdlWriteObject(USERCALENDARROOM,      /* which room */
+       CtdlWriteObject(USERCALENDARROOM,       /* which room */
                        "text/calendar",        /* MIME type */
                        temp,                   /* temp file */
                        u,                      /* which user */
@@ -77,12 +147,14 @@ void ical_write_to_cal(struct usersupp *u, icalcomponent *cal) {
                        0,              /* don't delete others of this type */
                        0);                     /* no flags */
 
-        unlink(temp);
+       unlink(temp);
 }
 
 
 /*
  * Add a calendar object to the user's calendar
+ * 
+ * ok because it uses ical_write_to_cal()
  */
 void ical_add(icalcomponent *cal, int recursion_level) {
        icalcomponent *c;
@@ -92,7 +164,7 @@ void ical_add(icalcomponent *cal, int recursion_level) {
         */
        if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
        
-               ical_write_to_cal(&CC->usersupp, cal);
+               ical_write_to_cal(&CC->user, cal);
 
        }
 
@@ -108,6 +180,159 @@ void ical_add(icalcomponent *cal, int recursion_level) {
 
 
 
+/*
+ * Send a reply to a meeting invitation.
+ *
+ * 'request' is the invitation to reply to.
+ * 'action' is the string "accept" or "decline".
+ *
+ * (Sorry about this being more than 80 columns ... there was just
+ * no easy way to break it down sensibly.)
+ * 
+ * ok
+ */
+void ical_send_a_reply(icalcomponent *request, char *action) {
+       icalcomponent *the_reply = NULL;
+       icalcomponent *vevent = NULL;
+       icalproperty *attendee = NULL;
+       char attendee_string[SIZ];
+       icalproperty *organizer = NULL;
+       char organizer_string[SIZ];
+       icalproperty *summary = NULL;
+       char summary_string[SIZ];
+       icalproperty *me_attend = NULL;
+       struct recptypes *recp = NULL;
+       icalparameter *partstat = NULL;
+       char *serialized_reply = NULL;
+       char *reply_message_text = NULL;
+       struct CtdlMessage *msg = NULL;
+       struct recptypes *valid = NULL;
+
+       strcpy(organizer_string, "");
+       strcpy(summary_string, "Calendar item");
+
+       if (request == NULL) {
+               lprintf(3, "ERROR: trying to reply to NULL event?\n");
+               return;
+       }
+
+       the_reply = icalcomponent_new_clone(request);
+       if (the_reply == NULL) {
+               lprintf(3, "ERROR: cannot clone request\n");
+               return;
+       }
+
+       /* Change the method from REQUEST to REPLY */
+       icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
+
+       vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
+       if (vevent != NULL) {
+               /* Hunt for attendees, removing ones that aren't us.
+                * (Actually, remove them all, cloning our own one so we can
+                * re-insert it later)
+                */
+               while (attendee = icalcomponent_get_first_property(vevent,
+                   ICAL_ATTENDEE_PROPERTY), (attendee != NULL)
+               ) {
+                       if (icalproperty_get_attendee(attendee)) {
+                               strcpy(attendee_string,
+                                       icalproperty_get_attendee(attendee) );
+                               if (!strncasecmp(attendee_string, "MAILTO:", 7)) {
+                                       strcpy(attendee_string, &attendee_string[7]);
+                                       striplt(attendee_string);
+                                       recp = validate_recipients(attendee_string);
+                                       if (recp != NULL) {
+                                               if (!strcasecmp(recp->recp_local, CC->user.fullname)) {
+                                                       if (me_attend) icalproperty_free(me_attend);
+                                                       me_attend = icalproperty_new_clone(attendee);
+                                               }
+                                               phree(recp);
+                                       }
+                               }
+                       }
+                       /* Remove it... */
+                       icalcomponent_remove_property(vevent, attendee);
+                       icalproperty_free(attendee);
+               }
+
+               /* We found our own address in the attendee list. */
+               if (me_attend) {
+                       /* Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE */
+                       icalproperty_remove_parameter(me_attend, ICAL_PARTSTAT_PARAMETER);
+
+                       if (!strcasecmp(action, "accept")) {
+                               partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
+                       }
+                       else if (!strcasecmp(action, "decline")) {
+                               partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
+                       }
+                       else if (!strcasecmp(action, "tentative")) {
+                               partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
+                       }
+
+                       if (partstat) icalproperty_add_parameter(me_attend, partstat);
+
+                       /* Now insert it back into the vevent. */
+                       icalcomponent_add_property(vevent, me_attend);
+               }
+
+               /* Figure out who to send this thing to */
+               organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
+               if (organizer != NULL) {
+                       if (icalproperty_get_organizer(organizer)) {
+                               strcpy(organizer_string,
+                                       icalproperty_get_organizer(organizer) );
+                       }
+               }
+               if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
+                       strcpy(organizer_string, &organizer_string[7]);
+                       striplt(organizer_string);
+               } else {
+                       strcpy(organizer_string, "");
+               }
+
+               /* Extract the summary string -- we'll use it as the
+                * message subject for the reply
+                */
+               summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
+               if (summary != NULL) {
+                       if (icalproperty_get_summary(summary)) {
+                               strcpy(summary_string,
+                                       icalproperty_get_summary(summary) );
+                       }
+               }
+
+       }
+
+       /* Now generate the reply message and send it out. */
+       serialized_reply = strdoop(icalcomponent_as_ical_string(the_reply));
+       icalcomponent_free(the_reply);  /* don't need this anymore */
+       if (serialized_reply == NULL) return;
+
+       reply_message_text = mallok(strlen(serialized_reply) + SIZ);
+       if (reply_message_text != NULL) {
+               sprintf(reply_message_text,
+                       "Content-type: text/calendar\r\n\r\n%s\r\n",
+                       serialized_reply
+               );
+
+               msg = CtdlMakeMessage(&CC->user, organizer_string,
+                       CC->room.QRname, 0, FMT_RFC822,
+                       "",
+                       summary_string,         /* Use summary for subject */
+                       reply_message_text);
+       
+               if (msg != NULL) {
+                       valid = validate_recipients(organizer_string);
+                       CtdlSubmitMsg(msg, valid, "");
+                       CtdlFreeMessage(msg);
+               }
+       }
+       phree(serialized_reply);
+}
+
+
+
 /*
  * Callback function for mime parser that hunts for calendar content types
  * and turns them into calendar objects
@@ -119,12 +344,30 @@ void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
        struct ical_respond_data *ird = NULL;
 
        ird = (struct ical_respond_data *) cbuserdata;
+
+       /* desired_partnum can be set to "_HUNT_" to have it just look for
+        * the first part with a content type of text/calendar.  Otherwise
+        * we have to only process the right one.
+        */
+       if (strcasecmp(ird->desired_partnum, "_HUNT_")) {
+               if (strcasecmp(partnum, ird->desired_partnum)) {
+                       return;
+               }
+       }
+
+       if (strcasecmp(cbtype, "text/calendar")) {
+               return;
+       }
+
        if (ird->cal != NULL) {
                icalcomponent_free(ird->cal);
                ird->cal = NULL;
        }
-       if (strcasecmp(partnum, ird->desired_partnum)) return;
+
        ird->cal = icalcomponent_new_from_string(content);
+       if (ird->cal != NULL) {
+               ical_dezonify(ird->cal);
+       }
 }
 
 
@@ -164,8 +407,14 @@ void ical_respond(long msgnum, char *partnum, char *action) {
                0
        );
 
+       /* We're done with the incoming message, because we now have a
+        * calendar object in memory.
+        */
        CtdlFreeMessage(msg);
 
+       /*
+        * Here is the real meat of this function.  Handle the event.
+        */
        if (ird.cal != NULL) {
                /* Save this in the user's calendar if necessary */
                if (!strcasecmp(action, "accept")) {
@@ -173,11 +422,16 @@ void ical_respond(long msgnum, char *partnum, char *action) {
                }
 
                /* Send a reply if necessary */
-               /* FIXME ... do this */
+               if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
+                       ical_send_a_reply(ird.cal, action);
+               }
 
-               /* Delete the message from the inbox */
-               /* FIXME ... do this */
+               /* Now that we've processed this message, we don't need it
+                * anymore.  So delete it.
+                */
+               CtdlDeleteMessages(CC->room.QRname, msgnum, "");
 
+               /* Free the memory we allocated and return a response. */
                icalcomponent_free(ird.cal);
                ird.cal = NULL;
                cprintf("%d ok\n", CIT_OK);
@@ -192,6 +446,361 @@ void ical_respond(long msgnum, char *partnum, char *action) {
 }
 
 
+/*
+ * Figure out the UID of the calendar event being referred to in a
+ * REPLY object.  This function is recursive.
+ */
+void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
+       icalcomponent *subcomponent;
+       icalproperty *p;
+
+       /* If this object is a REPLY, then extract the UID. */
+       if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
+               p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
+               if (p != NULL) {
+                       strcpy(uidbuf, icalproperty_get_comment(p));
+               }
+       }
+
+       /* Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
+        * UID of the reply; we want the UID of the invitation being replied to.
+        */
+       for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
+           subcomponent != NULL;
+           subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT) ) {
+               ical_learn_uid_of_reply(uidbuf, subcomponent);
+       }
+}
+
+
+/*
+ * ical_update_my_calendar_with_reply() refers to this callback function; when we
+ * locate the message containing the calendar event we're replying to, this function
+ * gets called.  It basically just sticks the message number in a supplied buffer.
+ */
+void ical_hunt_for_event_to_update(long msgnum, void *data) {
+       long *msgnumptr;
+
+       msgnumptr = (long *) data;
+       *msgnumptr = msgnum;
+}
+
+
+struct original_event_container {
+       icalcomponent *c;
+};
+
+/*
+ * Callback function for mime parser that hunts for calendar content types
+ * and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
+ * to fetch the object being updated)
+ */
+void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
+               void *content, char *cbtype, size_t length, char *encoding,
+               void *cbuserdata) {
+
+       struct original_event_container *oec = NULL;
+
+       if (strcasecmp(cbtype, "text/calendar")) {
+               return;
+       }
+       oec = (struct original_event_container *) cbuserdata;
+       if (oec->c != NULL) {
+               icalcomponent_free(oec->c);
+       }
+       oec->c = icalcomponent_new_from_string(content);
+}
+
+
+/*
+ * Merge updated attendee information from a REPLY into an existing event.
+ */
+void ical_merge_attendee_reply(icalcomponent *event, icalcomponent *reply) {
+       icalcomponent *c;
+       icalproperty *e_attendee, *r_attendee;
+
+       /* First things first.  If we're not looking at a VEVENT component,
+        * recurse through subcomponents until we find one.
+        */
+       if (icalcomponent_isa(event) != ICAL_VEVENT_COMPONENT) {
+               for (c = icalcomponent_get_first_component(event, ICAL_VEVENT_COMPONENT);
+                   c != NULL;
+                   c = icalcomponent_get_next_component(event, ICAL_VEVENT_COMPONENT) ) {
+                       ical_merge_attendee_reply(c, reply);
+               }
+               return;
+       }
+
+       /* Now do the same thing with the reply.
+        */
+       if (icalcomponent_isa(reply) != ICAL_VEVENT_COMPONENT) {
+               for (c = icalcomponent_get_first_component(reply, ICAL_VEVENT_COMPONENT);
+                   c != NULL;
+                   c = icalcomponent_get_next_component(reply, ICAL_VEVENT_COMPONENT) ) {
+                       ical_merge_attendee_reply(event, c);
+               }
+               return;
+       }
+
+       /* Clone the reply, because we're going to rip its guts out. */
+       reply = icalcomponent_new_clone(reply);
+
+       /* At this point we're looking at the correct subcomponents.
+        * Iterate through the attendees looking for a match.
+        */
+STARTOVER:
+       for (e_attendee = icalcomponent_get_first_property(event, ICAL_ATTENDEE_PROPERTY);
+           e_attendee != NULL;
+           e_attendee = icalcomponent_get_next_property(event, ICAL_ATTENDEE_PROPERTY)) {
+
+               for (r_attendee = icalcomponent_get_first_property(reply, ICAL_ATTENDEE_PROPERTY);
+                   r_attendee != NULL;
+                   r_attendee = icalcomponent_get_next_property(reply, ICAL_ATTENDEE_PROPERTY)) {
+
+                       /* Check to see if these two attendees match...
+                        */
+                       if (!strcasecmp(
+                          icalproperty_get_attendee(e_attendee),
+                          icalproperty_get_attendee(r_attendee)
+                       )) {
+                               /* ...and if they do, remove the attendee from the event
+                                * and replace it with the attendee from the reply.  (The
+                                * reply's copy will have the same address, but an updated
+                                * status.)
+                                */
+                               TRACE;
+                               icalcomponent_remove_property(event, e_attendee);
+                               TRACE;
+                               icalproperty_free(e_attendee);
+                               TRACE;
+                               icalcomponent_remove_property(reply, r_attendee);
+                               TRACE;
+                               icalcomponent_add_property(event, r_attendee);
+                               TRACE;
+
+                               /* Since we diddled both sets of attendees, we have to start
+                                * the iteration over again.  This will not create an infinite
+                                * loop because we removed the attendee from the reply.  (That's
+                                * why we cloned the reply, and that's what we mean by "ripping
+                                * its guts out.")
+                                */
+                               goto STARTOVER;
+                       }
+       
+               }
+       }
+
+       /* Free the *clone* of the reply. */
+       icalcomponent_free(reply);
+}
+
+
+
+
+/*
+ * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
+ * calendar event.  The object has already been deserialized for us; all
+ * we have to do here is hunt for the event in our calendar, merge in the
+ * updated attendee status, and save it again.
+ *
+ * This function returns 0 on success, 1 if the event was not found in the
+ * user's calendar, or 2 if an internal error occurred.
+ */
+int ical_update_my_calendar_with_reply(icalcomponent *cal) {
+       char uid[SIZ];
+       char hold_rm[ROOMNAMELEN];
+       long msgnum_being_replaced = 0;
+       struct CtdlMessage *template = NULL;
+       struct CtdlMessage *msg;
+       struct original_event_container oec;
+       icalcomponent *original_event;
+       char *serialized_event = NULL;
+       char roomname[ROOMNAMELEN];
+       char *message_text = NULL;
+
+       /* Figure out just what event it is we're dealing with */
+       strcpy(uid, "--==<< InVaLiD uId >>==--");
+       ical_learn_uid_of_reply(uid, cal);
+       lprintf(9, "UID of event being replied to is <%s>\n", uid);
+
+       strcpy(hold_rm, CC->room.QRname);       /* save current room */
+
+       if (getroom(&CC->room, USERCALENDARROOM) != 0) {
+               getroom(&CC->room, hold_rm);
+               lprintf(3, "cannot get user calendar room\n");
+               return(2);
+       }
+
+       /*
+        * Pound through the user's calendar looking for a message with
+        * the Citadel EUID set to the value we're looking for.  Since
+        * Citadel always sets the message EUID to the vCalendar UID of
+        * the event, this will work.
+        */
+       template = (struct CtdlMessage *)
+               mallok(sizeof(struct CtdlMessage));
+       memset(template, 0, sizeof(struct CtdlMessage));
+       template->cm_fields['E'] = strdoop(uid);
+       CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
+               template, ical_hunt_for_event_to_update, &msgnum_being_replaced);
+       CtdlFreeMessage(template);
+       getroom(&CC->room, hold_rm);    /* return to saved room */
+
+       lprintf(9, "msgnum_being_replaced == %ld\n", msgnum_being_replaced);
+       if (msgnum_being_replaced == 0) {
+               return(1);                      /* no calendar event found */
+       }
+
+       /* Now we know the ID of the message containing the event being updated.
+        * We don't actually have to delete it; that'll get taken care of by the
+        * server when we save another event with the same UID.  This just gives
+        * us the ability to load the event into memory so we can diddle the
+        * attendees.
+        */
+       msg = CtdlFetchMessage(msgnum_being_replaced);
+       if (msg == NULL) {
+               return(2);                      /* internal error */
+       }
+       oec.c = NULL;
+       mime_parser(msg->cm_fields['M'],
+               NULL,
+               *ical_locate_original_event,    /* callback function */
+               NULL, NULL,
+               &oec,                           /* user data */
+               0
+       );
+       CtdlFreeMessage(msg);
+
+       original_event = oec.c;
+       if (original_event == NULL) {
+               lprintf(3, "ERROR: Original_component is NULL.\n");
+               return(2);
+       }
+
+       /* Merge the attendee's updated status into the event */
+       ical_merge_attendee_reply(original_event, cal);
+
+       /* Serialize it */
+       serialized_event = strdoop(icalcomponent_as_ical_string(original_event));
+       icalcomponent_free(original_event);     /* Don't need this anymore. */
+       if (serialized_event == NULL) return(2);
+
+       MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
+
+       message_text = mallok(strlen(serialized_event) + SIZ);
+       if (message_text != NULL) {
+               sprintf(message_text,
+                       "Content-type: text/calendar\r\n\r\n%s\r\n",
+                       serialized_event
+               );
+
+               msg = CtdlMakeMessage(&CC->user,
+                       "",                     /* No recipient */
+                       roomname,
+                       0, FMT_RFC822,
+                       "",
+                       "",             /* no subject */
+                       message_text);
+       
+               if (msg != NULL) {
+                       CIT_ICAL->avoid_sending_invitations = 1;
+                       CtdlSubmitMsg(msg, NULL, roomname);
+                       CtdlFreeMessage(msg);
+                       CIT_ICAL->avoid_sending_invitations = 0;
+               }
+       }
+       phree(serialized_event);
+       return(0);
+}
+
+
+/*
+ * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
+ * simply extracts the calendar object from the message, deserializes it, and
+ * passes it up to ical_update_my_calendar_with_reply() for processing.
+ */
+void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
+       struct CtdlMessage *msg;
+       struct ical_respond_data ird;
+       int ret;
+
+       if (
+          (strcasecmp(action, "update"))
+          && (strcasecmp(action, "ignore"))
+       ) {
+               cprintf("%d Action must be 'update' or 'ignore'\n",
+                       ERROR + ILLEGAL_VALUE
+               );
+               return;
+       }
+
+       msg = CtdlFetchMessage(msgnum);
+       if (msg == NULL) {
+               cprintf("%d Message %ld not found.\n",
+                       ERROR+ILLEGAL_VALUE,
+                       (long)msgnum
+               );
+               return;
+       }
+
+       memset(&ird, 0, sizeof ird);
+       strcpy(ird.desired_partnum, partnum);
+       mime_parser(msg->cm_fields['M'],
+               NULL,
+               *ical_locate_part,              /* callback function */
+               NULL, NULL,
+               (void *) &ird,                  /* user data */
+               0
+       );
+
+       /* We're done with the incoming message, because we now have a
+        * calendar object in memory.
+        */
+       CtdlFreeMessage(msg);
+
+       /*
+        * Here is the real meat of this function.  Handle the event.
+        */
+       if (ird.cal != NULL) {
+               /* Update the user's calendar if necessary */
+               if (!strcasecmp(action, "update")) {
+                       ret = ical_update_my_calendar_with_reply(ird.cal);
+                       if (ret == 0) {
+                               cprintf("%d Your calendar has been updated with this reply.\n",
+                                       CIT_OK);
+                       }
+                       else if (ret == 1) {
+                               cprintf("%d This event does not exist in your calendar.\n",
+                                       ERROR + FILE_NOT_FOUND);
+                       }
+                       else {
+                               cprintf("%d An internal error occurred.\n",
+                                       ERROR + INTERNAL_ERROR);
+                       }
+               }
+               else {
+                       cprintf("%d This reply has been ignored.\n", CIT_OK);
+               }
+
+               /* Now that we've processed this message, we don't need it
+                * anymore.  So delete it.  (Maybe make this optional?)
+                */
+               CtdlDeleteMessages(CC->room.QRname, msgnum, "");
+
+               /* Free the memory we allocated and return a response. */
+               icalcomponent_free(ird.cal);
+               ird.cal = NULL;
+               return;
+       }
+       else {
+               cprintf("%d No calendar object found\n", ERROR);
+               return;
+       }
+
+       /* should never get here */
+}
+
+
 /*
  * Search for a property in both the top level and in a VEVENT subcomponent
  */
@@ -214,21 +823,10 @@ icalproperty *ical_ctdl_get_subprop(
 }
 
 
-/*
- * Helper function for ical_ctdl_is_overlap() to simplify the code when
- * comparing year/month/day.  The number doesn't have to be meaningful, only
- * consistent and unique for the supplied y/m/d combination.
- */
-inline int itymd(struct icaltimetype t) {
-       return (
-               (t.year * 416)
-               + (t.month * 32)
-               + (t.day)
-       );
-}
-
 /*
  * Check to see if two events overlap.  Returns nonzero if they do.
+ * (This function is used in both Citadel and WebCit.  If you change it in
+ * one place, change it in the other.  Better yet, put it in a library.)
  */
 int ical_ctdl_is_overlap(
                        struct icaltimetype t1start,
@@ -284,19 +882,25 @@ int ical_ctdl_is_overlap(
 /*
  * Backend for ical_hunt_for_conflicts()
  */
-void vcard_hunt_for_conflicts_backend(long msgnum, void *data) {
+void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
        icalcomponent *cal;
        struct CtdlMessage *msg;
        struct ical_respond_data ird;
        struct icaltimetype t1start, t1end, t2start, t2end;
        icalproperty *p;
+       char conflict_event_uid[SIZ];
+       char conflict_event_summary[SIZ];
+       char compare_uid[SIZ];
 
        cal = (icalcomponent *)data;
+       strcpy(compare_uid, "");
+       strcpy(conflict_event_uid, "");
+       strcpy(conflict_event_summary, "");
 
        msg = CtdlFetchMessage(msgnum);
        if (msg == NULL) return;
        memset(&ird, 0, sizeof ird);
-       strcpy(ird.desired_partnum, "1");       /* hopefully it's always 1 */
+       strcpy(ird.desired_partnum, "_HUNT_");
        mime_parser(msg->cm_fields['M'],
                NULL,
                *ical_locate_part,              /* callback function */
@@ -328,11 +932,32 @@ void vcard_hunt_for_conflicts_backend(long msgnum, void *data) {
        p = ical_ctdl_get_subprop(cal, ICAL_DTEND_PROPERTY);
        if (p != NULL) t1end = icalproperty_get_dtend(p);
        
+       p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
+       if (p != NULL) {
+               strcpy(compare_uid, icalproperty_get_comment(p));
+       }
+
+       p = ical_ctdl_get_subprop(ird.cal, ICAL_UID_PROPERTY);
+       if (p != NULL) {
+               strcpy(conflict_event_uid, icalproperty_get_comment(p));
+       }
+
+       p = ical_ctdl_get_subprop(ird.cal, ICAL_SUMMARY_PROPERTY);
+       if (p != NULL) {
+               strcpy(conflict_event_summary, icalproperty_get_comment(p));
+       }
+
        icalcomponent_free(ird.cal);
 
        if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
-               cprintf("%ld|FIXME put more here\n",
-                       msgnum
+               cprintf("%ld||%s|%s|%d|\n",
+                       msgnum,
+                       conflict_event_uid,
+                       conflict_event_summary,
+                       (       ((strlen(compare_uid)>0)
+                               &&(!strcasecmp(compare_uid,
+                               conflict_event_uid))) ? 1 : 0
+                       )
                );
        }
 }
@@ -347,26 +972,26 @@ void vcard_hunt_for_conflicts_backend(long msgnum, void *data) {
  * with this one.
  */
 void ical_hunt_for_conflicts(icalcomponent *cal) {
-        char hold_rm[ROOMNAMELEN];
+       char hold_rm[ROOMNAMELEN];
 
-        strcpy(hold_rm, CC->quickroom.QRname); /* save current room */
+       strcpy(hold_rm, CC->room.QRname);       /* save current room */
 
-        if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
-                getroom(&CC->quickroom, hold_rm);
+       if (getroom(&CC->room, USERCALENDARROOM) != 0) {
+               getroom(&CC->room, hold_rm);
                cprintf("%d You do not have a calendar.\n", ERROR);
                return;
-        }
+       }
 
        cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
 
-        CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
+       CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
                NULL,
-               vcard_hunt_for_conflicts_backend,
+               ical_hunt_for_conflicts_backend,
                (void *) cal
        );
 
        cprintf("000\n");
-        getroom(&CC->quickroom, hold_rm);      /* return to saved room */
+       getroom(&CC->room, hold_rm);    /* return to saved room */
 
 }
 
@@ -415,6 +1040,185 @@ void ical_conflicts(long msgnum, char *partnum) {
 
 
 
+/*
+ * Look for busy time in a VEVENT and add it to the supplied VFREEBUSY.
+ */
+void ical_add_to_freebusy(icalcomponent *fb, icalcomponent *cal) {
+       icalproperty *p;
+       icalvalue *v;
+       struct icalperiodtype my_period;
+
+       if (cal == NULL) return;
+       my_period = icalperiodtype_null_period();
+
+       if (icalcomponent_isa(cal) != ICAL_VEVENT_COMPONENT) {
+               ical_add_to_freebusy(fb,
+                       icalcomponent_get_first_component(
+                               cal, ICAL_VEVENT_COMPONENT
+                       )
+               );
+               return;
+       }
+
+       ical_dezonify(cal);
+
+       /* If this event is not opaque, the user isn't publishing it as
+        * busy time, so don't bother doing anything else.
+        */
+       p = icalcomponent_get_first_property(cal, ICAL_TRANSP_PROPERTY);
+       if (p != NULL) {
+               v = icalproperty_get_value(p);
+               if (v != NULL) {
+                       if (icalvalue_get_transp(v) != ICAL_TRANSP_OPAQUE) {
+                               return;
+                       }
+               }
+       }
+
+       /* Convert the DTSTART and DTEND properties to an icalperiod. */
+       p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
+       if (p != NULL) {
+               my_period.start = icalproperty_get_dtstart(p);
+       }
+
+       p = icalcomponent_get_first_property(cal, ICAL_DTEND_PROPERTY);
+       if (p != NULL) {
+               my_period.end = icalproperty_get_dtstart(p);
+       }
+
+       /* Now add it. */
+       icalcomponent_add_property(fb,
+               icalproperty_new_freebusy(my_period)
+       );
+
+}
+
+
+
+/*
+ * Backend for ical_freebusy()
+ *
+ * This function simply loads the messages in the user's calendar room,
+ * which contain VEVENTs, then strips them of all non-freebusy data, and
+ * adds them to the supplied VCALENDAR.
+ *
+ */
+void ical_freebusy_backend(long msgnum, void *data) {
+       icalcomponent *cal;
+       struct CtdlMessage *msg;
+       struct ical_respond_data ird;
+
+       cal = (icalcomponent *)data;
+
+       msg = CtdlFetchMessage(msgnum);
+       if (msg == NULL) return;
+       memset(&ird, 0, sizeof ird);
+       strcpy(ird.desired_partnum, "_HUNT_");
+       mime_parser(msg->cm_fields['M'],
+               NULL,
+               *ical_locate_part,              /* callback function */
+               NULL, NULL,
+               (void *) &ird,                  /* user data */
+               0
+       );
+       CtdlFreeMessage(msg);
+
+       if (ird.cal == NULL) return;
+
+       ical_add_to_freebusy(cal, ird.cal);
+
+       /* Now free the memory. */
+       icalcomponent_free(ird.cal);
+}
+
+
+
+/*
+ * Grab another user's free/busy times
+ */
+void ical_freebusy(char *who) {
+       struct ctdluser usbuf;
+       char calendar_room_name[ROOMNAMELEN];
+       char hold_rm[ROOMNAMELEN];
+       char *serialized_request = NULL;
+       icalcomponent *encaps = NULL;
+       icalcomponent *fb = NULL;
+
+       if (getuser(&usbuf, who) != 0) {
+               cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
+               return;
+       }
+
+       MailboxName(calendar_room_name, sizeof calendar_room_name,
+               &usbuf, USERCALENDARROOM);
+
+       strcpy(hold_rm, CC->room.QRname);       /* save current room */
+
+       if (getroom(&CC->room, calendar_room_name) != 0) {
+               cprintf("%d Cannot open calendar\n", ERROR+ROOM_NOT_FOUND);
+               getroom(&CC->room, hold_rm);
+               return;
+       }
+
+       /* Create a VFREEBUSY subcomponent */
+       lprintf(9, "Creating VFREEBUSY component\n");
+       fb = icalcomponent_new_vfreebusy();
+       if (fb == NULL) {
+               cprintf("%d Internal error: cannot allocate memory.\n",
+                       ERROR+INTERNAL_ERROR);
+               icalcomponent_free(encaps);
+               getroom(&CC->room, hold_rm);
+               return;
+       }
+
+       lprintf(9, "Adding busy time from events\n");
+       CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
+               NULL, ical_freebusy_backend, (void *)fb
+       );
+
+       /* Set the method to PUBLISH */
+       icalcomponent_set_method(fb, ICAL_METHOD_PUBLISH);
+
+       /* Set the DTSTAMP to right now. */
+       icalcomponent_set_dtstamp(fb, icaltime_from_timet(time(NULL), 0));
+
+       /* FIXME we still need (at least) DTSTART, DTEND, and the user's
+        * e-mail address as ORGANIZER.
+        */
+
+       /* Put the freebusy component into the calendar component */
+       lprintf(9, "Encapsulating\n");
+       encaps = ical_encapsulate_subcomponent(fb);
+       if (encaps == NULL) {
+               icalcomponent_free(fb);
+               cprintf("%d Internal error: cannot allocate memory.\n",
+                       ERROR+INTERNAL_ERROR);
+               getroom(&CC->room, hold_rm);
+               return;
+       }
+
+       /* Set the method to PUBLISH */
+       lprintf(9, "Setting method\n");
+       icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
+
+       /* Serialize it */
+       lprintf(9, "Serializing\n");
+       serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
+       icalcomponent_free(encaps);     /* Don't need this anymore. */
+
+       cprintf("%d Here is the free/busy data:\n", LISTING_FOLLOWS);
+       if (serialized_request != NULL) {
+               client_write(serialized_request, strlen(serialized_request));
+               phree(serialized_request);
+       }
+       cprintf("\n000\n");
+
+       /* Go back to the room from which we came... */
+       getroom(&CC->room, hold_rm);
+}
+
+
+
 
 /*
  * All Citadel calendar commands from the client come through here.
@@ -425,38 +1229,51 @@ void cmd_ical(char *argbuf)
        long msgnum;
        char partnum[SIZ];
        char action[SIZ];
-
-       if (CtdlAccessCheck(ac_logged_in)) return;
+       char who[SIZ];
 
        extract(subcmd, argbuf, 0);
 
+       /* Allow "test" and "freebusy" subcommands without logging in. */
+
        if (!strcmp(subcmd, "test")) {
                cprintf("%d This server supports calendaring\n", CIT_OK);
                return;
        }
 
-       else if (!strcmp(subcmd, "respond")) {
+       if (!strcmp(subcmd, "freebusy")) {
+               extract(who, argbuf, 1);
+               ical_freebusy(who);
+               return;
+       }
+
+       if (CtdlAccessCheck(ac_logged_in)) return;
+
+       if (!strcmp(subcmd, "respond")) {
                msgnum = extract_long(argbuf, 1);
                extract(partnum, argbuf, 2);
                extract(action, argbuf, 3);
                ical_respond(msgnum, partnum, action);
+               return;
        }
 
-       else if (!strcmp(subcmd, "conflicts")) {
+       if (!strcmp(subcmd, "handle_rsvp")) {
                msgnum = extract_long(argbuf, 1);
                extract(partnum, argbuf, 2);
-               ical_conflicts(msgnum, partnum);
+               extract(action, argbuf, 3);
+               ical_handle_rsvp(msgnum, partnum, action);
+               return;
        }
 
-       else {
-               cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
+       if (!strcmp(subcmd, "conflicts")) {
+               msgnum = extract_long(argbuf, 1);
+               extract(partnum, argbuf, 2);
+               ical_conflicts(msgnum, partnum);
                return;
        }
 
-       /* should never get here */
+       cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
 }
 
-#endif /* HAVE_ICAL_H */
 
 
 /*
@@ -464,7 +1281,7 @@ void cmd_ical(char *argbuf)
  */
 void ical_create_room(void)
 {
-       struct quickroom qr;
+       struct ctdlroom qr;
        struct visit vbuf;
 
        /* Create the calendar room if it doesn't already exist */
@@ -476,12 +1293,13 @@ void ical_create_room(void)
                return;
        }
        qr.QRep.expire_mode = EXPIRE_MANUAL;
+       qr.QRdefaultview = 3;   /* 3 = calendar view */
        lputroom(&qr);
 
        /* Set the view to a calendar view */
-       CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
+       CtdlGetRelationship(&vbuf, &CC->user, &qr);
        vbuf.v_view = 3;        /* 3 = calendar */
-       CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
+       CtdlSetRelationship(&vbuf, &CC->user, &qr);
 
        /* Create the tasks list room if it doesn't already exist */
        create_room(USERTASKSROOM, 4, "", 0, 1, 0);
@@ -492,35 +1310,294 @@ void ical_create_room(void)
                return;
        }
        qr.QRep.expire_mode = EXPIRE_MANUAL;
+       qr.QRdefaultview = 4;   /* 4 = tasks view */
        lputroom(&qr);
 
        /* Set the view to a task list view */
-       CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
+       CtdlGetRelationship(&vbuf, &CC->user, &qr);
        vbuf.v_view = 4;        /* 4 = tasks */
-       CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
+       CtdlSetRelationship(&vbuf, &CC->user, &qr);
 
        return;
 }
 
 
-/* See if we need to prevent the object from being saved */
+/*
+ * ical_send_out_invitations() is called by ical_saving_vevent() when it
+ * finds a VEVENT.
+ */
+void ical_send_out_invitations(icalcomponent *cal) {
+       icalcomponent *the_request = NULL;
+       char *serialized_request = NULL;
+       icalcomponent *encaps = NULL;
+       char *request_message_text = NULL;
+       struct CtdlMessage *msg = NULL;
+       struct recptypes *valid = NULL;
+       char attendees_string[SIZ];
+       int num_attendees = 0;
+       char this_attendee[SIZ];
+       icalproperty *attendee = NULL;
+       char summary_string[SIZ];
+       icalproperty *summary = NULL;
+
+       if (cal == NULL) {
+               lprintf(3, "ERROR: trying to reply to NULL event?\n");
+               return;
+       }
+
+
+       /* If this is a VCALENDAR component, look for a VEVENT subcomponent. */
+       if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
+               ical_send_out_invitations(
+                       icalcomponent_get_first_component(
+                               cal, ICAL_VEVENT_COMPONENT
+                       )
+               );
+               return;
+       }
+
+       /* Clone the event */
+       the_request = icalcomponent_new_clone(cal);
+       if (the_request == NULL) {
+               lprintf(3, "ERROR: cannot clone calendar object\n");
+               return;
+       }
+
+       /* Extract the summary string -- we'll use it as the
+        * message subject for the request
+        */
+       strcpy(summary_string, "Meeting request");
+       summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
+       if (summary != NULL) {
+               if (icalproperty_get_summary(summary)) {
+                       strcpy(summary_string,
+                               icalproperty_get_summary(summary) );
+               }
+       }
+
+       /* Determine who the recipients of this message are (the attendees) */
+       strcpy(attendees_string, "");
+       for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
+               if (icalproperty_get_attendee(attendee)) {
+                       strcpy(this_attendee, icalproperty_get_attendee(attendee) );
+                       if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
+                               strcpy(this_attendee, &this_attendee[7]);
+                               snprintf(&attendees_string[strlen(attendees_string)],
+                                       sizeof(attendees_string) - strlen(attendees_string),
+                                       "%s, ",
+                                       this_attendee
+                               );
+                               ++num_attendees;
+                       }
+               }
+       }
+
+       lprintf(9, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
+
+       /* If there are no attendees, there are no invitations to send, so...
+        * don't bother putting one together!  Punch out, Maverick!
+        */
+       if (num_attendees == 0) {
+               icalcomponent_free(the_request);
+               return;
+       }
+
+       /* Encapsulate the VEVENT component into a complete VCALENDAR */
+       encaps = icalcomponent_new_vcalendar();
+       if (encaps == NULL) {
+               lprintf(3, "Error at %s:%d - could not allocate component!\n",
+                       __FILE__, __LINE__);
+               icalcomponent_free(the_request);
+               return;
+       }
+
+       /* Set the Product ID */
+       icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
+
+       /* Set the Version Number */
+       icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
+
+       /* Set the method to REQUEST */
+       icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
+
+       /* Now make sure all of the DTSTART and DTEND properties are UTC. */
+       ical_dezonify(the_request);
+
+       /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
+        * are responsible for "the_request"'s memory -- it will be freed
+        * when we free "encaps".
+        */
+       icalcomponent_add_component(encaps, the_request);
+
+       /* Serialize it */
+       serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
+       icalcomponent_free(encaps);     /* Don't need this anymore. */
+       if (serialized_request == NULL) return;
+
+       request_message_text = mallok(strlen(serialized_request) + SIZ);
+       if (request_message_text != NULL) {
+               sprintf(request_message_text,
+                       "Content-type: text/calendar\r\n\r\n%s\r\n",
+                       serialized_request
+               );
+
+               msg = CtdlMakeMessage(&CC->user,
+                       "",                     /* No single recipient here */
+                       CC->room.QRname, 0, FMT_RFC822,
+                       "",
+                       summary_string,         /* Use summary for subject */
+                       request_message_text);
+       
+               if (msg != NULL) {
+                       valid = validate_recipients(attendees_string);
+                       CtdlSubmitMsg(msg, valid, "");
+                       CtdlFreeMessage(msg);
+               }
+       }
+       phree(serialized_request);
+}
+
+
+/*
+ * When a calendar object is being saved, determine whether it's a VEVENT
+ * and the user saving it is the organizer.  If so, send out invitations
+ * to any listed attendees.
+ *
+ */
+void ical_saving_vevent(icalcomponent *cal) {
+       icalcomponent *c;
+       icalproperty *organizer = NULL;
+       char organizer_string[SIZ];
+
+       /* Don't send out invitations if we've been asked not to. */
+       lprintf(9, "CIT_ICAL->avoid_sending_invitations = %d\n",
+               CIT_ICAL->avoid_sending_invitations);
+       if (CIT_ICAL->avoid_sending_invitations > 0) {
+               return;
+       }
+
+       strcpy(organizer_string, "");
+       /*
+        * The VEVENT subcomponent is the one we're interested in.
+        * Send out invitations if, and only if, this user is the Organizer.
+        */
+       if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
+               organizer = icalcomponent_get_first_property(cal,
+                                               ICAL_ORGANIZER_PROPERTY);
+               if (organizer != NULL) {
+                       if (icalproperty_get_organizer(organizer)) {
+                               strcpy(organizer_string,
+                                       icalproperty_get_organizer(organizer));
+                       }
+               }
+               if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
+                       strcpy(organizer_string, &organizer_string[7]);
+                       striplt(organizer_string);
+                       /*
+                        * If the user saving the event is listed as the
+                        * organizer, then send out invitations.
+                        */
+                       if (CtdlIsMe(organizer_string)) {
+                               ical_send_out_invitations(cal);
+                       }
+               }
+       }
+
+       /* If the component has subcomponents, recurse through them. */
+       for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
+           (c != NULL);
+           c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
+               /* Recursively process subcomponent */
+               ical_saving_vevent(c);
+       }
+
+}
+
+
+
+/*
+ * Back end for ical_obj_beforesave()
+ * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
+ * the summary of the event (becomes message subject),
+ * and the start time (becomes message date/time).
+ */
+void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
+               char *disp, void *content, char *cbtype, size_t length,
+               char *encoding, void *cbuserdata)
+{
+       icalcomponent *cal;
+       icalproperty *p;
+       struct icalmessagemod *imm;
+
+       imm = (struct icalmessagemod *)cbuserdata;
+
+       /* If this is a text/calendar object, hunt for the UID and drop it in
+        * the "user data" pointer for the MIME parser.  When
+        * ical_obj_beforesave() sees it there, it'll set the Extended msgid
+        * to that string.
+        */
+       if (!strcasecmp(cbtype, "text/calendar")) {
+               cal = icalcomponent_new_from_string(content);
+               if (cal != NULL) {
+                       if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
+                               cal = icalcomponent_get_first_component(
+                                       cal, ICAL_VEVENT_COMPONENT
+                               );
+                       }
+               }
+               if (cal != NULL) {
+                       p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
+                       if (p != NULL) {
+                               strcpy(imm->uid, icalproperty_get_comment(p));
+                       }
+                       p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
+                       if (p != NULL) {
+                               strcpy(imm->subject,
+                                               icalproperty_get_comment(p));
+                       }
+                       p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
+                       if (p != NULL) {
+                               imm->dtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
+                       }
+                       icalcomponent_free(cal);
+               }
+       }
+}
+
+
+
+
+
+/*
+ * See if we need to prevent the object from being saved (we don't allow
+ * MIME types other than text/calendar in the Calendar> room).  Also, when
+ * saving an event to the calendar, set the message's Citadel extended message
+ * ID to the UID of the object.  This causes our replication checker to
+ * automatically delete any existing instances of the same object.  (Isn't
+ * that cool?)
+ *
+ * We also set the message's Subject to the event summary, and the Date/time to
+ * the event start time.
+ */
 int ical_obj_beforesave(struct CtdlMessage *msg)
 {
        char roomname[ROOMNAMELEN];
        char *p;
        int a;
-       
+       struct icalmessagemod imm;
+
        /*
-        * Only messages with content-type text/calendar or text/x-calendar
+        * Only messages with content-type text/calendar
         * may be saved to Calendar>.  If the message is bound for
         * Calendar> but doesn't have this content-type, throw an error
         * so that the message may not be posted.
         */
 
        /* First determine if this is our room */
-       MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
-       if (strncmp(roomname, msg->cm_fields['O'], ROOMNAMELEN))
-               return 0;       /* It's not us... */
+       MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
+       if (strcasecmp(roomname, CC->room.QRname)) {
+               return 0;       /* It's not the Calendar room. */
+       }
 
        /* Then determine content-type of the message */
        
@@ -534,11 +1611,39 @@ int ical_obj_beforesave(struct CtdlMessage *msg)
        a = strlen(p);
        while (--a > 0) {
                if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
-                       if (!strncasecmp(p + 14, "text/x-calendar", 15) ||
-                           !strncasecmp(p + 14, "text/calendar", 13))
+                       if (!strncasecmp(p + 14, "text/calendar", 13)) {
+                               memset(&imm, 0, sizeof(struct icalmessagemod));
+                               mime_parser(msg->cm_fields['M'],
+                                       NULL,
+                                       *ical_ctdl_set_extended_msgid,
+                                       NULL, NULL,
+                                       (void *)&imm,
+                                       0
+                               );
+                               if (strlen(imm.uid) > 0) {
+                                       if (msg->cm_fields['E'] != NULL) {
+                                               phree(msg->cm_fields['E']);
+                                       }
+                                       msg->cm_fields['E'] = strdoop(imm.uid);
+                               }
+                               if (strlen(imm.subject) > 0) {
+                                       if (msg->cm_fields['U'] != NULL) {
+                                               phree(msg->cm_fields['U']);
+                                       }
+                                       msg->cm_fields['U'] = strdoop(imm.subject);
+                               }
+                               if (imm.dtstart > 0) {
+                                       if (msg->cm_fields['T'] != NULL) {
+                                               phree(msg->cm_fields['T']);
+                                       }
+                                       msg->cm_fields['T'] = strdoop("000000000000000000");
+                                       sprintf(msg->cm_fields['T'], "%ld", imm.dtstart);
+                               }
                                return 0;
-                       else
+                       }
+                       else {
                                return 1;
+                       }
                }
                p++;
        }
@@ -549,14 +1654,103 @@ int ical_obj_beforesave(struct CtdlMessage *msg)
 }
 
 
+/*
+ * Things we need to do after saving a calendar event.
+ */
+void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
+               char *disp, void *content, char *cbtype, size_t length,
+               char *encoding, void *cbuserdata)
+{
+       icalcomponent *cal;
+
+       /* If this is a text/calendar object, hunt for the UID and drop it in
+        * the "user data" pointer for the MIME parser.  When
+        * ical_obj_beforesave() sees it there, it'll set the Extended msgid
+        * to that string.
+        */
+       if (!strcasecmp(cbtype, "text/calendar")) {
+               cal = icalcomponent_new_from_string(content);
+               if (cal != NULL) {
+                       ical_saving_vevent(cal);
+                       icalcomponent_free(cal);
+               }
+       }
+}
+
+
+/* 
+ * Things we need to do after saving a calendar event.
+ */
+int ical_obj_aftersave(struct CtdlMessage *msg)
+{
+       char roomname[ROOMNAMELEN];
+       char *p;
+       int a;
+
+       /*
+        * If this isn't the Calendar> room, no further action is necessary.
+        */
 
-/* Register this module with the Citadel server. */
-char *Dynamic_Module_Init(void)
+       /* First determine if this is our room */
+       MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
+       if (strcasecmp(roomname, CC->room.QRname)) {
+               return 0;       /* It's not the Calendar room. */
+       }
+
+       /* Then determine content-type of the message */
+       
+       /* It must be an RFC822 message! */
+       /* FIXME: Not handling MIME multipart messages; implement with IMIP */
+       if (msg->cm_format_type != 4) return(1);
+       
+       /* Find the Content-Type: header */
+       p = msg->cm_fields['M'];
+       a = strlen(p);
+       while (--a > 0) {
+               if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
+                       if (!strncasecmp(p + 14, "text/calendar", 13)) {
+                               mime_parser(msg->cm_fields['M'],
+                                       NULL,
+                                       *ical_obj_aftersave_backend,
+                                       NULL, NULL,
+                                       NULL,
+                                       0
+                               );
+                               return 0;
+                       }
+                       else {
+                               return 1;
+                       }
+               }
+               p++;
+       }
+       
+       /* Oops!  No Content-Type in this message!  How'd that happen? */
+       lprintf(7, "RFC822 message with no Content-Type header!\n");
+       return 1;
+}
+
+
+void ical_session_startup(void) {
+       CtdlAllocUserData(SYM_CIT_ICAL, sizeof(struct cit_ical));
+       memset(CIT_ICAL, 0, sizeof(struct cit_ical));
+}
+
+
+#endif /* CITADEL_WITH_CALENDAR_SERVICE */
+
+/*
+ * Register this module with the Citadel server.
+ */
+char *serv_calendar_init(void)
 {
+#ifdef CITADEL_WITH_CALENDAR_SERVICE
+       SYM_CIT_ICAL = CtdlGetDynamicSymbol();
        CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
-#ifdef HAVE_ICAL_H
+       CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
        CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
        CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
+       CtdlRegisterSessionHook(ical_session_startup, EVT_START);
 #endif
        return "$Id$";
 }