* set up ical_dezonify() to be called at appropriate times
[citadel.git] / citadel / serv_calendar.c
1 /* 
2  * $Id$ 
3  *
4  * This module implements iCalendar object processing and the Calendar>
5  * room on a Citadel/UX 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 <unistd.h>
14 #include <sys/types.h>
15 #include <limits.h>
16 #include <stdio.h>
17 #include <string.h>
18 #ifdef HAVE_STRINGS_H
19 #include <strings.h>
20 #endif
21 #include "citadel.h"
22 #include "server.h"
23 #include "citserver.h"
24 #include "sysdep_decls.h"
25 #include "support.h"
26 #include "config.h"
27 #include "dynloader.h"
28 #include "user_ops.h"
29 #include "room_ops.h"
30 #include "tools.h"
31 #include "msgbase.h"
32 #include "mime_parser.h"
33 #include "serv_calendar.h"
34
35 #ifdef HAVE_ICAL_H
36
37 #include <ical.h>
38 #include "ical_dezonify.h"
39
40 struct ical_respond_data {
41         char desired_partnum[SIZ];
42         icalcomponent *cal;
43 };
44
45 /* Session-local data for calendaring. */
46 long SYM_CIT_ICAL;
47
48 /*
49  * Write a calendar object into the specified user's calendar room.
50  */
51 void ical_write_to_cal(struct usersupp *u, icalcomponent *cal) {
52         char temp[PATH_MAX];
53         FILE *fp;
54         char *ser;
55
56         strcpy(temp, tmpnam(NULL));
57         ser = icalcomponent_as_ical_string(cal);
58         if (ser == NULL) return;
59
60         /* Make a temp file out of it */
61         fp = fopen(temp, "w");
62         if (fp == NULL) return;
63         fwrite(ser, strlen(ser), 1, fp);
64         fclose(fp);
65
66         /* This handy API function does all the work for us.
67          */
68         CtdlWriteObject(USERCALENDARROOM,       /* which room */
69                         "text/calendar",        /* MIME type */
70                         temp,                   /* temp file */
71                         u,                      /* which user */
72                         0,                      /* not binary */
73                         0,              /* don't delete others of this type */
74                         0);                     /* no flags */
75
76         unlink(temp);
77 }
78
79
80 /*
81  * Add a calendar object to the user's calendar
82  */
83 void ical_add(icalcomponent *cal, int recursion_level) {
84         icalcomponent *c;
85
86         /*
87          * The VEVENT subcomponent is the one we're interested in saving.
88          */
89         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
90         
91                 ical_write_to_cal(&CC->usersupp, cal);
92
93         }
94
95         /* If the component has subcomponents, recurse through them. */
96         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
97             (c != 0);
98             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
99                 /* Recursively process subcomponent */
100                 ical_add(c, recursion_level+1);
101         }
102
103 }
104
105
106
107 /*
108  * Send a reply to a meeting invitation.
109  *
110  * 'request' is the invitation to reply to.
111  * 'action' is the string "accept" or "decline".
112  *
113  * (Sorry about this being more than 80 columns ... there was just
114  * no easy way to break it down sensibly.)
115  */
116 void ical_send_a_reply(icalcomponent *request, char *action) {
117         icalcomponent *the_reply = NULL;
118         icalcomponent *vevent = NULL;
119         icalproperty *attendee = NULL;
120         char attendee_string[SIZ];
121         icalproperty *organizer = NULL;
122         char organizer_string[SIZ];
123         icalproperty *summary = NULL;
124         char summary_string[SIZ];
125         icalproperty *me_attend = NULL;
126         struct recptypes *recp = NULL;
127         icalparameter *partstat = NULL;
128         char *serialized_reply = NULL;
129         char *reply_message_text = NULL;
130         struct CtdlMessage *msg = NULL;
131         struct recptypes *valid = NULL;
132
133         strcpy(organizer_string, "");
134         strcpy(summary_string, "Calendar item");
135
136         if (request == NULL) {
137                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
138                 return;
139         }
140
141         the_reply = icalcomponent_new_clone(request);
142         ical_dezonify(the_reply);
143         if (the_reply == NULL) {
144                 lprintf(3, "ERROR: cannot clone request\n");
145                 return;
146         }
147
148         /* Change the method from REQUEST to REPLY */
149         icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
150
151         vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
152         if (vevent != NULL) {
153                 /* Hunt for attendees, removing ones that aren't us.
154                  * (Actually, remove them all, cloning our own one so we can
155                  * re-insert it later)
156                  */
157                 while (attendee = icalcomponent_get_first_property(vevent,
158                     ICAL_ATTENDEE_PROPERTY), (attendee != NULL)
159                 ) {
160                         if (icalproperty_get_attendee(attendee)) {
161                                 strcpy(attendee_string,
162                                         icalproperty_get_attendee(attendee) );
163                                 if (!strncasecmp(attendee_string, "MAILTO:", 7)) {
164                                         strcpy(attendee_string, &attendee_string[7]);
165                                         striplt(attendee_string);
166                                         recp = validate_recipients(attendee_string);
167                                         if (recp != NULL) {
168                                                 if (!strcasecmp(recp->recp_local, CC->usersupp.fullname)) {
169                                                         if (me_attend) icalproperty_free(me_attend);
170                                                         me_attend = icalproperty_new_clone(attendee);
171                                                 }
172                                                 phree(recp);
173                                         }
174                                 }
175                         }
176                         /* Remove it... */
177                         icalcomponent_remove_property(vevent, attendee);
178                         icalproperty_free(attendee);
179                 }
180
181                 /* We found our own address in the attendee list. */
182                 if (me_attend) {
183                         /* Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE */
184                         icalproperty_remove_parameter(me_attend, ICAL_PARTSTAT_PARAMETER);
185
186                         if (!strcasecmp(action, "accept")) {
187                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
188                         }
189                         else if (!strcasecmp(action, "decline")) {
190                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
191                         }
192                         else if (!strcasecmp(action, "tentative")) {
193                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
194                         }
195
196                         if (partstat) icalproperty_add_parameter(me_attend, partstat);
197
198                         /* Now insert it back into the vevent. */
199                         icalcomponent_add_property(vevent, me_attend);
200                 }
201
202                 /* Figure out who to send this thing to */
203                 organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
204                 if (organizer != NULL) {
205                         if (icalproperty_get_organizer(organizer)) {
206                                 strcpy(organizer_string,
207                                         icalproperty_get_organizer(organizer) );
208                         }
209                 }
210                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
211                         strcpy(organizer_string, &organizer_string[7]);
212                         striplt(organizer_string);
213                 } else {
214                         strcpy(organizer_string, "");
215                 }
216
217                 /* Extract the summary string -- we'll use it as the
218                  * message subject for the reply
219                  */
220                 summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
221                 if (summary != NULL) {
222                         if (icalproperty_get_summary(summary)) {
223                                 strcpy(summary_string,
224                                         icalproperty_get_summary(summary) );
225                         }
226                 }
227
228         }
229
230         /* Now generate the reply message and send it out. */
231         serialized_reply = strdoop(icalcomponent_as_ical_string(the_reply));
232         icalcomponent_free(the_reply);  /* don't need this anymore */
233         if (serialized_reply == NULL) return;
234
235         reply_message_text = mallok(strlen(serialized_reply) + SIZ);
236         if (reply_message_text != NULL) {
237                 sprintf(reply_message_text,
238                         "Content-type: text/calendar\r\n\r\n%s\r\n",
239                         serialized_reply
240                 );
241
242                 msg = CtdlMakeMessage(&CC->usersupp, organizer_string,
243                         CC->quickroom.QRname, 0, FMT_RFC822,
244                         "",
245                         summary_string,         /* Use summary for subject */
246                         reply_message_text);
247         
248                 if (msg != NULL) {
249                         valid = validate_recipients(organizer_string);
250                         CtdlSubmitMsg(msg, valid, "");
251                         CtdlFreeMessage(msg);
252                 }
253         }
254         phree(serialized_reply);
255 }
256
257
258
259 /*
260  * Callback function for mime parser that hunts for calendar content types
261  * and turns them into calendar objects
262  */
263 void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
264                 void *content, char *cbtype, size_t length, char *encoding,
265                 void *cbuserdata) {
266
267         struct ical_respond_data *ird = NULL;
268
269         ird = (struct ical_respond_data *) cbuserdata;
270         if (ird->cal != NULL) {
271                 icalcomponent_free(ird->cal);
272                 ird->cal = NULL;
273         }
274         if (strcasecmp(partnum, ird->desired_partnum)) return;
275         ird->cal = icalcomponent_new_from_string(content);
276         ical_dezonify(ird->cal);
277 }
278
279
280 /*
281  * Respond to a meeting request.
282  */
283 void ical_respond(long msgnum, char *partnum, char *action) {
284         struct CtdlMessage *msg;
285         struct ical_respond_data ird;
286
287         if (
288            (strcasecmp(action, "accept"))
289            && (strcasecmp(action, "decline"))
290         ) {
291                 cprintf("%d Action must be 'accept' or 'decline'\n",
292                         ERROR + ILLEGAL_VALUE
293                 );
294                 return;
295         }
296
297         msg = CtdlFetchMessage(msgnum);
298         if (msg == NULL) {
299                 cprintf("%d Message %ld not found.\n",
300                         ERROR+ILLEGAL_VALUE,
301                         (long)msgnum
302                 );
303                 return;
304         }
305
306         memset(&ird, 0, sizeof ird);
307         strcpy(ird.desired_partnum, partnum);
308         mime_parser(msg->cm_fields['M'],
309                 NULL,
310                 *ical_locate_part,              /* callback function */
311                 NULL, NULL,
312                 (void *) &ird,                  /* user data */
313                 0
314         );
315
316         /* We're done with the incoming message, because we now have a
317          * calendar object in memory.
318          */
319         CtdlFreeMessage(msg);
320
321         /*
322          * Here is the real meat of this function.  Handle the event.
323          */
324         if (ird.cal != NULL) {
325                 /* Save this in the user's calendar if necessary */
326                 if (!strcasecmp(action, "accept")) {
327                         ical_add(ird.cal, 0);
328                 }
329
330                 /* Send a reply if necessary */
331                 if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
332                         ical_send_a_reply(ird.cal, action);
333                 }
334
335                 /* Now that we've processed this message, we don't need it
336                  * anymore.  So delete it.
337                  */
338                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
339
340                 /* Free the memory we allocated and return a response. */
341                 icalcomponent_free(ird.cal);
342                 ird.cal = NULL;
343                 cprintf("%d ok\n", CIT_OK);
344                 return;
345         }
346         else {
347                 cprintf("%d No calendar object found\n", ERROR);
348                 return;
349         }
350
351         /* should never get here */
352 }
353
354
355 /*
356  * Figure out the UID of the calendar event being referred to in a
357  * REPLY object.  This function is recursive.
358  */
359 void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
360         icalcomponent *subcomponent;
361         icalproperty *p;
362
363         /* If this object is a REPLY, then extract the UID. */
364         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
365                 p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
366                 if (p != NULL) {
367                         strcpy(uidbuf, icalproperty_get_comment(p));
368                 }
369         }
370
371         /* Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
372          * UID of the reply; we want the UID of the invitation being replied to.
373          */
374         for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
375             subcomponent != NULL;
376             subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT) ) {
377                 ical_learn_uid_of_reply(uidbuf, subcomponent);
378         }
379 }
380
381
382 /*
383  * ical_update_my_calendar_with_reply() refers to this callback function; when we
384  * locate the message containing the calendar event we're replying to, this function
385  * gets called.  It basically just sticks the message number in a supplied buffer.
386  */
387 void ical_hunt_for_event_to_update(long msgnum, void *data) {
388         long *msgnumptr;
389
390         msgnumptr = (long *) data;
391         *msgnumptr = msgnum;
392 }
393
394
395 struct original_event_container {
396         icalcomponent *c;
397 };
398
399 /*
400  * Callback function for mime parser that hunts for calendar content types
401  * and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
402  * to fetch the object being updated)
403  */
404 void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
405                 void *content, char *cbtype, size_t length, char *encoding,
406                 void *cbuserdata) {
407
408         struct original_event_container *oec = NULL;
409
410         if (strcasecmp(cbtype, "text/calendar")) {
411                 return;
412         }
413         oec = (struct original_event_container *) cbuserdata;
414         if (oec->c != NULL) {
415                 icalcomponent_free(oec->c);
416         }
417         oec->c = icalcomponent_new_from_string(content);
418         ical_dezonify(oec->c);
419 }
420
421
422 /*
423  * Merge updated attendee information from a REPLY into an existing event.
424  */
425 void ical_merge_attendee_reply(icalcomponent *event, icalcomponent *reply) {
426         icalcomponent *c;
427         icalproperty *e_attendee, *r_attendee;
428
429         /* First things first.  If we're not looking at a VEVENT component,
430          * recurse through subcomponents until we find one.
431          */
432         if (icalcomponent_isa(event) != ICAL_VEVENT_COMPONENT) {
433                 for (c = icalcomponent_get_first_component(event, ICAL_VEVENT_COMPONENT);
434                     c != NULL;
435                     c = icalcomponent_get_next_component(event, ICAL_VEVENT_COMPONENT) ) {
436                         ical_merge_attendee_reply(c, reply);
437                 }
438                 return;
439         }
440
441         /* Now do the same thing with the reply.
442          */
443         if (icalcomponent_isa(reply) != ICAL_VEVENT_COMPONENT) {
444                 for (c = icalcomponent_get_first_component(reply, ICAL_VEVENT_COMPONENT);
445                     c != NULL;
446                     c = icalcomponent_get_next_component(reply, ICAL_VEVENT_COMPONENT) ) {
447                         ical_merge_attendee_reply(event, c);
448                 }
449                 return;
450         }
451
452         /* Clone the reply, because we're going to rip its guts out. */
453         reply = icalcomponent_new_clone(reply);
454         ical_dezonify(reply);
455
456         /* At this point we're looking at the correct subcomponents.
457          * Iterate through the attendees looking for a match.
458          */
459 STARTOVER:
460         for (e_attendee = icalcomponent_get_first_property(event, ICAL_ATTENDEE_PROPERTY);
461             e_attendee != NULL;
462             e_attendee = icalcomponent_get_next_property(event, ICAL_ATTENDEE_PROPERTY)) {
463
464                 for (r_attendee = icalcomponent_get_first_property(reply, ICAL_ATTENDEE_PROPERTY);
465                     r_attendee != NULL;
466                     r_attendee = icalcomponent_get_next_property(reply, ICAL_ATTENDEE_PROPERTY)) {
467
468                         /* Check to see if these two attendees match...
469                          */
470                         if (!strcasecmp(
471                            icalproperty_get_attendee(e_attendee),
472                            icalproperty_get_attendee(r_attendee)
473                         )) {
474                                 /* ...and if they do, remove the attendee from the event
475                                  * and replace it with the attendee from the reply.  (The
476                                  * reply's copy will have the same address, but an updated
477                                  * status.)
478                                  */
479                                 TRACE;
480                                 icalcomponent_remove_property(event, e_attendee);
481                                 TRACE;
482                                 icalproperty_free(e_attendee);
483                                 TRACE;
484                                 icalcomponent_remove_property(reply, r_attendee);
485                                 TRACE;
486                                 icalcomponent_add_property(event, r_attendee);
487                                 TRACE;
488
489                                 /* Since we diddled both sets of attendees, we have to start
490                                  * the iteration over again.  This will not create an infinite
491                                  * loop because we removed the attendee from the reply.  (That's
492                                  * why we cloned the reply, and that's what we mean by "ripping
493                                  * its guts out.")
494                                  */
495                                 goto STARTOVER;
496                         }
497         
498                 }
499         }
500
501         /* Free the *clone* of the reply. */
502         icalcomponent_free(reply);
503 }
504
505
506
507
508 /*
509  * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
510  * calendar event.  The object has already been deserialized for us; all
511  * we have to do here is hunt for the event in our calendar, merge in the
512  * updated attendee status, and save it again.
513  *
514  * This function returns 0 on success, 1 if the event was not found in the
515  * user's calendar, or 2 if an internal error occurred.
516  */
517 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
518         char uid[SIZ];
519         char hold_rm[ROOMNAMELEN];
520         long msgnum_being_replaced = 0;
521         struct CtdlMessage *template = NULL;
522         struct CtdlMessage *msg;
523         struct original_event_container oec;
524         icalcomponent *original_event;
525         char *serialized_event = NULL;
526         char roomname[ROOMNAMELEN];
527         char *message_text = NULL;
528
529         /* Figure out just what event it is we're dealing with */
530         strcpy(uid, "--==<< InVaLiD uId >>==--");
531         ical_learn_uid_of_reply(uid, cal);
532         lprintf(9, "UID of event being replied to is <%s>\n", uid);
533
534         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
535
536         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
537                 getroom(&CC->quickroom, hold_rm);
538                 lprintf(3, "cannot get user calendar room\n");
539                 return(2);
540         }
541
542         /*
543          * Pound through the user's calendar looking for a message with
544          * the Citadel EUID set to the value we're looking for.  Since
545          * Citadel always sets the message EUID to the vCalendar UID of
546          * the event, this will work.
547          */
548         template = (struct CtdlMessage *)
549                 mallok(sizeof(struct CtdlMessage));
550         memset(template, 0, sizeof(struct CtdlMessage));
551         template->cm_fields['E'] = strdoop(uid);
552         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
553                 template, ical_hunt_for_event_to_update, &msgnum_being_replaced);
554         CtdlFreeMessage(template);
555         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
556
557         lprintf(9, "msgnum_being_replaced == %ld\n", msgnum_being_replaced);
558         if (msgnum_being_replaced == 0) {
559                 return(1);                      /* no calendar event found */
560         }
561
562         /* Now we know the ID of the message containing the event being updated.
563          * We don't actually have to delete it; that'll get taken care of by the
564          * server when we save another event with the same UID.  This just gives
565          * us the ability to load the event into memory so we can diddle the
566          * attendees.
567          */
568         msg = CtdlFetchMessage(msgnum_being_replaced);
569         if (msg == NULL) {
570                 return(2);                      /* internal error */
571         }
572         oec.c = NULL;
573         mime_parser(msg->cm_fields['M'],
574                 NULL,
575                 *ical_locate_original_event,    /* callback function */
576                 NULL, NULL,
577                 &oec,                           /* user data */
578                 0
579         );
580         CtdlFreeMessage(msg);
581
582         original_event = oec.c;
583         if (original_event == NULL) {
584                 lprintf(3, "ERROR: Original_component is NULL.\n");
585                 return(2);
586         }
587
588         /* Merge the attendee's updated status into the event */
589         ical_merge_attendee_reply(original_event, cal);
590
591         /* Serialize it */
592         serialized_event = strdoop(icalcomponent_as_ical_string(original_event));
593         icalcomponent_free(original_event);     /* Don't need this anymore. */
594         if (serialized_event == NULL) return(2);
595
596         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
597
598         message_text = mallok(strlen(serialized_event) + SIZ);
599         if (message_text != NULL) {
600                 sprintf(message_text,
601                         "Content-type: text/calendar\r\n\r\n%s\r\n",
602                         serialized_event
603                 );
604
605                 msg = CtdlMakeMessage(&CC->usersupp,
606                         "",                     /* No recipient */
607                         roomname,
608                         0, FMT_RFC822,
609                         "",
610                         "",             /* no subject */
611                         message_text);
612         
613                 if (msg != NULL) {
614                         CIT_ICAL->avoid_sending_invitations = 1;
615                         CtdlSubmitMsg(msg, NULL, roomname);
616                         CtdlFreeMessage(msg);
617                         CIT_ICAL->avoid_sending_invitations = 0;
618                 }
619         }
620         phree(serialized_event);
621         return(0);
622 }
623
624
625 /*
626  * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
627  * simply extracts the calendar object from the message, deserializes it, and
628  * passes it up to ical_update_my_calendar_with_reply() for processing.
629  */
630 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
631         struct CtdlMessage *msg;
632         struct ical_respond_data ird;
633         int ret;
634
635         if (
636            (strcasecmp(action, "update"))
637            && (strcasecmp(action, "ignore"))
638         ) {
639                 cprintf("%d Action must be 'update' or 'ignore'\n",
640                         ERROR + ILLEGAL_VALUE
641                 );
642                 return;
643         }
644
645         msg = CtdlFetchMessage(msgnum);
646         if (msg == NULL) {
647                 cprintf("%d Message %ld not found.\n",
648                         ERROR+ILLEGAL_VALUE,
649                         (long)msgnum
650                 );
651                 return;
652         }
653
654         memset(&ird, 0, sizeof ird);
655         strcpy(ird.desired_partnum, partnum);
656         mime_parser(msg->cm_fields['M'],
657                 NULL,
658                 *ical_locate_part,              /* callback function */
659                 NULL, NULL,
660                 (void *) &ird,                  /* user data */
661                 0
662         );
663
664         /* We're done with the incoming message, because we now have a
665          * calendar object in memory.
666          */
667         CtdlFreeMessage(msg);
668
669         /*
670          * Here is the real meat of this function.  Handle the event.
671          */
672         if (ird.cal != NULL) {
673                 /* Update the user's calendar if necessary */
674                 if (!strcasecmp(action, "update")) {
675                         ret = ical_update_my_calendar_with_reply(ird.cal);
676                         if (ret == 0) {
677                                 cprintf("%d Your calendar has been updated with this reply.\n",
678                                         CIT_OK);
679                         }
680                         else if (ret == 1) {
681                                 cprintf("%d This event does not exist in your calendar.\n",
682                                         ERROR + FILE_NOT_FOUND);
683                         }
684                         else {
685                                 cprintf("%d An internal error occurred.\n",
686                                         ERROR + INTERNAL_ERROR);
687                         }
688                 }
689                 else {
690                         cprintf("%d This reply has been ignored.\n", CIT_OK);
691                 }
692
693                 /* Now that we've processed this message, we don't need it
694                  * anymore.  So delete it.  FIXME uncomment this when ready!
695                  */
696                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
697
698                 /* Free the memory we allocated and return a response. */
699                 icalcomponent_free(ird.cal);
700                 ird.cal = NULL;
701                 return;
702         }
703         else {
704                 cprintf("%d No calendar object found\n", ERROR);
705                 return;
706         }
707
708         /* should never get here */
709 }
710
711
712 /*
713  * Search for a property in both the top level and in a VEVENT subcomponent
714  */
715 icalproperty *ical_ctdl_get_subprop(
716                 icalcomponent *cal,
717                 icalproperty_kind which_prop
718 ) {
719         icalproperty *p;
720         icalcomponent *c;
721
722         p = icalcomponent_get_first_property(cal, which_prop);
723         if (p == NULL) {
724                 c = icalcomponent_get_first_component(cal,
725                                                         ICAL_VEVENT_COMPONENT);
726                 if (c != NULL) {
727                         p = icalcomponent_get_first_property(c, which_prop);
728                 }
729         }
730         return p;
731 }
732
733
734 /*
735  * Check to see if two events overlap.  Returns nonzero if they do.
736  */
737 int ical_ctdl_is_overlap(
738                         struct icaltimetype t1start,
739                         struct icaltimetype t1end,
740                         struct icaltimetype t2start,
741                         struct icaltimetype t2end
742 ) {
743
744         if (icaltime_is_null_time(t1start)) return(0);
745         if (icaltime_is_null_time(t2start)) return(0);
746
747         /* First, check for all-day events */
748         if (t1start.is_date) {
749                 if (!icaltime_compare_date_only(t1start, t2start)) {
750                         return(1);
751                 }
752                 if (!icaltime_is_null_time(t2end)) {
753                         if (!icaltime_compare_date_only(t1start, t2end)) {
754                                 return(1);
755                         }
756                 }
757         }
758
759         if (t2start.is_date) {
760                 if (!icaltime_compare_date_only(t2start, t1start)) {
761                         return(1);
762                 }
763                 if (!icaltime_is_null_time(t1end)) {
764                         if (!icaltime_compare_date_only(t2start, t1end)) {
765                                 return(1);
766                         }
767                 }
768         }
769
770         /* Now check for overlaps using date *and* time. */
771
772         /* First, bail out if either event 1 or event 2 is missing end time. */
773         if (icaltime_is_null_time(t1end)) return(0);
774         if (icaltime_is_null_time(t2end)) return(0);
775
776         /* If event 1 ends before event 2 starts, we're in the clear. */
777         if (icaltime_compare(t1end, t2start) <= 0) return(0);
778
779         /* If event 2 ends before event 1 starts, we're also ok. */
780         if (icaltime_compare(t2end, t1start) <= 0) return(0);
781
782         /* Otherwise, they overlap. */
783         return(1);
784 }
785
786
787
788 /*
789  * Backend for ical_hunt_for_conflicts()
790  */
791 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
792         icalcomponent *cal;
793         struct CtdlMessage *msg;
794         struct ical_respond_data ird;
795         struct icaltimetype t1start, t1end, t2start, t2end;
796         icalproperty *p;
797         char conflict_event_uid[SIZ];
798         char conflict_event_summary[SIZ];
799         char compare_uid[SIZ];
800
801         cal = (icalcomponent *)data;
802         strcpy(compare_uid, "");
803         strcpy(conflict_event_uid, "");
804         strcpy(conflict_event_summary, "");
805
806         msg = CtdlFetchMessage(msgnum);
807         if (msg == NULL) return;
808         memset(&ird, 0, sizeof ird);
809         strcpy(ird.desired_partnum, "1");       /* hopefully it's always 1 */
810         mime_parser(msg->cm_fields['M'],
811                 NULL,
812                 *ical_locate_part,              /* callback function */
813                 NULL, NULL,
814                 (void *) &ird,                  /* user data */
815                 0
816         );
817         CtdlFreeMessage(msg);
818
819         if (ird.cal == NULL) return;
820
821         t1start = icaltime_null_time();
822         t1end = icaltime_null_time();
823         t2start = icaltime_null_time();
824         t1end = icaltime_null_time();
825
826         /* Now compare cal to ird.cal */
827         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTSTART_PROPERTY);
828         if (p == NULL) return;
829         if (p != NULL) t2start = icalproperty_get_dtstart(p);
830         
831         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTEND_PROPERTY);
832         if (p != NULL) t2end = icalproperty_get_dtend(p);
833
834         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
835         if (p == NULL) return;
836         if (p != NULL) t1start = icalproperty_get_dtstart(p);
837         
838         p = ical_ctdl_get_subprop(cal, ICAL_DTEND_PROPERTY);
839         if (p != NULL) t1end = icalproperty_get_dtend(p);
840         
841         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
842         if (p != NULL) {
843                 strcpy(compare_uid, icalproperty_get_comment(p));
844         }
845
846         p = ical_ctdl_get_subprop(ird.cal, ICAL_UID_PROPERTY);
847         if (p != NULL) {
848                 strcpy(conflict_event_uid, icalproperty_get_comment(p));
849         }
850
851         p = ical_ctdl_get_subprop(ird.cal, ICAL_SUMMARY_PROPERTY);
852         if (p != NULL) {
853                 strcpy(conflict_event_summary, icalproperty_get_comment(p));
854         }
855
856
857         icalcomponent_free(ird.cal);
858
859         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
860                 cprintf("%ld||%s|%s|%d|\n",
861                         msgnum,
862                         conflict_event_uid,
863                         conflict_event_summary,
864                         (       ((strlen(compare_uid)>0)
865                                 &&(!strcasecmp(compare_uid,
866                                 conflict_event_uid))) ? 1 : 0
867                         )
868                 );
869         }
870 }
871
872
873
874 /* 
875  * Phase 2 of "hunt for conflicts" operation.
876  * At this point we have a calendar object which represents the VEVENT that
877  * we're considering adding to the calendar.  Now hunt through the user's
878  * calendar room, and output zero or more existing VEVENTs which conflict
879  * with this one.
880  */
881 void ical_hunt_for_conflicts(icalcomponent *cal) {
882         char hold_rm[ROOMNAMELEN];
883
884         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
885
886         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
887                 getroom(&CC->quickroom, hold_rm);
888                 cprintf("%d You do not have a calendar.\n", ERROR);
889                 return;
890         }
891
892         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
893
894         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
895                 NULL,
896                 ical_hunt_for_conflicts_backend,
897                 (void *) cal
898         );
899
900         cprintf("000\n");
901         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
902
903 }
904
905
906
907 /*
908  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
909  */
910 void ical_conflicts(long msgnum, char *partnum) {
911         struct CtdlMessage *msg;
912         struct ical_respond_data ird;
913
914         msg = CtdlFetchMessage(msgnum);
915         if (msg == NULL) {
916                 cprintf("%d Message %ld not found.\n",
917                         ERROR+ILLEGAL_VALUE,
918                         (long)msgnum
919                 );
920                 return;
921         }
922
923         memset(&ird, 0, sizeof ird);
924         strcpy(ird.desired_partnum, partnum);
925         mime_parser(msg->cm_fields['M'],
926                 NULL,
927                 *ical_locate_part,              /* callback function */
928                 NULL, NULL,
929                 (void *) &ird,                  /* user data */
930                 0
931         );
932
933         CtdlFreeMessage(msg);
934
935         if (ird.cal != NULL) {
936                 ical_hunt_for_conflicts(ird.cal);
937                 icalcomponent_free(ird.cal);
938                 return;
939         }
940         else {
941                 cprintf("%d No calendar object found\n", ERROR);
942                 return;
943         }
944
945         /* should never get here */
946 }
947
948
949
950
951 /*
952  * All Citadel calendar commands from the client come through here.
953  */
954 void cmd_ical(char *argbuf)
955 {
956         char subcmd[SIZ];
957         long msgnum;
958         char partnum[SIZ];
959         char action[SIZ];
960
961         if (CtdlAccessCheck(ac_logged_in)) return;
962
963         extract(subcmd, argbuf, 0);
964
965         if (!strcmp(subcmd, "test")) {
966                 cprintf("%d This server supports calendaring\n", CIT_OK);
967                 return;
968         }
969
970         else if (!strcmp(subcmd, "respond")) {
971                 msgnum = extract_long(argbuf, 1);
972                 extract(partnum, argbuf, 2);
973                 extract(action, argbuf, 3);
974                 ical_respond(msgnum, partnum, action);
975         }
976
977         else if (!strcmp(subcmd, "handle_rsvp")) {
978                 msgnum = extract_long(argbuf, 1);
979                 extract(partnum, argbuf, 2);
980                 extract(action, argbuf, 3);
981                 ical_handle_rsvp(msgnum, partnum, action);
982         }
983
984         else if (!strcmp(subcmd, "conflicts")) {
985                 msgnum = extract_long(argbuf, 1);
986                 extract(partnum, argbuf, 2);
987                 ical_conflicts(msgnum, partnum);
988         }
989
990         else {
991                 cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
992                 return;
993         }
994
995         /* should never get here */
996 }
997
998
999
1000 /*
1001  * We don't know if the calendar room exists so we just create it at login
1002  */
1003 void ical_create_room(void)
1004 {
1005         struct quickroom qr;
1006         struct visit vbuf;
1007
1008         /* Create the calendar room if it doesn't already exist */
1009         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
1010
1011         /* Set expiration policy to manual; otherwise objects will be lost! */
1012         if (lgetroom(&qr, USERCALENDARROOM)) {
1013                 lprintf(3, "Couldn't get the user calendar room!\n");
1014                 return;
1015         }
1016         qr.QRep.expire_mode = EXPIRE_MANUAL;
1017         lputroom(&qr);
1018
1019         /* Set the view to a calendar view */
1020         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1021         vbuf.v_view = 3;        /* 3 = calendar */
1022         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1023
1024         /* Create the tasks list room if it doesn't already exist */
1025         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
1026
1027         /* Set expiration policy to manual; otherwise objects will be lost! */
1028         if (lgetroom(&qr, USERTASKSROOM)) {
1029                 lprintf(3, "Couldn't get the user calendar room!\n");
1030                 return;
1031         }
1032         qr.QRep.expire_mode = EXPIRE_MANUAL;
1033         lputroom(&qr);
1034
1035         /* Set the view to a task list view */
1036         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1037         vbuf.v_view = 4;        /* 4 = tasks */
1038         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1039
1040         return;
1041 }
1042
1043
1044 /*
1045  * ical_send_out_invitations() is called by ical_saving_vevent() when it
1046  * finds a VEVENT.
1047  */
1048 void ical_send_out_invitations(icalcomponent *cal) {
1049         icalcomponent *the_request = NULL;
1050         char *serialized_request = NULL;
1051         char *request_message_text = NULL;
1052         struct CtdlMessage *msg = NULL;
1053         struct recptypes *valid = NULL;
1054         char attendees_string[SIZ];
1055         int num_attendees = 0;
1056         char this_attendee[SIZ];
1057         icalproperty *attendee = NULL;
1058         char summary_string[SIZ];
1059         icalproperty *summary = NULL;
1060         icalcomponent *encaps = NULL;
1061
1062         if (cal == NULL) {
1063                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
1064                 return;
1065         }
1066
1067         /* Clone the event */
1068         the_request = icalcomponent_new_clone(cal);
1069         if (the_request == NULL) {
1070                 lprintf(3, "ERROR: cannot clone calendar object\n");
1071                 return;
1072         }
1073         ical_dezonify(the_request);
1074
1075         /* Extract the summary string -- we'll use it as the
1076          * message subject for the request
1077          */
1078         strcpy(summary_string, "Meeting request");
1079         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
1080         if (summary != NULL) {
1081                 if (icalproperty_get_summary(summary)) {
1082                         strcpy(summary_string,
1083                                 icalproperty_get_summary(summary) );
1084                 }
1085         }
1086
1087         /* Determine who the recipients of this message are (the attendees) */
1088         strcpy(attendees_string, "");
1089         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
1090                 if (icalproperty_get_attendee(attendee)) {
1091                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
1092                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
1093                                 strcpy(this_attendee, &this_attendee[7]);
1094                                 snprintf(&attendees_string[strlen(attendees_string)],
1095                                         sizeof(attendees_string) - strlen(attendees_string),
1096                                         "%s, ",
1097                                         this_attendee
1098                                 );
1099                                 ++num_attendees;
1100                         }
1101                 }
1102         }
1103
1104         lprintf(9, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
1105
1106         /* If there are no attendees, there are no invitations to send, so...
1107          * don't bother putting one together!  Punch out, Maverick!
1108          */
1109         if (num_attendees == 0) {
1110                 icalcomponent_free(the_request);
1111                 return;
1112         }
1113
1114         /* Encapsulate the VEVENT component into a complete VCALENDAR */
1115         encaps = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
1116         if (encaps == NULL) {
1117                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
1118                         __FILE__, __LINE__);
1119                 icalcomponent_free(the_request);
1120                 return;
1121         }
1122
1123         /* Set the Product ID */
1124         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1125
1126         /* Set the Version Number */
1127         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1128
1129         /* Set the method to REQUEST */
1130         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
1131
1132         /* FIXME: here we need to insert a VTIMEZONE object. */
1133
1134         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1135          * are responsible for "the_request"'s memory -- it will be freed
1136          * when we free "encaps".
1137          */
1138         icalcomponent_add_component(encaps, the_request);
1139
1140         /* Serialize it */
1141         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1142         icalcomponent_free(encaps);     /* Don't need this anymore. */
1143         if (serialized_request == NULL) return;
1144
1145         request_message_text = mallok(strlen(serialized_request) + SIZ);
1146         if (request_message_text != NULL) {
1147                 sprintf(request_message_text,
1148                         "Content-type: text/calendar\r\n\r\n%s\r\n",
1149                         serialized_request
1150                 );
1151
1152                 msg = CtdlMakeMessage(&CC->usersupp,
1153                         "",                     /* No single recipient here */
1154                         CC->quickroom.QRname, 0, FMT_RFC822,
1155                         "",
1156                         summary_string,         /* Use summary for subject */
1157                         request_message_text);
1158         
1159                 if (msg != NULL) {
1160                         valid = validate_recipients(attendees_string);
1161                         CtdlSubmitMsg(msg, valid, "");
1162                         CtdlFreeMessage(msg);
1163                 }
1164         }
1165         phree(serialized_request);
1166 }
1167
1168
1169 /*
1170  * When a calendar object is being saved, determine whether it's a VEVENT
1171  * and the user saving it is the organizer.  If so, send out invitations
1172  * to any listed attendees.
1173  *
1174  */
1175 void ical_saving_vevent(icalcomponent *cal) {
1176         icalcomponent *c;
1177         icalproperty *organizer = NULL;
1178         char organizer_string[SIZ];
1179
1180         /* Don't send out invitations if we've been asked not to. */
1181         lprintf(9, "CIT_ICAL->avoid_sending_invitations = %d\n",
1182                 CIT_ICAL->avoid_sending_invitations);
1183         if (CIT_ICAL->avoid_sending_invitations > 0) {
1184                 return;
1185         }
1186
1187         strcpy(organizer_string, "");
1188         /*
1189          * The VEVENT subcomponent is the one we're interested in.
1190          * Send out invitations if, and only if, this user is the Organizer.
1191          */
1192         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
1193                 organizer = icalcomponent_get_first_property(cal,
1194                                                 ICAL_ORGANIZER_PROPERTY);
1195                 if (organizer != NULL) {
1196                         if (icalproperty_get_organizer(organizer)) {
1197                                 strcpy(organizer_string,
1198                                         icalproperty_get_organizer(organizer));
1199                         }
1200                 }
1201                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
1202                         strcpy(organizer_string, &organizer_string[7]);
1203                         striplt(organizer_string);
1204                         /*
1205                          * If the user saving the event is listed as the
1206                          * organizer, then send out invitations.
1207                          */
1208                         if (CtdlIsMe(organizer_string)) {
1209                                 ical_send_out_invitations(cal);
1210                         }
1211                 }
1212         }
1213
1214         /* If the component has subcomponents, recurse through them. */
1215         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1216             (c != NULL);
1217             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1218                 /* Recursively process subcomponent */
1219                 ical_saving_vevent(c);
1220         }
1221
1222 }
1223
1224
1225
1226 /*
1227  * Back end for ical_obj_beforesave()
1228  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
1229  * the summary of the event (becomes message subject),
1230  * and the start time (becomes message date/time).
1231  */
1232 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1233                 char *disp, void *content, char *cbtype, size_t length,
1234                 char *encoding, void *cbuserdata)
1235 {
1236         icalcomponent *cal;
1237         icalproperty *p;
1238         struct icalmessagemod *imm;
1239
1240         imm = (struct icalmessagemod *)cbuserdata;
1241
1242         /* If this is a text/calendar object, hunt for the UID and drop it in
1243          * the "user data" pointer for the MIME parser.  When
1244          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1245          * to that string.
1246          */
1247         if (!strcasecmp(cbtype, "text/calendar")) {
1248                 cal = icalcomponent_new_from_string(content);
1249                 ical_dezonify(cal);
1250                 if (cal != NULL) {
1251                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1252                         if (p != NULL) {
1253                                 strcpy(imm->uid, icalproperty_get_comment(p));
1254                         }
1255                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
1256                         if (p != NULL) {
1257                                 strcpy(imm->subject,
1258                                                 icalproperty_get_comment(p));
1259                         }
1260                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
1261                         if (p != NULL) {
1262                                 imm->dtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
1263                         }
1264                         icalcomponent_free(cal);
1265                 }
1266         }
1267 }
1268
1269
1270
1271
1272
1273 /*
1274  * See if we need to prevent the object from being saved (we don't allow
1275  * MIME types other than text/calendar in the Calendar> room).  Also, when
1276  * saving an event to the calendar, set the message's Citadel extended message
1277  * ID to the UID of the object.  This causes our replication checker to
1278  * automatically delete any existing instances of the same object.  (Isn't
1279  * that cool?)
1280  *
1281  * We also set the message's Subject to the event summary, and the Date/time to
1282  * the event start time.
1283  */
1284 int ical_obj_beforesave(struct CtdlMessage *msg)
1285 {
1286         char roomname[ROOMNAMELEN];
1287         char *p;
1288         int a;
1289         struct icalmessagemod imm;
1290
1291         /*
1292          * Only messages with content-type text/calendar
1293          * may be saved to Calendar>.  If the message is bound for
1294          * Calendar> but doesn't have this content-type, throw an error
1295          * so that the message may not be posted.
1296          */
1297
1298         /* First determine if this is our room */
1299         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1300         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1301                 return 0;       /* It's not the Calendar room. */
1302         }
1303
1304         /* Then determine content-type of the message */
1305         
1306         /* It must be an RFC822 message! */
1307         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1308         if (msg->cm_format_type != 4)
1309                 return 1;       /* You tried to save a non-RFC822 message! */
1310         
1311         /* Find the Content-Type: header */
1312         p = msg->cm_fields['M'];
1313         a = strlen(p);
1314         while (--a > 0) {
1315                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1316                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1317                                 memset(&imm, 0, sizeof(struct icalmessagemod));
1318                                 mime_parser(msg->cm_fields['M'],
1319                                         NULL,
1320                                         *ical_ctdl_set_extended_msgid,
1321                                         NULL, NULL,
1322                                         (void *)&imm,
1323                                         0
1324                                 );
1325                                 if (strlen(imm.uid) > 0) {
1326                                         if (msg->cm_fields['E'] != NULL) {
1327                                                 phree(msg->cm_fields['E']);
1328                                         }
1329                                         msg->cm_fields['E'] = strdoop(imm.uid);
1330                                 }
1331                                 if (strlen(imm.subject) > 0) {
1332                                         if (msg->cm_fields['U'] != NULL) {
1333                                                 phree(msg->cm_fields['U']);
1334                                         }
1335                                         msg->cm_fields['U'] = strdoop(imm.subject);
1336                                 }
1337                                 if (imm.dtstart > 0) {
1338                                         if (msg->cm_fields['T'] != NULL) {
1339                                                 phree(msg->cm_fields['T']);
1340                                         }
1341                                         msg->cm_fields['T'] = strdoop("000000000000000000");
1342                                         sprintf(msg->cm_fields['T'], "%ld", imm.dtstart);
1343                                 }
1344                                 return 0;
1345                         }
1346                         else {
1347                                 return 1;
1348                         }
1349                 }
1350                 p++;
1351         }
1352         
1353         /* Oops!  No Content-Type in this message!  How'd that happen? */
1354         lprintf(7, "RFC822 message with no Content-Type header!\n");
1355         return 1;
1356 }
1357
1358
1359 /*
1360  * Things we need to do after saving a calendar event.
1361  */
1362 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1363                 char *disp, void *content, char *cbtype, size_t length,
1364                 char *encoding, void *cbuserdata)
1365 {
1366         icalcomponent *cal;
1367
1368         /* If this is a text/calendar object, hunt for the UID and drop it in
1369          * the "user data" pointer for the MIME parser.  When
1370          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1371          * to that string.
1372          */
1373         if (!strcasecmp(cbtype, "text/calendar")) {
1374                 cal = icalcomponent_new_from_string(content);
1375                 if (cal != NULL) {
1376                         ical_dezonify(cal);
1377                         ical_saving_vevent(cal);
1378                         icalcomponent_free(cal);
1379                 }
1380         }
1381 }
1382
1383
1384 /* 
1385  * Things we need to do after saving a calendar event.
1386  */
1387 int ical_obj_aftersave(struct CtdlMessage *msg)
1388 {
1389         char roomname[ROOMNAMELEN];
1390         char *p;
1391         int a;
1392
1393         /*
1394          * If this isn't the Calendar> room, no further action is necessary.
1395          */
1396
1397         /* First determine if this is our room */
1398         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1399         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1400                 return 0;       /* It's not the Calendar room. */
1401         }
1402
1403         /* Then determine content-type of the message */
1404         
1405         /* It must be an RFC822 message! */
1406         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1407         if (msg->cm_format_type != 4) return(1);
1408         
1409         /* Find the Content-Type: header */
1410         p = msg->cm_fields['M'];
1411         a = strlen(p);
1412         while (--a > 0) {
1413                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1414                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1415                                 mime_parser(msg->cm_fields['M'],
1416                                         NULL,
1417                                         *ical_obj_aftersave_backend,
1418                                         NULL, NULL,
1419                                         NULL,
1420                                         0
1421                                 );
1422                                 return 0;
1423                         }
1424                         else {
1425                                 return 1;
1426                         }
1427                 }
1428                 p++;
1429         }
1430         
1431         /* Oops!  No Content-Type in this message!  How'd that happen? */
1432         lprintf(7, "RFC822 message with no Content-Type header!\n");
1433         return 1;
1434 }
1435
1436
1437 void ical_session_startup(void) {
1438         SYM_CIT_ICAL = CtdlGetDynamicSymbol();
1439         CtdlAllocUserData(SYM_CIT_ICAL, sizeof(struct cit_ical));
1440         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
1441         
1442 }
1443
1444
1445 #endif  /* HAVE_ICAL_H */
1446
1447 /*
1448  * Register this module with the Citadel server.
1449  */
1450 char *Dynamic_Module_Init(void)
1451 {
1452 #ifdef HAVE_ICAL_H
1453         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1454         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1455         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1456         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1457         CtdlRegisterSessionHook(ical_session_startup, EVT_START);
1458 #endif
1459         return "$Id$";
1460 }