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