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