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