]> code.citadel.org Git - citadel.git/blob - citadel/serv_calendar.c
* Began framing up a command to view other users' free/busy 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 "serv_extensions.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 CITADEL_WITH_CALENDAR_SERVICE
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  * Grab another user's free/busy times
951  */
952 void ical_freebusy(char *who) {
953         struct usersupp usbuf;
954         char calendar_room_name[ROOMNAMELEN];
955         char hold_rm[ROOMNAMELEN];
956
957         if (getuser(&usbuf, who) != 0) {
958                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
959                 return;
960         }
961
962         MailboxName(calendar_room_name, sizeof calendar_room_name,
963                 &usbuf, USERCALENDARROOM);
964
965         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
966
967         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
968                 cprintf("%d Cannot open calendar\n", ERROR+ROOM_NOT_FOUND);
969                 getroom(&CC->quickroom, hold_rm);
970                 return;
971         }
972
973 /*
974         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
975                 template, the_FIXME_function, NULL);
976  */
977
978         /* Go back to the room from which we came... */
979         getroom(&CC->quickroom, hold_rm);
980
981         cprintf("%d not implemented yet\n", ERROR);
982 }
983
984
985
986
987 /*
988  * All Citadel calendar commands from the client come through here.
989  */
990 void cmd_ical(char *argbuf)
991 {
992         char subcmd[SIZ];
993         long msgnum;
994         char partnum[SIZ];
995         char action[SIZ];
996         char who[SIZ];
997
998         if (CtdlAccessCheck(ac_logged_in)) return;
999
1000         extract(subcmd, argbuf, 0);
1001
1002         if (!strcmp(subcmd, "test")) {
1003                 cprintf("%d This server supports calendaring\n", CIT_OK);
1004                 return;
1005         }
1006
1007         else if (!strcmp(subcmd, "respond")) {
1008                 msgnum = extract_long(argbuf, 1);
1009                 extract(partnum, argbuf, 2);
1010                 extract(action, argbuf, 3);
1011                 ical_respond(msgnum, partnum, action);
1012         }
1013
1014         else if (!strcmp(subcmd, "handle_rsvp")) {
1015                 msgnum = extract_long(argbuf, 1);
1016                 extract(partnum, argbuf, 2);
1017                 extract(action, argbuf, 3);
1018                 ical_handle_rsvp(msgnum, partnum, action);
1019         }
1020
1021         else if (!strcmp(subcmd, "conflicts")) {
1022                 msgnum = extract_long(argbuf, 1);
1023                 extract(partnum, argbuf, 2);
1024                 ical_conflicts(msgnum, partnum);
1025         }
1026
1027         else if (!strcmp(subcmd, "freebusy")) {
1028                 extract(who, argbuf, 1);
1029                 ical_freebusy(who);
1030         }
1031
1032         else {
1033                 cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
1034                 return;
1035         }
1036
1037         /* should never get here */
1038 }
1039
1040
1041
1042 /*
1043  * We don't know if the calendar room exists so we just create it at login
1044  */
1045 void ical_create_room(void)
1046 {
1047         struct quickroom qr;
1048         struct visit vbuf;
1049
1050         /* Create the calendar room if it doesn't already exist */
1051         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
1052
1053         /* Set expiration policy to manual; otherwise objects will be lost! */
1054         if (lgetroom(&qr, USERCALENDARROOM)) {
1055                 lprintf(3, "Couldn't get the user calendar room!\n");
1056                 return;
1057         }
1058         qr.QRep.expire_mode = EXPIRE_MANUAL;
1059         qr.QRdefaultview = 3;   /* 3 = calendar view */
1060         lputroom(&qr);
1061
1062         /* Set the view to a calendar view */
1063         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1064         vbuf.v_view = 3;        /* 3 = calendar */
1065         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1066
1067         /* Create the tasks list room if it doesn't already exist */
1068         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
1069
1070         /* Set expiration policy to manual; otherwise objects will be lost! */
1071         if (lgetroom(&qr, USERTASKSROOM)) {
1072                 lprintf(3, "Couldn't get the user calendar room!\n");
1073                 return;
1074         }
1075         qr.QRep.expire_mode = EXPIRE_MANUAL;
1076         qr.QRdefaultview = 4;   /* 4 = tasks view */
1077         lputroom(&qr);
1078
1079         /* Set the view to a task list view */
1080         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1081         vbuf.v_view = 4;        /* 4 = tasks */
1082         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1083
1084         return;
1085 }
1086
1087
1088 /*
1089  * ical_send_out_invitations() is called by ical_saving_vevent() when it
1090  * finds a VEVENT.
1091  */
1092 void ical_send_out_invitations(icalcomponent *cal) {
1093         icalcomponent *the_request = NULL;
1094         char *serialized_request = NULL;
1095         char *request_message_text = NULL;
1096         struct CtdlMessage *msg = NULL;
1097         struct recptypes *valid = NULL;
1098         char attendees_string[SIZ];
1099         int num_attendees = 0;
1100         char this_attendee[SIZ];
1101         icalproperty *attendee = NULL;
1102         char summary_string[SIZ];
1103         icalproperty *summary = NULL;
1104         icalcomponent *encaps = NULL;
1105
1106         if (cal == NULL) {
1107                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
1108                 return;
1109         }
1110
1111         /* Clone the event */
1112         the_request = icalcomponent_new_clone(cal);
1113         if (the_request == NULL) {
1114                 lprintf(3, "ERROR: cannot clone calendar object\n");
1115                 return;
1116         }
1117
1118         /* Extract the summary string -- we'll use it as the
1119          * message subject for the request
1120          */
1121         strcpy(summary_string, "Meeting request");
1122         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
1123         if (summary != NULL) {
1124                 if (icalproperty_get_summary(summary)) {
1125                         strcpy(summary_string,
1126                                 icalproperty_get_summary(summary) );
1127                 }
1128         }
1129
1130         /* Determine who the recipients of this message are (the attendees) */
1131         strcpy(attendees_string, "");
1132         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
1133                 if (icalproperty_get_attendee(attendee)) {
1134                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
1135                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
1136                                 strcpy(this_attendee, &this_attendee[7]);
1137                                 snprintf(&attendees_string[strlen(attendees_string)],
1138                                         sizeof(attendees_string) - strlen(attendees_string),
1139                                         "%s, ",
1140                                         this_attendee
1141                                 );
1142                                 ++num_attendees;
1143                         }
1144                 }
1145         }
1146
1147         lprintf(9, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
1148
1149         /* If there are no attendees, there are no invitations to send, so...
1150          * don't bother putting one together!  Punch out, Maverick!
1151          */
1152         if (num_attendees == 0) {
1153                 icalcomponent_free(the_request);
1154                 return;
1155         }
1156
1157         /* Encapsulate the VEVENT component into a complete VCALENDAR */
1158         encaps = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
1159         if (encaps == NULL) {
1160                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
1161                         __FILE__, __LINE__);
1162                 icalcomponent_free(the_request);
1163                 return;
1164         }
1165
1166         /* Set the Product ID */
1167         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1168
1169         /* Set the Version Number */
1170         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1171
1172         /* Set the method to REQUEST */
1173         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
1174
1175         /* Now make sure all of the DTSTART and DTEND properties are UTC. */
1176         ical_dezonify(the_request);
1177
1178         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1179          * are responsible for "the_request"'s memory -- it will be freed
1180          * when we free "encaps".
1181          */
1182         icalcomponent_add_component(encaps, the_request);
1183
1184         /* Serialize it */
1185         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1186         icalcomponent_free(encaps);     /* Don't need this anymore. */
1187         if (serialized_request == NULL) return;
1188
1189         request_message_text = mallok(strlen(serialized_request) + SIZ);
1190         if (request_message_text != NULL) {
1191                 sprintf(request_message_text,
1192                         "Content-type: text/calendar\r\n\r\n%s\r\n",
1193                         serialized_request
1194                 );
1195
1196                 msg = CtdlMakeMessage(&CC->usersupp,
1197                         "",                     /* No single recipient here */
1198                         CC->quickroom.QRname, 0, FMT_RFC822,
1199                         "",
1200                         summary_string,         /* Use summary for subject */
1201                         request_message_text);
1202         
1203                 if (msg != NULL) {
1204                         valid = validate_recipients(attendees_string);
1205                         CtdlSubmitMsg(msg, valid, "");
1206                         CtdlFreeMessage(msg);
1207                 }
1208         }
1209         phree(serialized_request);
1210 }
1211
1212
1213 /*
1214  * When a calendar object is being saved, determine whether it's a VEVENT
1215  * and the user saving it is the organizer.  If so, send out invitations
1216  * to any listed attendees.
1217  *
1218  */
1219 void ical_saving_vevent(icalcomponent *cal) {
1220         icalcomponent *c;
1221         icalproperty *organizer = NULL;
1222         char organizer_string[SIZ];
1223
1224         /* Don't send out invitations if we've been asked not to. */
1225         lprintf(9, "CIT_ICAL->avoid_sending_invitations = %d\n",
1226                 CIT_ICAL->avoid_sending_invitations);
1227         if (CIT_ICAL->avoid_sending_invitations > 0) {
1228                 return;
1229         }
1230
1231         strcpy(organizer_string, "");
1232         /*
1233          * The VEVENT subcomponent is the one we're interested in.
1234          * Send out invitations if, and only if, this user is the Organizer.
1235          */
1236         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
1237                 organizer = icalcomponent_get_first_property(cal,
1238                                                 ICAL_ORGANIZER_PROPERTY);
1239                 if (organizer != NULL) {
1240                         if (icalproperty_get_organizer(organizer)) {
1241                                 strcpy(organizer_string,
1242                                         icalproperty_get_organizer(organizer));
1243                         }
1244                 }
1245                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
1246                         strcpy(organizer_string, &organizer_string[7]);
1247                         striplt(organizer_string);
1248                         /*
1249                          * If the user saving the event is listed as the
1250                          * organizer, then send out invitations.
1251                          */
1252                         if (CtdlIsMe(organizer_string)) {
1253                                 ical_send_out_invitations(cal);
1254                         }
1255                 }
1256         }
1257
1258         /* If the component has subcomponents, recurse through them. */
1259         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1260             (c != NULL);
1261             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1262                 /* Recursively process subcomponent */
1263                 ical_saving_vevent(c);
1264         }
1265
1266 }
1267
1268
1269
1270 /*
1271  * Back end for ical_obj_beforesave()
1272  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
1273  * the summary of the event (becomes message subject),
1274  * and the start time (becomes message date/time).
1275  */
1276 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1277                 char *disp, void *content, char *cbtype, size_t length,
1278                 char *encoding, void *cbuserdata)
1279 {
1280         icalcomponent *cal;
1281         icalproperty *p;
1282         struct icalmessagemod *imm;
1283
1284         imm = (struct icalmessagemod *)cbuserdata;
1285
1286         /* If this is a text/calendar object, hunt for the UID and drop it in
1287          * the "user data" pointer for the MIME parser.  When
1288          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1289          * to that string.
1290          */
1291         if (!strcasecmp(cbtype, "text/calendar")) {
1292                 cal = icalcomponent_new_from_string(content);
1293                 if (cal != NULL) {
1294                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1295                         if (p != NULL) {
1296                                 strcpy(imm->uid, icalproperty_get_comment(p));
1297                         }
1298                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
1299                         if (p != NULL) {
1300                                 strcpy(imm->subject,
1301                                                 icalproperty_get_comment(p));
1302                         }
1303                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
1304                         if (p != NULL) {
1305                                 imm->dtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
1306                         }
1307                         icalcomponent_free(cal);
1308                 }
1309         }
1310 }
1311
1312
1313
1314
1315
1316 /*
1317  * See if we need to prevent the object from being saved (we don't allow
1318  * MIME types other than text/calendar in the Calendar> room).  Also, when
1319  * saving an event to the calendar, set the message's Citadel extended message
1320  * ID to the UID of the object.  This causes our replication checker to
1321  * automatically delete any existing instances of the same object.  (Isn't
1322  * that cool?)
1323  *
1324  * We also set the message's Subject to the event summary, and the Date/time to
1325  * the event start time.
1326  */
1327 int ical_obj_beforesave(struct CtdlMessage *msg)
1328 {
1329         char roomname[ROOMNAMELEN];
1330         char *p;
1331         int a;
1332         struct icalmessagemod imm;
1333
1334         /*
1335          * Only messages with content-type text/calendar
1336          * may be saved to Calendar>.  If the message is bound for
1337          * Calendar> but doesn't have this content-type, throw an error
1338          * so that the message may not be posted.
1339          */
1340
1341         /* First determine if this is our room */
1342         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1343         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1344                 return 0;       /* It's not the Calendar room. */
1345         }
1346
1347         /* Then determine content-type of the message */
1348         
1349         /* It must be an RFC822 message! */
1350         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1351         if (msg->cm_format_type != 4)
1352                 return 1;       /* You tried to save a non-RFC822 message! */
1353         
1354         /* Find the Content-Type: header */
1355         p = msg->cm_fields['M'];
1356         a = strlen(p);
1357         while (--a > 0) {
1358                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1359                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1360                                 memset(&imm, 0, sizeof(struct icalmessagemod));
1361                                 mime_parser(msg->cm_fields['M'],
1362                                         NULL,
1363                                         *ical_ctdl_set_extended_msgid,
1364                                         NULL, NULL,
1365                                         (void *)&imm,
1366                                         0
1367                                 );
1368                                 if (strlen(imm.uid) > 0) {
1369                                         if (msg->cm_fields['E'] != NULL) {
1370                                                 phree(msg->cm_fields['E']);
1371                                         }
1372                                         msg->cm_fields['E'] = strdoop(imm.uid);
1373                                 }
1374                                 if (strlen(imm.subject) > 0) {
1375                                         if (msg->cm_fields['U'] != NULL) {
1376                                                 phree(msg->cm_fields['U']);
1377                                         }
1378                                         msg->cm_fields['U'] = strdoop(imm.subject);
1379                                 }
1380                                 if (imm.dtstart > 0) {
1381                                         if (msg->cm_fields['T'] != NULL) {
1382                                                 phree(msg->cm_fields['T']);
1383                                         }
1384                                         msg->cm_fields['T'] = strdoop("000000000000000000");
1385                                         sprintf(msg->cm_fields['T'], "%ld", imm.dtstart);
1386                                 }
1387                                 return 0;
1388                         }
1389                         else {
1390                                 return 1;
1391                         }
1392                 }
1393                 p++;
1394         }
1395         
1396         /* Oops!  No Content-Type in this message!  How'd that happen? */
1397         lprintf(7, "RFC822 message with no Content-Type header!\n");
1398         return 1;
1399 }
1400
1401
1402 /*
1403  * Things we need to do after saving a calendar event.
1404  */
1405 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1406                 char *disp, void *content, char *cbtype, size_t length,
1407                 char *encoding, void *cbuserdata)
1408 {
1409         icalcomponent *cal;
1410
1411         /* If this is a text/calendar object, hunt for the UID and drop it in
1412          * the "user data" pointer for the MIME parser.  When
1413          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1414          * to that string.
1415          */
1416         if (!strcasecmp(cbtype, "text/calendar")) {
1417                 cal = icalcomponent_new_from_string(content);
1418                 if (cal != NULL) {
1419                         ical_saving_vevent(cal);
1420                         icalcomponent_free(cal);
1421                 }
1422         }
1423 }
1424
1425
1426 /* 
1427  * Things we need to do after saving a calendar event.
1428  */
1429 int ical_obj_aftersave(struct CtdlMessage *msg)
1430 {
1431         char roomname[ROOMNAMELEN];
1432         char *p;
1433         int a;
1434
1435         /*
1436          * If this isn't the Calendar> room, no further action is necessary.
1437          */
1438
1439         /* First determine if this is our room */
1440         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1441         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1442                 return 0;       /* It's not the Calendar room. */
1443         }
1444
1445         /* Then determine content-type of the message */
1446         
1447         /* It must be an RFC822 message! */
1448         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1449         if (msg->cm_format_type != 4) return(1);
1450         
1451         /* Find the Content-Type: header */
1452         p = msg->cm_fields['M'];
1453         a = strlen(p);
1454         while (--a > 0) {
1455                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1456                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1457                                 mime_parser(msg->cm_fields['M'],
1458                                         NULL,
1459                                         *ical_obj_aftersave_backend,
1460                                         NULL, NULL,
1461                                         NULL,
1462                                         0
1463                                 );
1464                                 return 0;
1465                         }
1466                         else {
1467                                 return 1;
1468                         }
1469                 }
1470                 p++;
1471         }
1472         
1473         /* Oops!  No Content-Type in this message!  How'd that happen? */
1474         lprintf(7, "RFC822 message with no Content-Type header!\n");
1475         return 1;
1476 }
1477
1478
1479 void ical_session_startup(void) {
1480         CtdlAllocUserData(SYM_CIT_ICAL, sizeof(struct cit_ical));
1481         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
1482 }
1483
1484
1485 #endif  /* CITADEL_WITH_CALENDAR_SERVICE */
1486
1487 /*
1488  * Register this module with the Citadel server.
1489  */
1490 char *serv_calendar_init(void)
1491 {
1492 #ifdef CITADEL_WITH_CALENDAR_SERVICE
1493         SYM_CIT_ICAL = CtdlGetDynamicSymbol();
1494         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1495         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1496         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1497         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1498         CtdlRegisterSessionHook(ical_session_startup, EVT_START);
1499 #endif
1500         return "$Id$";
1501 }