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