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