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