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