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