* More license declarations
[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  * Copyright (c) 1987-2009 by the citadel.org team
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 3 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, write to the Free Software
23  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25
26 #define PRODID "-//Citadel//NONSGML Citadel Calendar//EN"
27
28 #include "sysdep.h"
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <string.h>
35 #ifdef HAVE_STRINGS_H
36 #include <strings.h>
37 #endif
38 #include <libical/ical.h>
39 #include <libcitadel.h>
40 #include "citadel.h"
41 #include "server.h"
42 #include "citserver.h"
43 #include "support.h"
44 #include "config.h"
45 #include "user_ops.h"
46 #include "room_ops.h"
47 #include "msgbase.h"
48 #include "internet_addressing.h"
49 #include "serv_calendar.h"
50 #include "euidindex.h"
51 #include "ctdl_module.h"
52 #include "ical_dezonify.h"
53
54
55
56 struct ical_respond_data {
57         char desired_partnum[SIZ];
58         icalcomponent *cal;
59 };
60
61
62 /*
63  * Utility function to create a new VCALENDAR component with some of the
64  * required fields already set the way we like them.
65  */
66 icalcomponent *icalcomponent_new_citadel_vcalendar(void) {
67         icalcomponent *encaps;
68
69         encaps = icalcomponent_new_vcalendar();
70         if (encaps == NULL) {
71                 CtdlLogPrintf(CTDL_CRIT, "ERROR: could not allocate component!\n");
72                 return NULL;
73         }
74
75         /* Set the Product ID */
76         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
77
78         /* Set the Version Number */
79         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
80
81         return(encaps);
82 }
83
84
85 /*
86  * Utility function to encapsulate a subcomponent into a full VCALENDAR
87  */
88 icalcomponent *ical_encapsulate_subcomponent(icalcomponent *subcomp) {
89         icalcomponent *encaps;
90
91         /* If we're already looking at a full VCALENDAR component,
92          * don't bother ... just return itself.
93          */
94         if (icalcomponent_isa(subcomp) == ICAL_VCALENDAR_COMPONENT) {
95                 return subcomp;
96         }
97
98         /* Encapsulate the VEVENT component into a complete VCALENDAR */
99         encaps = icalcomponent_new_citadel_vcalendar();
100         if (encaps == NULL) return NULL;
101
102         /* Encapsulate the subcomponent inside */
103         icalcomponent_add_component(encaps, subcomp);
104
105         /* Return the object we just created. */
106         return(encaps);
107 }
108
109
110
111
112 /*
113  * Write a calendar object into the specified user's calendar room.
114  * If the supplied user is NULL, this function writes the calendar object
115  * to the currently selected room.
116  */
117 void ical_write_to_cal(struct ctdluser *u, icalcomponent *cal) {
118         char *ser = NULL;
119         icalcomponent *encaps = NULL;
120         struct CtdlMessage *msg = NULL;
121         icalcomponent *tmp=NULL;
122
123         if (cal == NULL) return;
124
125         /* If the supplied object is a subcomponent, encapsulate it in
126          * a full VCALENDAR component, and save that instead.
127          */
128         if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
129                 tmp = icalcomponent_new_clone(cal);
130                 encaps = ical_encapsulate_subcomponent(tmp);
131                 ical_write_to_cal(u, encaps);
132                 icalcomponent_free(tmp);
133                 icalcomponent_free(encaps);
134                 return;
135         }
136
137         ser = icalcomponent_as_ical_string_r(cal);
138         if (ser == NULL) return;
139
140         /* If the caller supplied a user, write to that user's default calendar room */
141         if (u) {
142                 /* This handy API function does all the work for us. */
143                 CtdlWriteObject(USERCALENDARROOM,       /* which room */
144                         "text/calendar",        /* MIME type */
145                         ser,                    /* data */
146                         strlen(ser)+1,          /* length */
147                         u,                      /* which user */
148                         0,                      /* not binary */
149                         0,                      /* don't delete others of this type */
150                         0                       /* no flags */
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, "", QP_EADDR);
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  * Send a reply to a meeting invitation.
181  *
182  * 'request' is the invitation to reply to.
183  * 'action' is the string "accept" or "decline" or "tentative".
184  *
185  */
186 void ical_send_a_reply(icalcomponent *request, char *action) {
187         icalcomponent *the_reply = NULL;
188         icalcomponent *vevent = NULL;
189         icalproperty *attendee = NULL;
190         char attendee_string[SIZ];
191         icalproperty *organizer = NULL;
192         char organizer_string[SIZ];
193         icalproperty *summary = NULL;
194         char summary_string[SIZ];
195         icalproperty *me_attend = NULL;
196         struct recptypes *recp = NULL;
197         icalparameter *partstat = NULL;
198         char *serialized_reply = NULL;
199         char *reply_message_text = NULL;
200         struct CtdlMessage *msg = NULL;
201         struct recptypes *valid = NULL;
202
203         strcpy(organizer_string, "");
204         strcpy(summary_string, "Calendar item");
205
206         if (request == NULL) {
207                 CtdlLogPrintf(CTDL_ERR, "ERROR: trying to reply to NULL event?\n");
208                 return;
209         }
210
211         the_reply = icalcomponent_new_clone(request);
212         if (the_reply == NULL) {
213                 CtdlLogPrintf(CTDL_ERR, "ERROR: cannot clone request\n");
214                 return;
215         }
216
217         /* Change the method from REQUEST to REPLY */
218         icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
219
220         vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
221         if (vevent != NULL) {
222                 /* Hunt for attendees, removing ones that aren't us.
223                  * (Actually, remove them all, cloning our own one so we can
224                  * re-insert it later)
225                  */
226                 while (attendee = icalcomponent_get_first_property(vevent,
227                     ICAL_ATTENDEE_PROPERTY), (attendee != NULL)
228                 ) {
229                         if (icalproperty_get_attendee(attendee)) {
230                                 strcpy(attendee_string,
231                                         icalproperty_get_attendee(attendee) );
232                                 if (!strncasecmp(attendee_string, "MAILTO:", 7)) {
233                                         strcpy(attendee_string, &attendee_string[7]);
234                                         striplt(attendee_string);
235                                         recp = validate_recipients(attendee_string, NULL, 0);
236                                         if (recp != NULL) {
237                                                 if (!strcasecmp(recp->recp_local, CC->user.fullname)) {
238                                                         if (me_attend) icalproperty_free(me_attend);
239                                                         me_attend = icalproperty_new_clone(attendee);
240                                                 }
241                                                 free_recipients(recp);
242                                         }
243                                 }
244                         }
245                         /* Remove it... */
246                         icalcomponent_remove_property(vevent, attendee);
247                         icalproperty_free(attendee);
248                 }
249
250                 /* We found our own address in the attendee list. */
251                 if (me_attend) {
252                         /* Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE */
253                         icalproperty_remove_parameter(me_attend, ICAL_PARTSTAT_PARAMETER);
254
255                         if (!strcasecmp(action, "accept")) {
256                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
257                         }
258                         else if (!strcasecmp(action, "decline")) {
259                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
260                         }
261                         else if (!strcasecmp(action, "tentative")) {
262                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
263                         }
264
265                         if (partstat) icalproperty_add_parameter(me_attend, partstat);
266
267                         /* Now insert it back into the vevent. */
268                         icalcomponent_add_property(vevent, me_attend);
269                 }
270
271                 /* Figure out who to send this thing to */
272                 organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
273                 if (organizer != NULL) {
274                         if (icalproperty_get_organizer(organizer)) {
275                                 strcpy(organizer_string,
276                                         icalproperty_get_organizer(organizer) );
277                         }
278                 }
279                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
280                         strcpy(organizer_string, &organizer_string[7]);
281                         striplt(organizer_string);
282                 } else {
283                         strcpy(organizer_string, "");
284                 }
285
286                 /* Extract the summary string -- we'll use it as the
287                  * message subject for the reply
288                  */
289                 summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
290                 if (summary != NULL) {
291                         if (icalproperty_get_summary(summary)) {
292                                 strcpy(summary_string,
293                                         icalproperty_get_summary(summary) );
294                         }
295                 }
296         }
297
298         /* Now generate the reply message and send it out. */
299         serialized_reply = icalcomponent_as_ical_string_r(the_reply);
300         icalcomponent_free(the_reply);  /* don't need this anymore */
301         if (serialized_reply == NULL) return;
302
303         reply_message_text = malloc(strlen(serialized_reply) + SIZ);
304         if (reply_message_text != NULL) {
305                 sprintf(reply_message_text,
306                         "Content-type: text/calendar; charset=\"utf-8\"\r\n\r\n%s\r\n",
307                         serialized_reply
308                 );
309
310                 msg = CtdlMakeMessage(&CC->user,
311                         organizer_string,       /* to */
312                         "",                     /* cc */
313                         CC->room.QRname, 0, FMT_RFC822,
314                         "",
315                         "",
316                         summary_string,         /* Use summary for subject */
317                         NULL,
318                         reply_message_text,
319                         NULL);
320         
321                 if (msg != NULL) {
322                         valid = validate_recipients(organizer_string, NULL, 0);
323                         CtdlSubmitMsg(msg, valid, "", QP_EADDR);
324                         CtdlFreeMessage(msg);
325                         free_recipients(valid);
326                 }
327         }
328         free(serialized_reply);
329 }
330
331
332
333 /*
334  * Callback function for mime parser that hunts for calendar content types
335  * and turns them into calendar objects.  If something is found, it is placed
336  * in ird->cal, and the caller now owns that memory and is responsible for freeing it.
337  */
338 void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
339                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
340                 char *cbid, void *cbuserdata) {
341
342         struct ical_respond_data *ird = NULL;
343
344         ird = (struct ical_respond_data *) cbuserdata;
345
346         /* desired_partnum can be set to "_HUNT_" to have it just look for
347          * the first part with a content type of text/calendar.  Otherwise
348          * we have to only process the right one.
349          */
350         if (strcasecmp(ird->desired_partnum, "_HUNT_")) {
351                 if (strcasecmp(partnum, ird->desired_partnum)) {
352                         return;
353                 }
354         }
355
356         if (  (strcasecmp(cbtype, "text/calendar"))
357            && (strcasecmp(cbtype, "application/ics")) ) {
358                 return;
359         }
360
361         if (ird->cal != NULL) {
362                 icalcomponent_free(ird->cal);
363                 ird->cal = NULL;
364         }
365
366         ird->cal = icalcomponent_new_from_string(content);
367 }
368
369
370 /*
371  * Respond to a meeting request.
372  */
373 void ical_respond(long msgnum, char *partnum, char *action) {
374         struct CtdlMessage *msg = NULL;
375         struct ical_respond_data ird;
376
377         if (
378            (strcasecmp(action, "accept"))
379            && (strcasecmp(action, "decline"))
380         ) {
381                 cprintf("%d Action must be 'accept' or 'decline'\n",
382                         ERROR + ILLEGAL_VALUE
383                 );
384                 return;
385         }
386
387         msg = CtdlFetchMessage(msgnum, 1);
388         if (msg == NULL) {
389                 cprintf("%d Message %ld not found.\n",
390                         ERROR + ILLEGAL_VALUE,
391                         (long)msgnum
392                 );
393                 return;
394         }
395
396         memset(&ird, 0, sizeof ird);
397         strcpy(ird.desired_partnum, partnum);
398         mime_parser(msg->cm_fields['M'],
399                 NULL,
400                 *ical_locate_part,              /* callback function */
401                 NULL, NULL,
402                 (void *) &ird,                  /* user data */
403                 0
404         );
405
406         /* We're done with the incoming message, because we now have a
407          * calendar object in memory.
408          */
409         CtdlFreeMessage(msg);
410
411         /*
412          * Here is the real meat of this function.  Handle the event.
413          */
414         if (ird.cal != NULL) {
415                 /* Save this in the user's calendar if necessary */
416                 if (!strcasecmp(action, "accept")) {
417                         ical_write_to_cal(&CC->user, ird.cal);
418                 }
419
420                 /* Send a reply if necessary */
421                 if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
422                         ical_send_a_reply(ird.cal, action);
423                 }
424
425                 /* We used to delete the invitation after handling it.
426                  * We don't do that anymore, but here is the code that handled it:
427                  * CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
428                  */
429
430                 /* Free the memory we allocated and return a response. */
431                 icalcomponent_free(ird.cal);
432                 ird.cal = NULL;
433                 cprintf("%d ok\n", CIT_OK);
434                 return;
435         }
436         else {
437                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
438                 return;
439         }
440
441         /* should never get here */
442 }
443
444
445 /*
446  * Figure out the UID of the calendar event being referred to in a
447  * REPLY object.  This function is recursive.
448  */
449 void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
450         icalcomponent *subcomponent;
451         icalproperty *p;
452
453         /* If this object is a REPLY, then extract the UID. */
454         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
455                 p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
456                 if (p != NULL) {
457                         strcpy(uidbuf, icalproperty_get_comment(p));
458                 }
459         }
460
461         /* Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
462          * UID of the reply; we want the UID of the invitation being replied to.
463          */
464         for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
465             subcomponent != NULL;
466             subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT) ) {
467                 ical_learn_uid_of_reply(uidbuf, subcomponent);
468         }
469 }
470
471
472 /*
473  * ical_update_my_calendar_with_reply() refers to this callback function; when we
474  * locate the message containing the calendar event we're replying to, this function
475  * gets called.  It basically just sticks the message number in a supplied buffer.
476  */
477 void ical_hunt_for_event_to_update(long msgnum, void *data) {
478         long *msgnumptr;
479
480         msgnumptr = (long *) data;
481         *msgnumptr = msgnum;
482 }
483
484
485 struct original_event_container {
486         icalcomponent *c;
487 };
488
489 /*
490  * Callback function for mime parser that hunts for calendar content types
491  * and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
492  * to fetch the object being updated)
493  */
494 void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
495                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
496                 char *cbid, void *cbuserdata) {
497
498         struct original_event_container *oec = NULL;
499
500         if (  (strcasecmp(cbtype, "text/calendar"))
501            && (strcasecmp(cbtype, "application/ics")) ) {
502                 return;
503         }
504         oec = (struct original_event_container *) cbuserdata;
505         if (oec->c != NULL) {
506                 icalcomponent_free(oec->c);
507         }
508         oec->c = icalcomponent_new_from_string(content);
509 }
510
511
512 /*
513  * Merge updated attendee information from a REPLY into an existing event.
514  */
515 void ical_merge_attendee_reply(icalcomponent *event, icalcomponent *reply) {
516         icalcomponent *c;
517         icalproperty *e_attendee, *r_attendee;
518
519         /* First things first.  If we're not looking at a VEVENT component,
520          * recurse through subcomponents until we find one.
521          */
522         if (icalcomponent_isa(event) != ICAL_VEVENT_COMPONENT) {
523                 for (c = icalcomponent_get_first_component(event, ICAL_VEVENT_COMPONENT);
524                     c != NULL;
525                     c = icalcomponent_get_next_component(event, ICAL_VEVENT_COMPONENT) ) {
526                         ical_merge_attendee_reply(c, reply);
527                 }
528                 return;
529         }
530
531         /* Now do the same thing with the reply.
532          */
533         if (icalcomponent_isa(reply) != ICAL_VEVENT_COMPONENT) {
534                 for (c = icalcomponent_get_first_component(reply, ICAL_VEVENT_COMPONENT);
535                     c != NULL;
536                     c = icalcomponent_get_next_component(reply, ICAL_VEVENT_COMPONENT) ) {
537                         ical_merge_attendee_reply(event, c);
538                 }
539                 return;
540         }
541
542         /* Clone the reply, because we're going to rip its guts out. */
543         reply = icalcomponent_new_clone(reply);
544
545         /* At this point we're looking at the correct subcomponents.
546          * Iterate through the attendees looking for a match.
547          */
548 STARTOVER:
549         for (e_attendee = icalcomponent_get_first_property(event, ICAL_ATTENDEE_PROPERTY);
550             e_attendee != NULL;
551             e_attendee = icalcomponent_get_next_property(event, ICAL_ATTENDEE_PROPERTY)) {
552
553                 for (r_attendee = icalcomponent_get_first_property(reply, ICAL_ATTENDEE_PROPERTY);
554                     r_attendee != NULL;
555                     r_attendee = icalcomponent_get_next_property(reply, ICAL_ATTENDEE_PROPERTY)) {
556
557                         /* Check to see if these two attendees match...
558                          */
559                         if (!strcasecmp(
560                            icalproperty_get_attendee(e_attendee),
561                            icalproperty_get_attendee(r_attendee)
562                         )) {
563                                 /* ...and if they do, remove the attendee from the event
564                                  * and replace it with the attendee from the reply.  (The
565                                  * reply's copy will have the same address, but an updated
566                                  * status.)
567                                  */
568                                 icalcomponent_remove_property(event, e_attendee);
569                                 icalproperty_free(e_attendee);
570                                 icalcomponent_remove_property(reply, r_attendee);
571                                 icalcomponent_add_property(event, r_attendee);
572
573                                 /* Since we diddled both sets of attendees, we have to start
574                                  * the iteration over again.  This will not create an infinite
575                                  * loop because we removed the attendee from the reply.  (That's
576                                  * why we cloned the reply, and that's what we mean by "ripping
577                                  * its guts out.")
578                                  */
579                                 goto STARTOVER;
580                         }
581         
582                 }
583         }
584
585         /* Free the *clone* of the reply. */
586         icalcomponent_free(reply);
587 }
588
589
590
591
592 /*
593  * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
594  * calendar event.  The object has already been deserialized for us; all
595  * we have to do here is hunt for the event in our calendar, merge in the
596  * updated attendee status, and save it again.
597  *
598  * This function returns 0 on success, 1 if the event was not found in the
599  * user's calendar, or 2 if an internal error occurred.
600  */
601 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
602         char uid[SIZ];
603         char hold_rm[ROOMNAMELEN];
604         long msgnum_being_replaced = 0;
605         struct CtdlMessage *msg = NULL;
606         struct original_event_container oec;
607         icalcomponent *original_event;
608         char *serialized_event = NULL;
609         char roomname[ROOMNAMELEN];
610         char *message_text = NULL;
611
612         /* Figure out just what event it is we're dealing with */
613         strcpy(uid, "--==<< InVaLiD uId >>==--");
614         ical_learn_uid_of_reply(uid, cal);
615         CtdlLogPrintf(CTDL_DEBUG, "UID of event being replied to is <%s>\n", uid);
616
617         strcpy(hold_rm, CC->room.QRname);       /* save current room */
618
619         if (getroom(&CC->room, USERCALENDARROOM) != 0) {
620                 getroom(&CC->room, hold_rm);
621                 CtdlLogPrintf(CTDL_CRIT, "cannot get user calendar room\n");
622                 return(2);
623         }
624
625         /*
626          * Look in the EUID index for a message with
627          * the Citadel EUID set to the value we're looking for.  Since
628          * Citadel always sets the message EUID to the iCalendar UID of
629          * the event, this will work.
630          */
631         msgnum_being_replaced = locate_message_by_euid(uid, &CC->room);
632
633         getroom(&CC->room, hold_rm);    /* return to saved room */
634
635         CtdlLogPrintf(CTDL_DEBUG, "msgnum_being_replaced == %ld\n", msgnum_being_replaced);
636         if (msgnum_being_replaced == 0) {
637                 return(1);                      /* no calendar event found */
638         }
639
640         /* Now we know the ID of the message containing the event being updated.
641          * We don't actually have to delete it; that'll get taken care of by the
642          * server when we save another event with the same UID.  This just gives
643          * us the ability to load the event into memory so we can diddle the
644          * attendees.
645          */
646         msg = CtdlFetchMessage(msgnum_being_replaced, 1);
647         if (msg == NULL) {
648                 return(2);                      /* internal error */
649         }
650         oec.c = NULL;
651         mime_parser(msg->cm_fields['M'],
652                 NULL,
653                 *ical_locate_original_event,    /* callback function */
654                 NULL, NULL,
655                 &oec,                           /* user data */
656                 0
657         );
658         CtdlFreeMessage(msg);
659
660         original_event = oec.c;
661         if (original_event == NULL) {
662                 CtdlLogPrintf(CTDL_ERR, "ERROR: Original_component is NULL.\n");
663                 return(2);
664         }
665
666         /* Merge the attendee's updated status into the event */
667         ical_merge_attendee_reply(original_event, cal);
668
669         /* Serialize it */
670         serialized_event = icalcomponent_as_ical_string_r(original_event);
671         icalcomponent_free(original_event);     /* Don't need this anymore. */
672         if (serialized_event == NULL) return(2);
673
674         MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
675
676         message_text = malloc(strlen(serialized_event) + SIZ);
677         if (message_text != NULL) {
678                 sprintf(message_text,
679                         "Content-type: text/calendar; charset=\"utf-8\"\r\n\r\n%s\r\n",
680                         serialized_event
681                 );
682
683                 msg = CtdlMakeMessage(&CC->user,
684                         "",                     /* No recipient */
685                         "",                     /* No recipient */
686                         roomname,
687                         0, FMT_RFC822,
688                         "",
689                         "",
690                         "",             /* no subject */
691                         NULL,
692                         message_text,
693                         NULL);
694         
695                 if (msg != NULL) {
696                         CIT_ICAL->avoid_sending_invitations = 1;
697                         CtdlSubmitMsg(msg, NULL, roomname, QP_EADDR);
698                         CtdlFreeMessage(msg);
699                         CIT_ICAL->avoid_sending_invitations = 0;
700                 }
701         }
702         free(serialized_event);
703         return(0);
704 }
705
706
707 /*
708  * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
709  * simply extracts the calendar object from the message, deserializes it, and
710  * passes it up to ical_update_my_calendar_with_reply() for processing.
711  */
712 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
713         struct CtdlMessage *msg = NULL;
714         struct ical_respond_data ird;
715         int ret;
716
717         if (
718            (strcasecmp(action, "update"))
719            && (strcasecmp(action, "ignore"))
720         ) {
721                 cprintf("%d Action must be 'update' or 'ignore'\n",
722                         ERROR + ILLEGAL_VALUE
723                 );
724                 return;
725         }
726
727         msg = CtdlFetchMessage(msgnum, 1);
728         if (msg == NULL) {
729                 cprintf("%d Message %ld not found.\n",
730                         ERROR + ILLEGAL_VALUE,
731                         (long)msgnum
732                 );
733                 return;
734         }
735
736         memset(&ird, 0, sizeof ird);
737         strcpy(ird.desired_partnum, partnum);
738         mime_parser(msg->cm_fields['M'],
739                 NULL,
740                 *ical_locate_part,              /* callback function */
741                 NULL, NULL,
742                 (void *) &ird,                  /* user data */
743                 0
744         );
745
746         /* We're done with the incoming message, because we now have a
747          * calendar object in memory.
748          */
749         CtdlFreeMessage(msg);
750
751         /*
752          * Here is the real meat of this function.  Handle the event.
753          */
754         if (ird.cal != NULL) {
755                 /* Update the user's calendar if necessary */
756                 if (!strcasecmp(action, "update")) {
757                         ret = ical_update_my_calendar_with_reply(ird.cal);
758                         if (ret == 0) {
759                                 cprintf("%d Your calendar has been updated with this reply.\n",
760                                         CIT_OK);
761                         }
762                         else if (ret == 1) {
763                                 cprintf("%d This event does not exist in your calendar.\n",
764                                         ERROR + FILE_NOT_FOUND);
765                         }
766                         else {
767                                 cprintf("%d An internal error occurred.\n",
768                                         ERROR + INTERNAL_ERROR);
769                         }
770                 }
771                 else {
772                         cprintf("%d This reply has been ignored.\n", CIT_OK);
773                 }
774
775                 /* Now that we've processed this message, we don't need it
776                  * anymore.  So delete it.  (Don't do this anymore.)
777                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
778                  */
779
780                 /* Free the memory we allocated and return a response. */
781                 icalcomponent_free(ird.cal);
782                 ird.cal = NULL;
783                 return;
784         }
785         else {
786                 cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
787                 return;
788         }
789
790         /* should never get here */
791 }
792
793
794 /*
795  * Search for a property in both the top level and in a VEVENT subcomponent
796  */
797 icalproperty *ical_ctdl_get_subprop(
798                 icalcomponent *cal,
799                 icalproperty_kind which_prop
800 ) {
801         icalproperty *p;
802         icalcomponent *c;
803
804         p = icalcomponent_get_first_property(cal, which_prop);
805         if (p == NULL) {
806                 c = icalcomponent_get_first_component(cal,
807                                                         ICAL_VEVENT_COMPONENT);
808                 if (c != NULL) {
809                         p = icalcomponent_get_first_property(c, which_prop);
810                 }
811         }
812         return p;
813 }
814
815
816 /*
817  * Check to see if two events overlap.  Returns nonzero if they do.
818  * (This function is used in both Citadel and WebCit.  If you change it in
819  * one place, change it in the other.  Better yet, put it in a library.)
820  */
821 int ical_ctdl_is_overlap(
822                         struct icaltimetype t1start,
823                         struct icaltimetype t1end,
824                         struct icaltimetype t2start,
825                         struct icaltimetype t2end
826 ) {
827         if (icaltime_is_null_time(t1start)) return(0);
828         if (icaltime_is_null_time(t2start)) return(0);
829
830         /* if either event lacks end time, assume end = start */
831         if (icaltime_is_null_time(t1end))
832                 memcpy(&t1end, &t1start, sizeof(struct icaltimetype));
833         else {
834                 if (t1end.is_date && icaltime_compare(t1start, t1end)) {
835                         /*
836                          * the end date is non-inclusive so adjust it by one
837                          * day because our test is inclusive, note that a day is
838                          * not too much because we are talking about all day
839                          * events
840                          * if start = end we assume that nevertheless the whole
841                          * day is meant
842                          */
843                         icaltime_adjust(&t1end, -1, 0, 0, 0);   
844                 }
845         }
846
847         if (icaltime_is_null_time(t2end))
848                 memcpy(&t2end, &t2start, sizeof(struct icaltimetype));
849         else {
850                 if (t2end.is_date && icaltime_compare(t2start, t2end)) {
851                         icaltime_adjust(&t2end, -1, 0, 0, 0);   
852                 }
853         }
854
855         /* First, check for all-day events */
856         if (t1start.is_date || t2start.is_date) {
857                 /* If event 1 ends before event 2 starts, we're in the clear. */
858                 if (icaltime_compare_date_only(t1end, t2start) < 0) return(0);
859
860                 /* If event 2 ends before event 1 starts, we're also ok. */
861                 if (icaltime_compare_date_only(t2end, t1start) < 0) return(0);
862
863                 return(1);
864         }
865
866         /* lprintf (9, "Comparing t1start %d:%d t1end %d:%d t2start %d:%d t2end %d:%d \n",
867                 t1start.hour, t1start.minute, t1end.hour, t1end.minute,
868                 t2start.hour, t2start.minute, t2end.hour, t2end.minute);
869         */
870
871         /* Now check for overlaps using date *and* time. */
872
873         /* If event 1 ends before event 2 starts, we're in the clear. */
874         if (icaltime_compare(t1end, t2start) <= 0) return(0);
875         /* lprintf(9, "first passed\n"); */
876
877         /* If event 2 ends before event 1 starts, we're also ok. */
878         if (icaltime_compare(t2end, t1start) <= 0) return(0);
879         /* lprintf(9, "second passed\n"); */
880
881         /* Otherwise, they overlap. */
882         return(1);
883 }
884
885 /* 
886  * Phase 6 of "hunt for conflicts"
887  * called by ical_conflicts_phase5()
888  *
889  * Now both the proposed and existing events have been boiled down to start and end times.
890  * Check for overlap and output any conflicts.
891  *
892  * Returns nonzero if a conflict was reported.  This allows the caller to stop iterating.
893  */
894 int ical_conflicts_phase6(struct icaltimetype t1start,
895                         struct icaltimetype t1end,
896                         struct icaltimetype t2start,
897                         struct icaltimetype t2end,
898                         long existing_msgnum,
899                         char *conflict_event_uid,
900                         char *conflict_event_summary,
901                         char *compare_uid)
902 {
903         int conflict_reported = 0;
904
905         /* debugging cruft *
906         time_t tt;
907         tt = icaltime_as_timet_with_zone(t1start, t1start.zone);
908         CtdlLogPrintf(CTDL_DEBUG, "PROPOSED START: %s", ctime(&tt));
909         tt = icaltime_as_timet_with_zone(t1end, t1end.zone);
910         CtdlLogPrintf(CTDL_DEBUG, "  PROPOSED END: %s", ctime(&tt));
911         tt = icaltime_as_timet_with_zone(t2start, t2start.zone);
912         CtdlLogPrintf(CTDL_DEBUG, "EXISTING START: %s", ctime(&tt));
913         tt = icaltime_as_timet_with_zone(t2end, t2end.zone);
914         CtdlLogPrintf(CTDL_DEBUG, "  EXISTING END: %s", ctime(&tt));
915         * debugging cruft */
916
917         /* compare and output */
918
919         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
920                 cprintf("%ld||%s|%s|%d|\n",
921                         existing_msgnum,
922                         conflict_event_uid,
923                         conflict_event_summary,
924                         (       ((strlen(compare_uid)>0)
925                                 &&(!strcasecmp(compare_uid,
926                                 conflict_event_uid))) ? 1 : 0
927                         )
928                 );
929                 conflict_reported = 1;
930         }
931
932         return(conflict_reported);
933 }
934
935
936
937 /*
938  * Phase 5 of "hunt for conflicts"
939  * Called by ical_conflicts_phase4()
940  *
941  * We have the proposed event boiled down to start and end times.
942  * Now check it against an existing event. 
943  */
944 void ical_conflicts_phase5(struct icaltimetype t1start,
945                         struct icaltimetype t1end,
946                         icalcomponent *existing_event,
947                         long existing_msgnum,
948                         char *compare_uid)
949 {
950         char conflict_event_uid[SIZ];
951         char conflict_event_summary[SIZ];
952         struct icaltimetype t2start, t2end;
953         icalproperty *p;
954
955         /* recur variables */
956         icalproperty *rrule = NULL;
957         struct icalrecurrencetype recur;
958         icalrecur_iterator *ritr = NULL;
959         struct icaldurationtype dur;
960         int num_recur = 0;
961
962         /* initialization */
963         strcpy(conflict_event_uid, "");
964         strcpy(conflict_event_summary, "");
965         t2start = icaltime_null_time();
966         t2end = icaltime_null_time();
967
968         /* existing event stuff */
969         p = ical_ctdl_get_subprop(existing_event, ICAL_DTSTART_PROPERTY);
970         if (p == NULL) return;
971         if (p != NULL) t2start = icalproperty_get_dtstart(p);
972         if (icaltime_is_utc(t2start)) {
973                 t2start.zone = icaltimezone_get_utc_timezone();
974         }
975         else {
976                 t2start.zone = icalcomponent_get_timezone(existing_event,
977                         icalparameter_get_tzid(
978                                 icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
979                         )
980                 );
981                 if (!t2start.zone) {
982                         t2start.zone = get_default_icaltimezone();
983                 }
984         }
985
986         p = ical_ctdl_get_subprop(existing_event, ICAL_DTEND_PROPERTY);
987         if (p != NULL) {
988                 t2end = icalproperty_get_dtend(p);
989
990                 if (icaltime_is_utc(t2end)) {
991                         t2end.zone = icaltimezone_get_utc_timezone();
992                 }
993                 else {
994                         t2end.zone = icalcomponent_get_timezone(existing_event,
995                                 icalparameter_get_tzid(
996                                         icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
997                                 )
998                         );
999                         if (!t2end.zone) {
1000                                 t2end.zone = get_default_icaltimezone();
1001                         }
1002                 }
1003                 dur = icaltime_subtract(t2end, t2start);
1004         }
1005
1006         rrule = ical_ctdl_get_subprop(existing_event, ICAL_RRULE_PROPERTY);
1007         if (rrule) {
1008                 recur = icalproperty_get_rrule(rrule);
1009                 ritr = icalrecur_iterator_new(recur, t2start);
1010         }
1011
1012         do {
1013                 p = ical_ctdl_get_subprop(existing_event, ICAL_UID_PROPERTY);
1014                 if (p != NULL) {
1015                         strcpy(conflict_event_uid, icalproperty_get_comment(p));
1016                 }
1017         
1018                 p = ical_ctdl_get_subprop(existing_event, ICAL_SUMMARY_PROPERTY);
1019                 if (p != NULL) {
1020                         strcpy(conflict_event_summary, icalproperty_get_comment(p));
1021                 }
1022         
1023                 if (ical_conflicts_phase6(t1start, t1end, t2start, t2end,
1024                    existing_msgnum, conflict_event_uid, conflict_event_summary, compare_uid))
1025                 {
1026                         num_recur = MAX_RECUR + 1;      /* force it out of scope, no need to continue */
1027                 }
1028
1029                 if (rrule) {
1030                         t2start = icalrecur_iterator_next(ritr);
1031                         if (!icaltime_is_null_time(t2end)) {
1032                                 const icaltimezone *hold_zone = t2end.zone;
1033                                 t2end = icaltime_add(t2start, dur);
1034                                 t2end.zone = hold_zone;
1035                         }
1036                         ++num_recur;
1037                 }
1038
1039                 if (icaltime_compare(t2start, t1end) < 0) {
1040                         num_recur = MAX_RECUR + 1;      /* force it out of scope */
1041                 }
1042
1043         } while ( (rrule) && (!icaltime_is_null_time(t2start)) && (num_recur < MAX_RECUR) );
1044         icalrecur_iterator_free(ritr);
1045 }
1046
1047
1048
1049
1050 /*
1051  * Phase 4 of "hunt for conflicts"
1052  * Called by ical_hunt_for_conflicts_backend()
1053  *
1054  * At this point we've got it boiled down to two icalcomponent events in memory.
1055  * If they conflict, output something to the client.
1056  */
1057 void ical_conflicts_phase4(icalcomponent *proposed_event,
1058                 icalcomponent *existing_event,
1059                 long existing_msgnum)
1060 {
1061         struct icaltimetype t1start, t1end;
1062         t1start = icaltime_null_time();
1063         t1end = icaltime_null_time();
1064         icalproperty *p;
1065         char compare_uid[SIZ];
1066
1067         /* recur variables */
1068         icalproperty *rrule = NULL;
1069         struct icalrecurrencetype recur;
1070         icalrecur_iterator *ritr = NULL;
1071         struct icaldurationtype dur;
1072         int num_recur = 0;
1073
1074         /* initialization */
1075         strcpy(compare_uid, "");
1076
1077         /* proposed event stuff */
1078
1079         p = ical_ctdl_get_subprop(proposed_event, ICAL_DTSTART_PROPERTY);
1080         if (p == NULL) return;
1081         if (p != NULL) t1start = icalproperty_get_dtstart(p);
1082         if (icaltime_is_utc(t1start)) {
1083                 t1start.zone = icaltimezone_get_utc_timezone();
1084         }
1085         else {
1086                 t1start.zone = icalcomponent_get_timezone(proposed_event,
1087                         icalparameter_get_tzid(
1088                                 icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
1089                         )
1090                 );
1091                 if (!t1start.zone) {
1092                         t1start.zone = get_default_icaltimezone();
1093                 }
1094         }
1095         
1096         p = ical_ctdl_get_subprop(proposed_event, ICAL_DTEND_PROPERTY);
1097         if (p != NULL) {
1098                 t1end = icalproperty_get_dtend(p);
1099
1100                 if (icaltime_is_utc(t1end)) {
1101                         t1end.zone = icaltimezone_get_utc_timezone();
1102                 }
1103                 else {
1104                         t1end.zone = icalcomponent_get_timezone(proposed_event,
1105                                 icalparameter_get_tzid(
1106                                         icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
1107                                 )
1108                         );
1109                         if (!t1end.zone) {
1110                                 t1end.zone = get_default_icaltimezone();
1111                         }
1112                 }
1113
1114                 dur = icaltime_subtract(t1end, t1start);
1115         }
1116
1117         rrule = ical_ctdl_get_subprop(proposed_event, ICAL_RRULE_PROPERTY);
1118         if (rrule) {
1119                 recur = icalproperty_get_rrule(rrule);
1120                 ritr = icalrecur_iterator_new(recur, t1start);
1121         }
1122
1123         p = ical_ctdl_get_subprop(proposed_event, ICAL_UID_PROPERTY);
1124         if (p != NULL) {
1125                 strcpy(compare_uid, icalproperty_get_comment(p));
1126         }
1127
1128         do {
1129                 ical_conflicts_phase5(t1start, t1end, existing_event, existing_msgnum, compare_uid);
1130
1131                 if (rrule) {
1132                         t1start = icalrecur_iterator_next(ritr);
1133                         if (!icaltime_is_null_time(t1end)) {
1134                                 const icaltimezone *hold_zone = t1end.zone;
1135                                 t1end = icaltime_add(t1start, dur);
1136                                 t1end.zone = hold_zone;
1137                         }
1138                         ++num_recur;
1139                 }
1140
1141         } while ( (rrule) && (!icaltime_is_null_time(t1start)) && (num_recur < MAX_RECUR) );
1142         icalrecur_iterator_free(ritr);
1143 }
1144
1145
1146
1147 /*
1148  * Phase 3 of "hunt for conflicts"
1149  * Called by ical_hunt_for_conflicts()
1150  */
1151 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
1152         icalcomponent *proposed_event;
1153         struct CtdlMessage *msg = NULL;
1154         struct ical_respond_data ird;
1155
1156         proposed_event = (icalcomponent *)data;
1157
1158         msg = CtdlFetchMessage(msgnum, 1);
1159         if (msg == NULL) return;
1160         memset(&ird, 0, sizeof ird);
1161         strcpy(ird.desired_partnum, "_HUNT_");
1162         mime_parser(msg->cm_fields['M'],
1163                 NULL,
1164                 *ical_locate_part,              /* callback function */
1165                 NULL, NULL,
1166                 (void *) &ird,                  /* user data */
1167                 0
1168         );
1169         CtdlFreeMessage(msg);
1170
1171         if (ird.cal == NULL) return;
1172
1173         ical_conflicts_phase4(proposed_event, ird.cal, msgnum);
1174         icalcomponent_free(ird.cal);
1175 }
1176
1177
1178
1179 /* 
1180  * Phase 2 of "hunt for conflicts" operation.
1181  * At this point we have a calendar object which represents the VEVENT that
1182  * is proposed for addition to the calendar.  Now hunt through the user's
1183  * calendar room, and output zero or more existing VEVENTs which conflict
1184  * with this one.
1185  */
1186 void ical_hunt_for_conflicts(icalcomponent *cal) {
1187         char hold_rm[ROOMNAMELEN];
1188
1189         strcpy(hold_rm, CC->room.QRname);       /* save current room */
1190
1191         if (getroom(&CC->room, USERCALENDARROOM) != 0) {
1192                 getroom(&CC->room, hold_rm);
1193                 cprintf("%d You do not have a calendar.\n", ERROR + ROOM_NOT_FOUND);
1194                 return;
1195         }
1196
1197         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
1198
1199         CtdlForEachMessage(MSGS_ALL, 0, NULL,
1200                 NULL,
1201                 NULL,
1202                 ical_hunt_for_conflicts_backend,
1203                 (void *) cal
1204         );
1205
1206         cprintf("000\n");
1207         getroom(&CC->room, hold_rm);    /* return to saved room */
1208
1209 }
1210
1211
1212
1213 /*
1214  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
1215  */
1216 void ical_conflicts(long msgnum, char *partnum) {
1217         struct CtdlMessage *msg = NULL;
1218         struct ical_respond_data ird;
1219
1220         msg = CtdlFetchMessage(msgnum, 1);
1221         if (msg == NULL) {
1222                 cprintf("%d Message %ld not found\n",
1223                         ERROR + ILLEGAL_VALUE,
1224                         (long)msgnum
1225                 );
1226                 return;
1227         }
1228
1229         memset(&ird, 0, sizeof ird);
1230         strcpy(ird.desired_partnum, partnum);
1231         mime_parser(msg->cm_fields['M'],
1232                 NULL,
1233                 *ical_locate_part,              /* callback function */
1234                 NULL, NULL,
1235                 (void *) &ird,                  /* user data */
1236                 0
1237         );
1238
1239         CtdlFreeMessage(msg);
1240
1241         if (ird.cal != NULL) {
1242                 ical_hunt_for_conflicts(ird.cal);
1243                 icalcomponent_free(ird.cal);
1244                 return;
1245         }
1246
1247         cprintf("%d No calendar object found\n", ERROR + ROOM_NOT_FOUND);
1248 }
1249
1250
1251
1252 /*
1253  * Look for busy time in a VEVENT and add it to the supplied VFREEBUSY.
1254  *
1255  * fb                   The VFREEBUSY component to which we are appending
1256  * top_level_cal        The top-level VCALENDAR component which contains a VEVENT to be added
1257  */
1258 void ical_add_to_freebusy(icalcomponent *fb, icalcomponent *top_level_cal) {
1259         icalcomponent *cal;
1260         icalproperty *p;
1261         icalvalue *v;
1262         struct icalperiodtype this_event_period = icalperiodtype_null_period();
1263         icaltimetype dtstart = icaltime_null_time();
1264         icaltimetype dtend = icaltime_null_time();
1265
1266         /* recur variables */
1267         icalproperty *rrule = NULL;
1268         struct icalrecurrencetype recur;
1269         icalrecur_iterator *ritr = NULL;
1270         struct icaldurationtype dur;
1271         int num_recur = 0;
1272
1273         if (!top_level_cal) return;
1274
1275         /* Find the VEVENT component containing an event */
1276         cal = icalcomponent_get_first_component(top_level_cal, ICAL_VEVENT_COMPONENT);
1277         if (!cal) return;
1278
1279         /* If this event is not opaque, the user isn't publishing it as
1280          * busy time, so don't bother doing anything else.
1281          */
1282         p = icalcomponent_get_first_property(cal, ICAL_TRANSP_PROPERTY);
1283         if (p != NULL) {
1284                 v = icalproperty_get_value(p);
1285                 if (v != NULL) {
1286                         if (icalvalue_get_transp(v) != ICAL_TRANSP_OPAQUE) {
1287                                 return;
1288                         }
1289                 }
1290         }
1291
1292         /*
1293          * Now begin calculating the event start and end times.
1294          */
1295         p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
1296         if (!p) return;
1297         dtstart = icalproperty_get_dtstart(p);
1298
1299         if (icaltime_is_utc(dtstart)) {
1300                 dtstart.zone = icaltimezone_get_utc_timezone();
1301         }
1302         else {
1303                 dtstart.zone = icalcomponent_get_timezone(top_level_cal,
1304                         icalparameter_get_tzid(
1305                                 icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER)
1306                         )
1307                 );
1308                 if (!dtstart.zone) {
1309                         dtstart.zone = get_default_icaltimezone();
1310                 }
1311         }
1312
1313         dtend = icalcomponent_get_dtend(cal);
1314         if (!icaltime_is_null_time(dtend)) {
1315                 dur = icaltime_subtract(dtend, dtstart);
1316         }
1317
1318         /* Is a recurrence specified?  If so, get ready to process it... */
1319         rrule = ical_ctdl_get_subprop(cal, ICAL_RRULE_PROPERTY);
1320         if (rrule) {
1321                 recur = icalproperty_get_rrule(rrule);
1322                 ritr = icalrecur_iterator_new(recur, dtstart);
1323         }
1324
1325         do {
1326                 /* Convert the DTSTART and DTEND properties to an icalperiod. */
1327                 this_event_period.start = dtstart;
1328         
1329                 if (!icaltime_is_null_time(dtend)) {
1330                         this_event_period.end = dtend;
1331                 }
1332
1333                 /* Convert the timestamps to UTC.  It's ok to do this because we've already expanded
1334                  * recurrences and this data is never going to get used again.
1335                  */
1336                 this_event_period.start = icaltime_convert_to_zone(
1337                         this_event_period.start,
1338                         icaltimezone_get_utc_timezone()
1339                 );
1340                 this_event_period.end = icaltime_convert_to_zone(
1341                         this_event_period.end,
1342                         icaltimezone_get_utc_timezone()
1343                 );
1344         
1345                 /* Now add it. */
1346                 icalcomponent_add_property(fb, icalproperty_new_freebusy(this_event_period));
1347
1348                 /* Make sure the DTSTART property of the freebusy *list* is set to
1349                  * the DTSTART property of the *earliest event*.
1350                  */
1351                 p = icalcomponent_get_first_property(fb, ICAL_DTSTART_PROPERTY);
1352                 if (p == NULL) {
1353                         icalcomponent_set_dtstart(fb, this_event_period.start);
1354                 }
1355                 else {
1356                         if (icaltime_compare(this_event_period.start, icalcomponent_get_dtstart(fb)) < 0) {
1357                                 icalcomponent_set_dtstart(fb, this_event_period.start);
1358                         }
1359                 }
1360         
1361                 /* Make sure the DTEND property of the freebusy *list* is set to
1362                  * the DTEND property of the *latest event*.
1363                  */
1364                 p = icalcomponent_get_first_property(fb, ICAL_DTEND_PROPERTY);
1365                 if (p == NULL) {
1366                         icalcomponent_set_dtend(fb, this_event_period.end);
1367                 }
1368                 else {
1369                         if (icaltime_compare(this_event_period.end, icalcomponent_get_dtend(fb)) > 0) {
1370                                 icalcomponent_set_dtend(fb, this_event_period.end);
1371                         }
1372                 }
1373
1374                 if (rrule) {
1375                         dtstart = icalrecur_iterator_next(ritr);
1376                         if (!icaltime_is_null_time(dtend)) {
1377                                 dtend = icaltime_add(dtstart, dur);
1378                                 dtend.zone = dtstart.zone;
1379                                 dtend.is_utc = dtstart.is_utc;
1380                         }
1381                         ++num_recur;
1382                 }
1383
1384         } while ( (rrule) && (!icaltime_is_null_time(dtstart)) && (num_recur < MAX_RECUR) ) ;
1385         icalrecur_iterator_free(ritr);
1386 }
1387
1388
1389
1390 /*
1391  * Backend for ical_freebusy()
1392  *
1393  * This function simply loads the messages in the user's calendar room,
1394  * which contain VEVENTs, then strips them of all non-freebusy data, and
1395  * adds them to the supplied VCALENDAR.
1396  *
1397  */
1398 void ical_freebusy_backend(long msgnum, void *data) {
1399         icalcomponent *fb;
1400         struct CtdlMessage *msg = NULL;
1401         struct ical_respond_data ird;
1402
1403         fb = (icalcomponent *)data;             /* User-supplied data will be the VFREEBUSY component */
1404
1405         msg = CtdlFetchMessage(msgnum, 1);
1406         if (msg == NULL) return;
1407         memset(&ird, 0, sizeof ird);
1408         strcpy(ird.desired_partnum, "_HUNT_");
1409         mime_parser(msg->cm_fields['M'],
1410                 NULL,
1411                 *ical_locate_part,              /* callback function */
1412                 NULL, NULL,
1413                 (void *) &ird,                  /* user data */
1414                 0
1415         );
1416         CtdlFreeMessage(msg);
1417
1418         if (ird.cal) {
1419                 ical_add_to_freebusy(fb, ird.cal);              /* Add VEVENT times to VFREEBUSY */
1420                 icalcomponent_free(ird.cal);
1421         }
1422 }
1423
1424
1425
1426 /*
1427  * Grab another user's free/busy times
1428  */
1429 void ical_freebusy(char *who) {
1430         struct ctdluser usbuf;
1431         char calendar_room_name[ROOMNAMELEN];
1432         char hold_rm[ROOMNAMELEN];
1433         char *serialized_request = NULL;
1434         icalcomponent *encaps = NULL;
1435         icalcomponent *fb = NULL;
1436         int found_user = (-1);
1437         struct recptypes *recp = NULL;
1438         char buf[256];
1439         char host[256];
1440         char type[256];
1441         int i = 0;
1442         int config_lines = 0;
1443
1444         /* First try an exact match. */
1445         found_user = getuser(&usbuf, who);
1446
1447         /* If not found, try it as an unqualified email address. */
1448         if (found_user != 0) {
1449                 strcpy(buf, who);
1450                 recp = validate_recipients(buf, NULL, 0);
1451                 CtdlLogPrintf(CTDL_DEBUG, "Trying <%s>\n", buf);
1452                 if (recp != NULL) {
1453                         if (recp->num_local == 1) {
1454                                 found_user = getuser(&usbuf, recp->recp_local);
1455                         }
1456                         free_recipients(recp);
1457                 }
1458         }
1459
1460         /* If still not found, try it as an address qualified with the
1461          * primary FQDN of this Citadel node.
1462          */
1463         if (found_user != 0) {
1464                 snprintf(buf, sizeof buf, "%s@%s", who, config.c_fqdn);
1465                 CtdlLogPrintf(CTDL_DEBUG, "Trying <%s>\n", buf);
1466                 recp = validate_recipients(buf, NULL, 0);
1467                 if (recp != NULL) {
1468                         if (recp->num_local == 1) {
1469                                 found_user = getuser(&usbuf, recp->recp_local);
1470                         }
1471                         free_recipients(recp);
1472                 }
1473         }
1474
1475         /* Still not found?  Try qualifying it with every domain we
1476          * might have addresses in.
1477          */
1478         if (found_user != 0) {
1479                 config_lines = num_tokens(inetcfg, '\n');
1480                 for (i=0; ((i < config_lines) && (found_user != 0)); ++i) {
1481                         extract_token(buf, inetcfg, i, '\n', sizeof buf);
1482                         extract_token(host, buf, 0, '|', sizeof host);
1483                         extract_token(type, buf, 1, '|', sizeof type);
1484
1485                         if ( (!strcasecmp(type, "localhost"))
1486                            || (!strcasecmp(type, "directory")) ) {
1487                                 snprintf(buf, sizeof buf, "%s@%s", who, host);
1488                                 CtdlLogPrintf(CTDL_DEBUG, "Trying <%s>\n", buf);
1489                                 recp = validate_recipients(buf, NULL, 0);
1490                                 if (recp != NULL) {
1491                                         if (recp->num_local == 1) {
1492                                                 found_user = getuser(&usbuf, recp->recp_local);
1493                                         }
1494                                         free_recipients(recp);
1495                                 }
1496                         }
1497                 }
1498         }
1499
1500         if (found_user != 0) {
1501                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1502                 return;
1503         }
1504
1505         MailboxName(calendar_room_name, sizeof calendar_room_name,
1506                 &usbuf, USERCALENDARROOM);
1507
1508         strcpy(hold_rm, CC->room.QRname);       /* save current room */
1509
1510         if (getroom(&CC->room, calendar_room_name) != 0) {
1511                 cprintf("%d Cannot open calendar\n", ERROR + ROOM_NOT_FOUND);
1512                 getroom(&CC->room, hold_rm);
1513                 return;
1514         }
1515
1516         /* Create a VFREEBUSY subcomponent */
1517         CtdlLogPrintf(CTDL_DEBUG, "Creating VFREEBUSY component\n");
1518         fb = icalcomponent_new_vfreebusy();
1519         if (fb == NULL) {
1520                 cprintf("%d Internal error: cannot allocate memory.\n",
1521                         ERROR + INTERNAL_ERROR);
1522                 getroom(&CC->room, hold_rm);
1523                 return;
1524         }
1525
1526         /* Set the method to PUBLISH */
1527         icalcomponent_set_method(fb, ICAL_METHOD_PUBLISH);
1528
1529         /* Set the DTSTAMP to right now. */
1530         icalcomponent_set_dtstamp(fb, icaltime_from_timet(time(NULL), 0));
1531
1532         /* Add the user's email address as ORGANIZER */
1533         sprintf(buf, "MAILTO:%s", who);
1534         if (strchr(buf, '@') == NULL) {
1535                 strcat(buf, "@");
1536                 strcat(buf, config.c_fqdn);
1537         }
1538         for (i=0; buf[i]; ++i) {
1539                 if (buf[i]==' ') buf[i] = '_';
1540         }
1541         icalcomponent_add_property(fb, icalproperty_new_organizer(buf));
1542
1543         /* Add busy time from events */
1544         CtdlLogPrintf(CTDL_DEBUG, "Adding busy time from events\n");
1545         CtdlForEachMessage(MSGS_ALL, 0, NULL, NULL, NULL, ical_freebusy_backend, (void *)fb );
1546
1547         /* If values for DTSTART and DTEND are still not present, set them
1548          * to yesterday and tomorrow as default values.
1549          */
1550         if (icalcomponent_get_first_property(fb, ICAL_DTSTART_PROPERTY) == NULL) {
1551                 icalcomponent_set_dtstart(fb, icaltime_from_timet(time(NULL)-86400L, 0));
1552         }
1553         if (icalcomponent_get_first_property(fb, ICAL_DTEND_PROPERTY) == NULL) {
1554                 icalcomponent_set_dtend(fb, icaltime_from_timet(time(NULL)+86400L, 0));
1555         }
1556
1557         /* Put the freebusy component into the calendar component */
1558         CtdlLogPrintf(CTDL_DEBUG, "Encapsulating\n");
1559         encaps = ical_encapsulate_subcomponent(fb);
1560         if (encaps == NULL) {
1561                 icalcomponent_free(fb);
1562                 cprintf("%d Internal error: cannot allocate memory.\n",
1563                         ERROR + INTERNAL_ERROR);
1564                 getroom(&CC->room, hold_rm);
1565                 return;
1566         }
1567
1568         /* Set the method to PUBLISH */
1569         CtdlLogPrintf(CTDL_DEBUG, "Setting method\n");
1570         icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1571
1572         /* Serialize it */
1573         CtdlLogPrintf(CTDL_DEBUG, "Serializing\n");
1574         serialized_request = icalcomponent_as_ical_string_r(encaps);
1575         icalcomponent_free(encaps);     /* Don't need this anymore. */
1576
1577         cprintf("%d Free/busy for %s\n", LISTING_FOLLOWS, usbuf.fullname);
1578         if (serialized_request != NULL) {
1579                 client_write(serialized_request, strlen(serialized_request));
1580                 free(serialized_request);
1581         }
1582         cprintf("\n000\n");
1583
1584         /* Go back to the room from which we came... */
1585         getroom(&CC->room, hold_rm);
1586 }
1587
1588
1589
1590 /*
1591  * Backend for ical_getics()
1592  * 
1593  * This is a ForEachMessage() callback function that searches the current room
1594  * for calendar events and adds them each into one big calendar component.
1595  */
1596 void ical_getics_backend(long msgnum, void *data) {
1597         icalcomponent *encaps, *c;
1598         struct CtdlMessage *msg = NULL;
1599         struct ical_respond_data ird;
1600
1601         encaps = (icalcomponent *)data;
1602         if (encaps == NULL) return;
1603
1604         /* Look for the calendar event... */
1605
1606         msg = CtdlFetchMessage(msgnum, 1);
1607         if (msg == NULL) return;
1608         memset(&ird, 0, sizeof ird);
1609         strcpy(ird.desired_partnum, "_HUNT_");
1610         mime_parser(msg->cm_fields['M'],
1611                 NULL,
1612                 *ical_locate_part,              /* callback function */
1613                 NULL, NULL,
1614                 (void *) &ird,                  /* user data */
1615                 0
1616         );
1617         CtdlFreeMessage(msg);
1618
1619         if (ird.cal == NULL) return;
1620
1621         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1622          * are responsible for "the_request"'s memory -- it will be freed
1623          * when we free "encaps".
1624          */
1625
1626         /* If the top-level component is *not* a VCALENDAR, we can drop it right
1627          * in.  This will almost never happen.
1628          */
1629         if (icalcomponent_isa(ird.cal) != ICAL_VCALENDAR_COMPONENT) {
1630                 icalcomponent_add_component(encaps, ird.cal);
1631         }
1632         /*
1633          * In the more likely event that we're looking at a VCALENDAR with the VEVENT
1634          * and other components encapsulated inside, we have to extract them.
1635          */
1636         else {
1637                 for (c = icalcomponent_get_first_component(ird.cal, ICAL_ANY_COMPONENT);
1638                     (c != NULL);
1639                     c = icalcomponent_get_next_component(ird.cal, ICAL_ANY_COMPONENT)) {
1640
1641                         /* For VTIMEZONE components, suppress duplicates of the same tzid */
1642
1643                         if (icalcomponent_isa(c) == ICAL_VTIMEZONE_COMPONENT) {
1644                                 icalproperty *p = icalcomponent_get_first_property(c, ICAL_TZID_PROPERTY);
1645                                 if (p) {
1646                                         const char *tzid = icalproperty_get_tzid(p);
1647                                         if (!icalcomponent_get_timezone(encaps, tzid)) {
1648                                                 icalcomponent_add_component(encaps,
1649                                                                         icalcomponent_new_clone(c));
1650                                         }
1651                                 }
1652                         }
1653
1654                         /* All other types of components can go in verbatim */
1655                         else {
1656                                 icalcomponent_add_component(encaps, icalcomponent_new_clone(c));
1657                         }
1658                 }
1659                 icalcomponent_free(ird.cal);
1660         }
1661 }
1662
1663
1664
1665 /*
1666  * Retrieve all of the calendar items in the current room, and output them
1667  * as a single icalendar object.
1668  */
1669 void ical_getics(void)
1670 {
1671         icalcomponent *encaps = NULL;
1672         char *ser = NULL;
1673
1674         if ( (CC->room.QRdefaultview != VIEW_CALENDAR)
1675            &&(CC->room.QRdefaultview != VIEW_TASKS) ) {
1676                 cprintf("%d Not a calendar room\n", ERROR+NOT_HERE);
1677                 return;         /* Not an iCalendar-centric room */
1678         }
1679
1680         encaps = icalcomponent_new_vcalendar();
1681         if (encaps == NULL) {
1682                 CtdlLogPrintf(CTDL_ALERT, "ERROR: could not allocate component!\n");
1683                 cprintf("%d Could not allocate memory\n", ERROR+INTERNAL_ERROR);
1684                 return;
1685         }
1686
1687         cprintf("%d one big calendar\n", LISTING_FOLLOWS);
1688
1689         /* Set the Product ID */
1690         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1691
1692         /* Set the Version Number */
1693         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1694
1695         /* Set the method to PUBLISH */
1696         icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1697
1698         /* Now go through the room encapsulating all calendar items. */
1699         CtdlForEachMessage(MSGS_ALL, 0, NULL,
1700                 NULL,
1701                 NULL,
1702                 ical_getics_backend,
1703                 (void *) encaps
1704         );
1705
1706         ser = icalcomponent_as_ical_string_r(encaps);
1707         icalcomponent_free(encaps);                     /* Don't need this anymore. */
1708         client_write(ser, strlen(ser));
1709         free(ser);
1710         cprintf("\n000\n");
1711 }
1712
1713
1714 /*
1715  * Helper callback function for ical_putics() to discover which TZID's we need.
1716  * Simply put the tzid name string into a hash table.  After the callbacks are
1717  * done we'll go through them and attach the ones that we have.
1718  */
1719 void ical_putics_grabtzids(icalparameter *param, void *data)
1720 {
1721         const char *tzid = icalparameter_get_tzid(param);
1722         HashList *keys = (HashList *) data;
1723         
1724         if ( (keys) && (tzid) && (!IsEmptyStr(tzid)) ) {
1725                 Put(keys, tzid, strlen(tzid), strdup(tzid), generic_free_handler);
1726         }
1727 }
1728
1729
1730 /*
1731  * Delete all of the calendar items in the current room, and replace them
1732  * with calendar items from a client-supplied data stream.
1733  */
1734 void ical_putics(void)
1735 {
1736         char *calstream = NULL;
1737         icalcomponent *cal;
1738         icalcomponent *c;
1739         icalcomponent *encaps = NULL;
1740         HashList *tzidlist = NULL;
1741         HashPos *HashPos;
1742         void *Value;
1743         const char *Key;
1744         long len;
1745
1746         /* Only allow this operation if we're in a room containing a calendar or tasks view */
1747         if ( (CC->room.QRdefaultview != VIEW_CALENDAR)
1748            &&(CC->room.QRdefaultview != VIEW_TASKS) ) {
1749                 cprintf("%d Not a calendar room\n", ERROR+NOT_HERE);
1750                 return;
1751         }
1752
1753         /* Only allow this operation if we have permission to overwrite the existing calendar */
1754         if (!CtdlDoIHavePermissionToDeleteMessagesFromThisRoom()) {
1755                 cprintf("%d Permission denied.\n", ERROR+HIGHER_ACCESS_REQUIRED);
1756                 return;
1757         }
1758
1759         cprintf("%d Transmit data now\n", SEND_LISTING);
1760         calstream = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0, 0);
1761         if (calstream == NULL) {
1762                 return;
1763         }
1764
1765         cal = icalcomponent_new_from_string(calstream);
1766         free(calstream);
1767
1768         /* We got our data stream -- now do something with it. */
1769
1770         /* Delete the existing messages in the room, because we are overwriting
1771          * the entire calendar with an entire new (or updated) calendar.
1772          * (Careful: this opens an S_ROOMS critical section!)
1773          */
1774         CtdlDeleteMessages(CC->room.QRname, NULL, 0, "");
1775
1776         /* If the top-level component is *not* a VCALENDAR, we can drop it right
1777          * in.  This will almost never happen.
1778          */
1779         if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
1780                 ical_write_to_cal(NULL, cal);
1781         }
1782         /*
1783          * In the more likely event that we're looking at a VCALENDAR with the VEVENT
1784          * and other components encapsulated inside, we have to extract them.
1785          */
1786         else {
1787                 for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1788                     (c != NULL);
1789                     c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1790
1791                         /* Non-VTIMEZONE components each get written as individual messages.
1792                          * But we also need to attach the relevant VTIMEZONE components to them.
1793                          */
1794                         if ( (icalcomponent_isa(c) != ICAL_VTIMEZONE_COMPONENT)
1795                            && (encaps = icalcomponent_new_vcalendar()) ) {
1796                                 icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1797                                 icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1798                                 icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1799
1800                                 /* Attach any needed timezones here */
1801                                 tzidlist = NewHash(1, NULL);
1802                                 if (tzidlist) {
1803                                         icalcomponent_foreach_tzid(c, ical_putics_grabtzids, tzidlist);
1804                                 }
1805                                 HashPos = GetNewHashPos(tzidlist, 0);
1806
1807                                 while (GetNextHashPos(tzidlist, HashPos, &len, &Key, &Value)) {
1808                                         CtdlLogPrintf(CTDL_DEBUG, "Attaching timezone '%s'\n", Value);
1809                                         icaltimezone *t = NULL;
1810
1811                                         /* First look for a timezone attached to the original calendar */
1812                                         t = icalcomponent_get_timezone(cal, Value);
1813
1814                                         /* Try built-in tzdata if the right one wasn't attached */
1815                                         if (!t) {
1816                                                 t = icaltimezone_get_builtin_timezone(Value);
1817                                         }
1818
1819                                         /* I've got a valid timezone to attach. */
1820                                         if (t) {
1821                                                 icalcomponent_add_component(encaps,
1822                                                         icalcomponent_new_clone(
1823                                                                 icaltimezone_get_component(t)
1824                                                         )
1825                                                 );
1826                                         }
1827
1828                                 }
1829                                 DeleteHashPos(&HashPos);
1830                                 DeleteHash(&tzidlist);
1831
1832                                 /* Now attach the component itself (usually a VEVENT or VTODO) */
1833                                 icalcomponent_add_component(encaps, icalcomponent_new_clone(c));
1834
1835                                 /* Write it to the message store */
1836                                 ical_write_to_cal(NULL, encaps);
1837                                 icalcomponent_free(encaps);
1838                         }
1839                 }
1840         }
1841
1842         icalcomponent_free(cal);
1843 }
1844
1845
1846 /*
1847  * All Citadel calendar commands from the client come through here.
1848  */
1849 void cmd_ical(char *argbuf)
1850 {
1851         char subcmd[64];
1852         long msgnum;
1853         char partnum[256];
1854         char action[256];
1855         char who[256];
1856
1857         extract_token(subcmd, argbuf, 0, '|', sizeof subcmd);
1858
1859         /* Allow "test" and "freebusy" subcommands without logging in. */
1860
1861         if (!strcasecmp(subcmd, "test")) {
1862                 cprintf("%d This server supports calendaring\n", CIT_OK);
1863                 return;
1864         }
1865
1866         if (!strcasecmp(subcmd, "freebusy")) {
1867                 extract_token(who, argbuf, 1, '|', sizeof who);
1868                 ical_freebusy(who);
1869                 return;
1870         }
1871
1872         if (!strcasecmp(subcmd, "sgi")) {
1873                 CIT_ICAL->server_generated_invitations =
1874                         (extract_int(argbuf, 1) ? 1 : 0) ;
1875                 cprintf("%d %d\n",
1876                         CIT_OK, CIT_ICAL->server_generated_invitations);
1877                 return;
1878         }
1879
1880         if (CtdlAccessCheck(ac_logged_in)) return;
1881
1882         if (!strcasecmp(subcmd, "respond")) {
1883                 msgnum = extract_long(argbuf, 1);
1884                 extract_token(partnum, argbuf, 2, '|', sizeof partnum);
1885                 extract_token(action, argbuf, 3, '|', sizeof action);
1886                 ical_respond(msgnum, partnum, action);
1887                 return;
1888         }
1889
1890         if (!strcasecmp(subcmd, "handle_rsvp")) {
1891                 msgnum = extract_long(argbuf, 1);
1892                 extract_token(partnum, argbuf, 2, '|', sizeof partnum);
1893                 extract_token(action, argbuf, 3, '|', sizeof action);
1894                 ical_handle_rsvp(msgnum, partnum, action);
1895                 return;
1896         }
1897
1898         if (!strcasecmp(subcmd, "conflicts")) {
1899                 msgnum = extract_long(argbuf, 1);
1900                 extract_token(partnum, argbuf, 2, '|', sizeof partnum);
1901                 ical_conflicts(msgnum, partnum);
1902                 return;
1903         }
1904
1905         if (!strcasecmp(subcmd, "getics")) {
1906                 ical_getics();
1907                 return;
1908         }
1909
1910         if (!strcasecmp(subcmd, "putics")) {
1911                 ical_putics();
1912                 return;
1913         }
1914
1915         cprintf("%d Invalid subcommand\n", ERROR + CMD_NOT_SUPPORTED);
1916 }
1917
1918
1919
1920 /*
1921  * We don't know if the calendar room exists so we just create it at login
1922  */
1923 void ical_create_room(void)
1924 {
1925         struct ctdlroom qr;
1926         struct visit vbuf;
1927
1928         /* Create the calendar room if it doesn't already exist */
1929         create_room(USERCALENDARROOM, 4, "", 0, 1, 0, VIEW_CALENDAR);
1930
1931         /* Set expiration policy to manual; otherwise objects will be lost! */
1932         if (lgetroom(&qr, USERCALENDARROOM)) {
1933                 CtdlLogPrintf(CTDL_CRIT, "Couldn't get the user calendar room!\n");
1934                 return;
1935         }
1936         qr.QRep.expire_mode = EXPIRE_MANUAL;
1937         qr.QRdefaultview = VIEW_CALENDAR;       /* 3 = calendar view */
1938         lputroom(&qr);
1939
1940         /* Set the view to a calendar view */
1941         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1942         vbuf.v_view = VIEW_CALENDAR;
1943         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1944
1945         /* Create the tasks list room if it doesn't already exist */
1946         create_room(USERTASKSROOM, 4, "", 0, 1, 0, VIEW_TASKS);
1947
1948         /* Set expiration policy to manual; otherwise objects will be lost! */
1949         if (lgetroom(&qr, USERTASKSROOM)) {
1950                 CtdlLogPrintf(CTDL_CRIT, "Couldn't get the user calendar room!\n");
1951                 return;
1952         }
1953         qr.QRep.expire_mode = EXPIRE_MANUAL;
1954         qr.QRdefaultview = VIEW_TASKS;
1955         lputroom(&qr);
1956
1957         /* Set the view to a task list view */
1958         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1959         vbuf.v_view = VIEW_TASKS;
1960         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1961
1962         /* Create the notes room if it doesn't already exist */
1963         create_room(USERNOTESROOM, 4, "", 0, 1, 0, VIEW_NOTES);
1964
1965         /* Set expiration policy to manual; otherwise objects will be lost! */
1966         if (lgetroom(&qr, USERNOTESROOM)) {
1967                 CtdlLogPrintf(CTDL_CRIT, "Couldn't get the user calendar room!\n");
1968                 return;
1969         }
1970         qr.QRep.expire_mode = EXPIRE_MANUAL;
1971         qr.QRdefaultview = VIEW_NOTES;
1972         lputroom(&qr);
1973
1974         /* Set the view to a notes view */
1975         CtdlGetRelationship(&vbuf, &CC->user, &qr);
1976         vbuf.v_view = VIEW_NOTES;
1977         CtdlSetRelationship(&vbuf, &CC->user, &qr);
1978
1979         return;
1980 }
1981
1982
1983 /*
1984  * ical_send_out_invitations() is called by ical_saving_vevent() when it finds a VEVENT.
1985  *
1986  * top_level_cal is the highest available level calendar object.
1987  * cal is the subcomponent containing the VEVENT.
1988  *
1989  * Note: if you change the encapsulation code here, change it in WebCit's ical_encapsulate_subcomponent()
1990  */
1991 void ical_send_out_invitations(icalcomponent *top_level_cal, icalcomponent *cal) {
1992         icalcomponent *the_request = NULL;
1993         char *serialized_request = NULL;
1994         icalcomponent *encaps = NULL;
1995         char *request_message_text = NULL;
1996         struct CtdlMessage *msg = NULL;
1997         struct recptypes *valid = NULL;
1998         char attendees_string[SIZ];
1999         int num_attendees = 0;
2000         char this_attendee[256];
2001         icalproperty *attendee = NULL;
2002         char summary_string[SIZ];
2003         icalproperty *summary = NULL;
2004         size_t reqsize;
2005         icalproperty *p;
2006         struct icaltimetype t;
2007         const icaltimezone *attached_zones[5] = { NULL, NULL, NULL, NULL, NULL };
2008         int i;
2009         const icaltimezone *z;
2010         int num_zones_attached = 0;
2011         int zone_already_attached;
2012         icalparameter *tzidp = NULL;
2013         const char *tzidc = NULL;
2014
2015         if (cal == NULL) {
2016                 CtdlLogPrintf(CTDL_ERR, "ERROR: trying to reply to NULL event?\n");
2017                 return;
2018         }
2019
2020
2021         /* If this is a VCALENDAR component, look for a VEVENT subcomponent. */
2022         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
2023                 ical_send_out_invitations(top_level_cal,
2024                         icalcomponent_get_first_component(
2025                                 cal, ICAL_VEVENT_COMPONENT
2026                         )
2027                 );
2028                 return;
2029         }
2030
2031         /* Clone the event */
2032         the_request = icalcomponent_new_clone(cal);
2033         if (the_request == NULL) {
2034                 CtdlLogPrintf(CTDL_ERR, "ERROR: cannot clone calendar object\n");
2035                 return;
2036         }
2037
2038         /* Extract the summary string -- we'll use it as the
2039          * message subject for the request
2040          */
2041         strcpy(summary_string, "Meeting request");
2042         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
2043         if (summary != NULL) {
2044                 if (icalproperty_get_summary(summary)) {
2045                         strcpy(summary_string,
2046                                 icalproperty_get_summary(summary) );
2047                 }
2048         }
2049
2050         /* Determine who the recipients of this message are (the attendees) */
2051         strcpy(attendees_string, "");
2052         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
2053                 if (icalproperty_get_attendee(attendee)) {
2054                         safestrncpy(this_attendee, icalproperty_get_attendee(attendee), sizeof this_attendee);
2055                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
2056                                 strcpy(this_attendee, &this_attendee[7]);
2057
2058                                 if (!CtdlIsMe(this_attendee, sizeof this_attendee)) {   /* don't send an invitation to myself! */
2059                                         snprintf(&attendees_string[strlen(attendees_string)],
2060                                                 sizeof(attendees_string) - strlen(attendees_string),
2061                                                 "%s, ",
2062                                                 this_attendee
2063                                         );
2064                                         ++num_attendees;
2065                                 }
2066                         }
2067                 }
2068         }
2069
2070         CtdlLogPrintf(CTDL_DEBUG, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
2071
2072         /* If there are no attendees, there are no invitations to send, so...
2073          * don't bother putting one together!  Punch out, Maverick!
2074          */
2075         if (num_attendees == 0) {
2076                 icalcomponent_free(the_request);
2077                 return;
2078         }
2079
2080         /* Encapsulate the VEVENT component into a complete VCALENDAR */
2081         encaps = icalcomponent_new_vcalendar();
2082         if (encaps == NULL) {
2083                 CtdlLogPrintf(CTDL_ALERT, "ERROR: could not allocate component!\n");
2084                 icalcomponent_free(the_request);
2085                 return;
2086         }
2087
2088         /* Set the Product ID */
2089         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
2090
2091         /* Set the Version Number */
2092         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
2093
2094         /* Set the method to REQUEST */
2095         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
2096
2097         /* Look for properties containing timezone parameters, to see if we need to attach VTIMEZONEs */
2098         for (p = icalcomponent_get_first_property(the_request, ICAL_ANY_PROPERTY);
2099              p != NULL;
2100              p = icalcomponent_get_next_property(the_request, ICAL_ANY_PROPERTY))
2101         {
2102                 if ( (icalproperty_isa(p) == ICAL_COMPLETED_PROPERTY)
2103                   || (icalproperty_isa(p) == ICAL_CREATED_PROPERTY)
2104                   || (icalproperty_isa(p) == ICAL_DATEMAX_PROPERTY)
2105                   || (icalproperty_isa(p) == ICAL_DATEMIN_PROPERTY)
2106                   || (icalproperty_isa(p) == ICAL_DTEND_PROPERTY)
2107                   || (icalproperty_isa(p) == ICAL_DTSTAMP_PROPERTY)
2108                   || (icalproperty_isa(p) == ICAL_DTSTART_PROPERTY)
2109                   || (icalproperty_isa(p) == ICAL_DUE_PROPERTY)
2110                   || (icalproperty_isa(p) == ICAL_EXDATE_PROPERTY)
2111                   || (icalproperty_isa(p) == ICAL_LASTMODIFIED_PROPERTY)
2112                   || (icalproperty_isa(p) == ICAL_MAXDATE_PROPERTY)
2113                   || (icalproperty_isa(p) == ICAL_MINDATE_PROPERTY)
2114                   || (icalproperty_isa(p) == ICAL_RECURRENCEID_PROPERTY)
2115                 ) {
2116                         t = icalproperty_get_dtstart(p);        // it's safe to use dtstart for all of them
2117
2118                         /* Determine the tzid in order for some of the conditions below to work */
2119                         tzidp = icalproperty_get_first_parameter(p, ICAL_TZID_PARAMETER);
2120                         if (tzidp) {
2121                                 tzidc = icalparameter_get_tzid(tzidp);
2122                         }
2123                         else {
2124                                 tzidc = NULL;
2125                         }
2126
2127                         /* First see if there's a timezone attached to the data structure itself */
2128                         if (icaltime_is_utc(t)) {
2129                                 z = icaltimezone_get_utc_timezone();
2130                         }
2131                         else {
2132                                 z = icaltime_get_timezone(t);
2133                         }
2134
2135                         /* If not, try to determine the tzid from the parameter using attached zones */
2136                         if ((!z) && (tzidc)) {
2137                                 z = icalcomponent_get_timezone(top_level_cal, tzidc);
2138                         }
2139
2140                         /* Still no good?  Try our internal database */
2141                         if ((!z) && (tzidc)) {
2142                                 z = icaltimezone_get_builtin_timezone_from_tzid(tzidc);
2143                         }
2144
2145                         if (z) {
2146                                 /* We have a valid timezone.  Good.  Now we need to attach it. */
2147
2148                                 zone_already_attached = 0;
2149                                 for (i=0; i<5; ++i) {
2150                                         if (z == attached_zones[i]) {
2151                                                 /* We've already got this one, no need to attach another. */
2152                                                 ++zone_already_attached;
2153                                         }
2154                                 }
2155                                 if ((!zone_already_attached) && (num_zones_attached < 5)) {
2156                                         /* This is a new one, so attach it. */
2157                                         attached_zones[num_zones_attached++] = z;
2158                                 }
2159
2160                                 icalproperty_set_parameter(p,
2161                                         icalparameter_new_tzid(icaltimezone_get_tzid(z))
2162                                 );
2163                         }
2164                 }
2165         }
2166
2167         /* Encapsulate any timezones we need */
2168         if (num_zones_attached > 0) for (i=0; i<num_zones_attached; ++i) {
2169                 icalcomponent *zc;
2170                 zc = icalcomponent_new_clone(icaltimezone_get_component(attached_zones[i]));
2171                 icalcomponent_add_component(encaps, zc);
2172         }
2173
2174         /* Here we go: encapsulate the VEVENT into the VCALENDAR.  We now no longer
2175          * are responsible for "the_request"'s memory -- it will be freed
2176          * when we free "encaps".
2177          */
2178         icalcomponent_add_component(encaps, the_request);
2179
2180         /* Serialize it */
2181         serialized_request = icalcomponent_as_ical_string_r(encaps);
2182         icalcomponent_free(encaps);     /* Don't need this anymore. */
2183         if (serialized_request == NULL) return;
2184
2185         reqsize = strlen(serialized_request) + SIZ;
2186         request_message_text = malloc(reqsize);
2187         if (request_message_text != NULL) {
2188                 snprintf(request_message_text, reqsize,
2189                         "Content-type: text/calendar\r\n\r\n%s\r\n",
2190                         serialized_request
2191                 );
2192
2193                 msg = CtdlMakeMessage(
2194                         &CC->user,
2195                         NULL,                   /* No single recipient here */
2196                         NULL,                   /* No single recipient here */
2197                         CC->room.QRname,
2198                         0,
2199                         FMT_RFC822,
2200                         NULL,
2201                         NULL,
2202                         summary_string,         /* Use summary for subject */
2203                         NULL,
2204                         request_message_text,
2205                         NULL
2206                 );
2207         
2208                 if (msg != NULL) {
2209                         valid = validate_recipients(attendees_string, NULL, 0);
2210                         CtdlSubmitMsg(msg, valid, "", QP_EADDR);
2211                         CtdlFreeMessage(msg);
2212                         free_recipients(valid);
2213                 }
2214         }
2215         free(serialized_request);
2216 }
2217
2218
2219 /*
2220  * When a calendar object is being saved, determine whether it's a VEVENT
2221  * and the user saving it is the organizer.  If so, send out invitations
2222  * to any listed attendees.
2223  *
2224  * This function is recursive.  The caller can simply supply the same object
2225  * as both arguments.  When it recurses it will alter the second argument
2226  * while holding on to the top level object.  This allows us to go back and
2227  * grab things like time zones which might be attached.
2228  *
2229  */
2230 void ical_saving_vevent(icalcomponent *top_level_cal, icalcomponent *cal) {
2231         icalcomponent *c;
2232         icalproperty *organizer = NULL;
2233         char organizer_string[SIZ];
2234
2235         CtdlLogPrintf(CTDL_DEBUG, "ical_saving_vevent() has been called!\n");
2236
2237         /* Don't send out invitations unless the client wants us to. */
2238         if (CIT_ICAL->server_generated_invitations == 0) {
2239                 return;
2240         }
2241
2242         /* Don't send out invitations if we've been asked not to. */
2243         if (CIT_ICAL->avoid_sending_invitations > 0) {
2244                 return;
2245         }
2246
2247         strcpy(organizer_string, "");
2248         /*
2249          * The VEVENT subcomponent is the one we're interested in.
2250          * Send out invitations if, and only if, this user is the Organizer.
2251          */
2252         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
2253                 organizer = icalcomponent_get_first_property(cal, ICAL_ORGANIZER_PROPERTY);
2254                 if (organizer != NULL) {
2255                         if (icalproperty_get_organizer(organizer)) {
2256                                 strcpy(organizer_string,
2257                                         icalproperty_get_organizer(organizer));
2258                         }
2259                 }
2260                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
2261                         strcpy(organizer_string, &organizer_string[7]);
2262                         striplt(organizer_string);
2263                         /*
2264                          * If the user saving the event is listed as the
2265                          * organizer, then send out invitations.
2266                          */
2267                         if (CtdlIsMe(organizer_string, sizeof organizer_string)) {
2268                                 ical_send_out_invitations(top_level_cal, cal);
2269                         }
2270                 }
2271         }
2272
2273         /* If the component has subcomponents, recurse through them. */
2274         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
2275             (c != NULL);
2276             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
2277                 /* Recursively process subcomponent */
2278                 ical_saving_vevent(top_level_cal, c);
2279         }
2280
2281 }
2282
2283
2284
2285 /*
2286  * Back end for ical_obj_beforesave()
2287  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
2288  * the summary of the event (becomes message subject),
2289  * and the start time (becomes message date/time).
2290  */
2291 void ical_obj_beforesave_backend(char *name, char *filename, char *partnum,
2292                 char *disp, void *content, char *cbtype, char *cbcharset, size_t length,
2293                 char *encoding, char *cbid, void *cbuserdata)
2294 {
2295         icalcomponent *cal, *nested_event, *nested_todo, *whole_cal;
2296         icalproperty *p;
2297         char new_uid[256] = "";
2298         char buf[1024] = "";
2299         struct CtdlMessage *msg = (struct CtdlMessage *) cbuserdata;
2300
2301         if (!msg) return;
2302
2303         /* We're only interested in calendar data. */
2304         if (  (strcasecmp(cbtype, "text/calendar"))
2305            && (strcasecmp(cbtype, "application/ics")) ) {
2306                 return;
2307         }
2308
2309         /* Hunt for the UID and drop it in
2310          * the "user data" pointer for the MIME parser.  When
2311          * ical_obj_beforesave() sees it there, it'll set the Exclusive msgid
2312          * to that string.
2313          */
2314         whole_cal = icalcomponent_new_from_string(content);
2315         cal = whole_cal;
2316         if (cal != NULL) {
2317                 if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
2318                         nested_event = icalcomponent_get_first_component(
2319                                 cal, ICAL_VEVENT_COMPONENT);
2320                         if (nested_event != NULL) {
2321                                 cal = nested_event;
2322                         }
2323                         else {
2324                                 nested_todo = icalcomponent_get_first_component(
2325                                         cal, ICAL_VTODO_COMPONENT);
2326                                 if (nested_todo != NULL) {
2327                                         cal = nested_todo;
2328                                 }
2329                         }
2330                 }
2331                 
2332                 if (cal != NULL) {
2333
2334                         /* Set the message EUID to the iCalendar UID */
2335
2336                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
2337                         if (p == NULL) {
2338                                 /* If there's no uid we must generate one */
2339                                 generate_uuid(new_uid);
2340                                 icalcomponent_add_property(cal, icalproperty_new_uid(new_uid));
2341                                 p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
2342                         }
2343                         if (p != NULL) {
2344                                 safestrncpy(buf, icalproperty_get_comment(p), sizeof buf);
2345                                 if (!IsEmptyStr(buf)) {
2346                                         if (msg->cm_fields['E'] != NULL) {
2347                                                 free(msg->cm_fields['E']);
2348                                         }
2349                                         msg->cm_fields['E'] = strdup(buf);
2350                                         CtdlLogPrintf(CTDL_DEBUG, "Saving calendar UID <%s>\n", buf);
2351                                 }
2352                         }
2353
2354                         /* Set the message subject to the iCalendar summary */
2355
2356                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
2357                         if (p != NULL) {
2358                                 safestrncpy(buf, icalproperty_get_comment(p), sizeof buf);
2359                                 if (!IsEmptyStr(buf)) {
2360                                         if (msg->cm_fields['U'] != NULL) {
2361                                                 free(msg->cm_fields['U']);
2362                                         }
2363                                         msg->cm_fields['U'] = strdup(buf);
2364                                 }
2365                         }
2366
2367                         /* Set the message date/time to the iCalendar start time */
2368
2369                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
2370                         if (p != NULL) {
2371                                 time_t idtstart;
2372                                 idtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
2373                                 if (idtstart > 0) {
2374                                         if (msg->cm_fields['T'] != NULL) {
2375                                                 free(msg->cm_fields['T']);
2376                                         }
2377                                         msg->cm_fields['T'] = strdup("000000000000000000");
2378                                         sprintf(msg->cm_fields['T'], "%ld", idtstart);
2379                                 }
2380                         }
2381
2382                 }
2383                 icalcomponent_free(cal);
2384                 if (whole_cal != cal) {
2385                         icalcomponent_free(whole_cal);
2386                 }
2387         }
2388 }
2389
2390
2391
2392
2393 /*
2394  * See if we need to prevent the object from being saved (we don't allow
2395  * MIME types other than text/calendar in "calendar" or "tasks" rooms).
2396  *
2397  * If the message is being saved, we also set various message header fields
2398  * using data found in the iCalendar object.
2399  */
2400 int ical_obj_beforesave(struct CtdlMessage *msg)
2401 {
2402         /* First determine if this is a calendar or tasks room */
2403         if (  (CC->room.QRdefaultview != VIEW_CALENDAR)
2404            && (CC->room.QRdefaultview != VIEW_TASKS)
2405         ) {
2406                 return(0);              /* Not an iCalendar-centric room */
2407         }
2408
2409         /* It must be an RFC822 message! */
2410         if (msg->cm_format_type != 4) {
2411                 CtdlLogPrintf(CTDL_DEBUG, "Rejecting non-RFC822 message\n");
2412                 return(1);              /* You tried to save a non-RFC822 message! */
2413         }
2414
2415         if (msg->cm_fields['M'] == NULL) {
2416                 return(1);              /* You tried to save a null message! */
2417         }
2418
2419         /* Do all of our lovely back-end parsing */
2420         mime_parser(msg->cm_fields['M'],
2421                 NULL,
2422                 *ical_obj_beforesave_backend,
2423                 NULL, NULL,
2424                 (void *)msg,
2425                 0
2426         );
2427
2428         return(0);
2429 }
2430
2431
2432 /*
2433  * Things we need to do after saving a calendar event.
2434  */
2435 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
2436                 char *disp, void *content, char *cbtype, char *cbcharset, size_t length,
2437                 char *encoding, char *cbid, void *cbuserdata)
2438 {
2439         icalcomponent *cal;
2440
2441         /* We're only interested in calendar items here. */
2442         if (  (strcasecmp(cbtype, "text/calendar"))
2443            && (strcasecmp(cbtype, "application/ics")) ) {
2444                 return;
2445         }
2446
2447         /* Hunt for the UID and drop it in
2448          * the "user data" pointer for the MIME parser.  When
2449          * ical_obj_beforesave() sees it there, it'll set the Exclusive msgid
2450          * to that string.
2451          */
2452         if (  (!strcasecmp(cbtype, "text/calendar"))
2453            || (!strcasecmp(cbtype, "application/ics")) ) {
2454                 cal = icalcomponent_new_from_string(content);
2455                 if (cal != NULL) {
2456                         ical_saving_vevent(cal, cal);
2457                         icalcomponent_free(cal);
2458                 }
2459         }
2460 }
2461
2462
2463 /* 
2464  * Things we need to do after saving a calendar event.
2465  * (This will start back end tasks such as automatic generation of invitations,
2466  * if such actions are appropriate.)
2467  */
2468 int ical_obj_aftersave(struct CtdlMessage *msg)
2469 {
2470         char roomname[ROOMNAMELEN];
2471
2472         /*
2473          * If this isn't the Calendar> room, no further action is necessary.
2474          */
2475
2476         /* First determine if this is our room */
2477         MailboxName(roomname, sizeof roomname, &CC->user, USERCALENDARROOM);
2478         if (strcasecmp(roomname, CC->room.QRname)) {
2479                 return(0);      /* Not the Calendar room -- don't do anything. */
2480         }
2481
2482         /* It must be an RFC822 message! */
2483         if (msg->cm_format_type != 4) return(1);
2484
2485         /* Reject null messages */
2486         if (msg->cm_fields['M'] == NULL) return(1);
2487         
2488         /* Now recurse through it looking for our icalendar data */
2489         mime_parser(msg->cm_fields['M'],
2490                 NULL,
2491                 *ical_obj_aftersave_backend,
2492                 NULL, NULL,
2493                 NULL,
2494                 0
2495         );
2496
2497         return(0);
2498 }
2499
2500
2501 void ical_session_startup(void) {
2502         CIT_ICAL = malloc(sizeof(struct cit_ical));
2503         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
2504 }
2505
2506 void ical_session_shutdown(void) {
2507         free(CIT_ICAL);
2508 }
2509
2510
2511 /*
2512  * Back end for ical_fixed_output()
2513  */
2514 void ical_fixed_output_backend(icalcomponent *cal,
2515                         int recursion_level
2516 ) {
2517         icalcomponent *c;
2518         icalproperty *p;
2519         char buf[256];
2520
2521         p = icalcomponent_get_first_property(cal, ICAL_SUMMARY_PROPERTY);
2522         if (p != NULL) {
2523                 cprintf("%s\n", (const char *)icalproperty_get_comment(p));
2524         }
2525
2526         p = icalcomponent_get_first_property(cal, ICAL_LOCATION_PROPERTY);
2527         if (p != NULL) {
2528                 cprintf("%s\n", (const char *)icalproperty_get_comment(p));
2529         }
2530
2531         p = icalcomponent_get_first_property(cal, ICAL_DESCRIPTION_PROPERTY);
2532         if (p != NULL) {
2533                 cprintf("%s\n", (const char *)icalproperty_get_comment(p));
2534         }
2535
2536         /* If the component has attendees, iterate through them. */
2537         for (p = icalcomponent_get_first_property(cal, ICAL_ATTENDEE_PROPERTY); (p != NULL); p = icalcomponent_get_next_property(cal, ICAL_ATTENDEE_PROPERTY)) {
2538                 safestrncpy(buf, icalproperty_get_attendee(p), sizeof buf);
2539                 if (!strncasecmp(buf, "MAILTO:", 7)) {
2540
2541                         /* screen name or email address */
2542                         strcpy(buf, &buf[7]);
2543                         striplt(buf);
2544                         cprintf("%s ", buf);
2545                 }
2546                 cprintf("\n");
2547         }
2548
2549         /* If the component has subcomponents, recurse through them. */
2550         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
2551             (c != 0);
2552             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
2553                 /* Recursively process subcomponent */
2554                 ical_fixed_output_backend(c, recursion_level+1);
2555         }
2556 }
2557
2558
2559
2560 /*
2561  * Function to output iCalendar data as plain text.  Nobody uses MSG0
2562  * anymore, so really this is just so we expose the vCard data to the full
2563  * text indexer.
2564  */
2565 void ical_fixed_output(char *ptr, int len) {
2566         icalcomponent *cal;
2567         char *stringy_cal;
2568
2569         stringy_cal = malloc(len + 1);
2570         safestrncpy(stringy_cal, ptr, len + 1);
2571         cal = icalcomponent_new_from_string(stringy_cal);
2572         free(stringy_cal);
2573
2574         if (cal == NULL) {
2575                 return;
2576         }
2577
2578         ical_fixed_output_backend(cal, 0);
2579
2580         /* Free the memory we obtained from libical's constructor */
2581         icalcomponent_free(cal);
2582 }
2583
2584
2585
2586 void serv_calendar_destroy(void)
2587 {
2588         icaltimezone_free_builtin_timezones();
2589 }
2590
2591 /*
2592  * Register this module with the Citadel server.
2593  */
2594 CTDL_MODULE_INIT(calendar)
2595 {
2596         if (!threading)
2597         {
2598
2599                 /* Tell libical to return errors instead of aborting if it gets bad data */
2600                 icalerror_errors_are_fatal = 0;
2601
2602                 /* Use our own application prefix in tzid's generated from system tzdata */
2603                 icaltimezone_set_tzid_prefix("/citadel.org/");
2604
2605                 /* Initialize our hook functions */
2606                 CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
2607                 CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
2608                 CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
2609                 CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
2610                 CtdlRegisterSessionHook(ical_session_startup, EVT_START);
2611                 CtdlRegisterSessionHook(ical_session_shutdown, EVT_STOP);
2612                 CtdlRegisterFixedOutputHook("text/calendar", ical_fixed_output);
2613                 CtdlRegisterFixedOutputHook("application/ics", ical_fixed_output);
2614                 CtdlRegisterCleanupHook(serv_calendar_destroy);
2615         }
2616         
2617         /* return our Subversion id for the Log */
2618         return "$Id$";
2619 }