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