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