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