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