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