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