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