* Rewrite of calendar-to-freebusy conversion functions. This one creates
[citadel.git] / citadel / serv_calendar.c
1 /* 
2  * $Id$ 
3  *
4  * This module implements iCalendar object processing and the Calendar>
5  * room on a Citadel/UX 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 <unistd.h>
14 #include <sys/types.h>
15 #include <limits.h>
16 #include <stdio.h>
17 #include <string.h>
18 #ifdef HAVE_STRINGS_H
19 #include <strings.h>
20 #endif
21 #include "citadel.h"
22 #include "server.h"
23 #include "citserver.h"
24 #include "sysdep_decls.h"
25 #include "support.h"
26 #include "config.h"
27 #include "serv_extensions.h"
28 #include "user_ops.h"
29 #include "room_ops.h"
30 #include "tools.h"
31 #include "msgbase.h"
32 #include "mime_parser.h"
33 #include "serv_calendar.h"
34
35 #ifdef CITADEL_WITH_CALENDAR_SERVICE
36
37 #include <ical.h>
38 #include "ical_dezonify.h"
39
40 struct ical_respond_data {
41         char desired_partnum[SIZ];
42         icalcomponent *cal;
43 };
44
45 /* Session-local data for calendaring. */
46 long SYM_CIT_ICAL;
47
48
49 /*
50  * Utility function to create a new VCALENDAR component with some of the
51  * required fields already set the way we like them.
52  */
53 icalcomponent *icalcomponent_new_citadel_vcalendar(void) {
54         icalcomponent *encaps;
55
56         encaps = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
57         if (encaps == NULL) {
58                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
59                         __FILE__, __LINE__);
60                 return NULL;
61         }
62
63         /* Set the Product ID */
64         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
65
66         /* Set the Version Number */
67         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
68 }
69
70
71 /*
72  * Utility function to encapsulate a subcomponent into a full VCALENDAR
73  */
74 icalcomponent *ical_encapsulate_subcomponent(icalcomponent *subcomp) {
75         icalcomponent *encaps;
76
77         /* If we're already looking at a full VCALENDAR component,
78          * don't bother ... just return itself.
79          */
80         if (icalcomponent_isa(subcomp) == ICAL_VCALENDAR_COMPONENT) {
81                 return subcomp;
82         }
83
84         /* Encapsulate the VEVENT component into a complete VCALENDAR */
85         encaps = icalcomponent_new_citadel_vcalendar();
86         if (encaps == NULL) return NULL;
87
88         /* Encapsulate the subcomponent inside */
89         icalcomponent_add_component(encaps, subcomp);
90
91         /* Convert all timestamps to UTC so we don't have to deal with
92          * stupid VTIMEZONE crap.
93          */
94         ical_dezonify(encaps);
95
96         /* Return the object we just created. */
97         return(encaps);
98 }
99
100
101
102
103 /*
104  * Write a calendar object into the specified user's calendar room.
105  * 
106  * ok
107  */
108 void ical_write_to_cal(struct usersupp *u, icalcomponent *cal) {
109         char temp[PATH_MAX];
110         FILE *fp;
111         char *ser;
112         icalcomponent *encaps;
113
114         if (cal == NULL) return;
115
116         /* If the supplied object is a subcomponent, encapsulate it in
117          * a full VCALENDAR component, and save that instead.
118          */
119         if (icalcomponent_isa(cal) != ICAL_VCALENDAR_COMPONENT) {
120                 encaps = ical_encapsulate_subcomponent(
121                         icalcomponent_new_clone(cal)
122                 );
123                 ical_write_to_cal(u, encaps);
124                 icalcomponent_free(encaps);
125                 return;
126         }
127
128         strcpy(temp, tmpnam(NULL));
129         ser = icalcomponent_as_ical_string(cal);
130         if (ser == NULL) return;
131
132         /* Make a temp file out of it */
133         fp = fopen(temp, "w");
134         if (fp == NULL) return;
135         fwrite(ser, strlen(ser), 1, fp);
136         fclose(fp);
137
138         /* This handy API function does all the work for us.
139          */
140         CtdlWriteObject(USERCALENDARROOM,       /* which room */
141                         "text/calendar",        /* MIME type */
142                         temp,                   /* temp file */
143                         u,                      /* which user */
144                         0,                      /* not binary */
145                         0,              /* don't delete others of this type */
146                         0);                     /* no flags */
147
148         unlink(temp);
149 }
150
151
152 /*
153  * Add a calendar object to the user's calendar
154  * 
155  * ok because it uses ical_write_to_cal()
156  */
157 void ical_add(icalcomponent *cal, int recursion_level) {
158         icalcomponent *c;
159
160         /*
161          * The VEVENT subcomponent is the one we're interested in saving.
162          */
163         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
164         
165                 ical_write_to_cal(&CC->usersupp, cal);
166
167         }
168
169         /* If the component has subcomponents, recurse through them. */
170         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
171             (c != 0);
172             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
173                 /* Recursively process subcomponent */
174                 ical_add(c, recursion_level+1);
175         }
176
177 }
178
179
180
181 /*
182  * Send a reply to a meeting invitation.
183  *
184  * 'request' is the invitation to reply to.
185  * 'action' is the string "accept" or "decline".
186  *
187  * (Sorry about this being more than 80 columns ... there was just
188  * no easy way to break it down sensibly.)
189  * 
190  * ok
191  */
192 void ical_send_a_reply(icalcomponent *request, char *action) {
193         icalcomponent *the_reply = NULL;
194         icalcomponent *vevent = NULL;
195         icalproperty *attendee = NULL;
196         char attendee_string[SIZ];
197         icalproperty *organizer = NULL;
198         char organizer_string[SIZ];
199         icalproperty *summary = NULL;
200         char summary_string[SIZ];
201         icalproperty *me_attend = NULL;
202         struct recptypes *recp = NULL;
203         icalparameter *partstat = NULL;
204         char *serialized_reply = NULL;
205         char *reply_message_text = NULL;
206         struct CtdlMessage *msg = NULL;
207         struct recptypes *valid = NULL;
208
209         strcpy(organizer_string, "");
210         strcpy(summary_string, "Calendar item");
211
212         if (request == NULL) {
213                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
214                 return;
215         }
216
217         the_reply = icalcomponent_new_clone(request);
218         if (the_reply == NULL) {
219                 lprintf(3, "ERROR: cannot clone request\n");
220                 return;
221         }
222
223         /* Change the method from REQUEST to REPLY */
224         icalcomponent_set_method(the_reply, ICAL_METHOD_REPLY);
225
226         vevent = icalcomponent_get_first_component(the_reply, ICAL_VEVENT_COMPONENT);
227         if (vevent != NULL) {
228                 /* Hunt for attendees, removing ones that aren't us.
229                  * (Actually, remove them all, cloning our own one so we can
230                  * re-insert it later)
231                  */
232                 while (attendee = icalcomponent_get_first_property(vevent,
233                     ICAL_ATTENDEE_PROPERTY), (attendee != NULL)
234                 ) {
235                         if (icalproperty_get_attendee(attendee)) {
236                                 strcpy(attendee_string,
237                                         icalproperty_get_attendee(attendee) );
238                                 if (!strncasecmp(attendee_string, "MAILTO:", 7)) {
239                                         strcpy(attendee_string, &attendee_string[7]);
240                                         striplt(attendee_string);
241                                         recp = validate_recipients(attendee_string);
242                                         if (recp != NULL) {
243                                                 if (!strcasecmp(recp->recp_local, CC->usersupp.fullname)) {
244                                                         if (me_attend) icalproperty_free(me_attend);
245                                                         me_attend = icalproperty_new_clone(attendee);
246                                                 }
247                                                 phree(recp);
248                                         }
249                                 }
250                         }
251                         /* Remove it... */
252                         icalcomponent_remove_property(vevent, attendee);
253                         icalproperty_free(attendee);
254                 }
255
256                 /* We found our own address in the attendee list. */
257                 if (me_attend) {
258                         /* Change the partstat from NEEDS-ACTION to ACCEPT or DECLINE */
259                         icalproperty_remove_parameter(me_attend, ICAL_PARTSTAT_PARAMETER);
260
261                         if (!strcasecmp(action, "accept")) {
262                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_ACCEPTED);
263                         }
264                         else if (!strcasecmp(action, "decline")) {
265                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_DECLINED);
266                         }
267                         else if (!strcasecmp(action, "tentative")) {
268                                 partstat = icalparameter_new_partstat(ICAL_PARTSTAT_TENTATIVE);
269                         }
270
271                         if (partstat) icalproperty_add_parameter(me_attend, partstat);
272
273                         /* Now insert it back into the vevent. */
274                         icalcomponent_add_property(vevent, me_attend);
275                 }
276
277                 /* Figure out who to send this thing to */
278                 organizer = icalcomponent_get_first_property(vevent, ICAL_ORGANIZER_PROPERTY);
279                 if (organizer != NULL) {
280                         if (icalproperty_get_organizer(organizer)) {
281                                 strcpy(organizer_string,
282                                         icalproperty_get_organizer(organizer) );
283                         }
284                 }
285                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
286                         strcpy(organizer_string, &organizer_string[7]);
287                         striplt(organizer_string);
288                 } else {
289                         strcpy(organizer_string, "");
290                 }
291
292                 /* Extract the summary string -- we'll use it as the
293                  * message subject for the reply
294                  */
295                 summary = icalcomponent_get_first_property(vevent, ICAL_SUMMARY_PROPERTY);
296                 if (summary != NULL) {
297                         if (icalproperty_get_summary(summary)) {
298                                 strcpy(summary_string,
299                                         icalproperty_get_summary(summary) );
300                         }
301                 }
302
303         }
304
305         /* Now generate the reply message and send it out. */
306         serialized_reply = strdoop(icalcomponent_as_ical_string(the_reply));
307         icalcomponent_free(the_reply);  /* don't need this anymore */
308         if (serialized_reply == NULL) return;
309
310         reply_message_text = mallok(strlen(serialized_reply) + SIZ);
311         if (reply_message_text != NULL) {
312                 sprintf(reply_message_text,
313                         "Content-type: text/calendar\r\n\r\n%s\r\n",
314                         serialized_reply
315                 );
316
317                 msg = CtdlMakeMessage(&CC->usersupp, organizer_string,
318                         CC->quickroom.QRname, 0, FMT_RFC822,
319                         "",
320                         summary_string,         /* Use summary for subject */
321                         reply_message_text);
322         
323                 if (msg != NULL) {
324                         valid = validate_recipients(organizer_string);
325                         CtdlSubmitMsg(msg, valid, "");
326                         CtdlFreeMessage(msg);
327                 }
328         }
329         phree(serialized_reply);
330 }
331
332
333
334 /*
335  * Callback function for mime parser that hunts for calendar content types
336  * and turns them into calendar objects
337  */
338 void ical_locate_part(char *name, char *filename, char *partnum, char *disp,
339                 void *content, char *cbtype, size_t length, char *encoding,
340                 void *cbuserdata) {
341
342         struct ical_respond_data *ird = NULL;
343
344         ird = (struct ical_respond_data *) cbuserdata;
345
346         /* desired_partnum can be set to "_HUNT_" to have it just look for
347          * the first part with a content type of text/calendar.  Otherwise
348          * we have to only process the right one.
349          */
350         if (strcasecmp(ird->desired_partnum, "_HUNT_")) {
351                 if (strcasecmp(partnum, ird->desired_partnum)) {
352                         return;
353                 }
354         }
355
356         if (strcasecmp(cbtype, "text/calendar")) {
357                 return;
358         }
359
360         if (ird->cal != NULL) {
361                 icalcomponent_free(ird->cal);
362                 ird->cal = NULL;
363         }
364
365         ird->cal = icalcomponent_new_from_string(content);
366         if (ird->cal != NULL) {
367                 ical_dezonify(ird->cal);
368         }
369 }
370
371
372 /*
373  * Respond to a meeting request.
374  */
375 void ical_respond(long msgnum, char *partnum, char *action) {
376         struct CtdlMessage *msg;
377         struct ical_respond_data ird;
378
379         if (
380            (strcasecmp(action, "accept"))
381            && (strcasecmp(action, "decline"))
382         ) {
383                 cprintf("%d Action must be 'accept' or 'decline'\n",
384                         ERROR + ILLEGAL_VALUE
385                 );
386                 return;
387         }
388
389         msg = CtdlFetchMessage(msgnum);
390         if (msg == NULL) {
391                 cprintf("%d Message %ld not found.\n",
392                         ERROR+ILLEGAL_VALUE,
393                         (long)msgnum
394                 );
395                 return;
396         }
397
398         memset(&ird, 0, sizeof ird);
399         strcpy(ird.desired_partnum, partnum);
400         mime_parser(msg->cm_fields['M'],
401                 NULL,
402                 *ical_locate_part,              /* callback function */
403                 NULL, NULL,
404                 (void *) &ird,                  /* user data */
405                 0
406         );
407
408         /* We're done with the incoming message, because we now have a
409          * calendar object in memory.
410          */
411         CtdlFreeMessage(msg);
412
413         /*
414          * Here is the real meat of this function.  Handle the event.
415          */
416         if (ird.cal != NULL) {
417                 /* Save this in the user's calendar if necessary */
418                 if (!strcasecmp(action, "accept")) {
419                         ical_add(ird.cal, 0);
420                 }
421
422                 /* Send a reply if necessary */
423                 if (icalcomponent_get_method(ird.cal) == ICAL_METHOD_REQUEST) {
424                         ical_send_a_reply(ird.cal, action);
425                 }
426
427                 /* Now that we've processed this message, we don't need it
428                  * anymore.  So delete it.
429                  */
430                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
431
432                 /* Free the memory we allocated and return a response. */
433                 icalcomponent_free(ird.cal);
434                 ird.cal = NULL;
435                 cprintf("%d ok\n", CIT_OK);
436                 return;
437         }
438         else {
439                 cprintf("%d No calendar object found\n", ERROR);
440                 return;
441         }
442
443         /* should never get here */
444 }
445
446
447 /*
448  * Figure out the UID of the calendar event being referred to in a
449  * REPLY object.  This function is recursive.
450  */
451 void ical_learn_uid_of_reply(char *uidbuf, icalcomponent *cal) {
452         icalcomponent *subcomponent;
453         icalproperty *p;
454
455         /* If this object is a REPLY, then extract the UID. */
456         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
457                 p = icalcomponent_get_first_property(cal, ICAL_UID_PROPERTY);
458                 if (p != NULL) {
459                         strcpy(uidbuf, icalproperty_get_comment(p));
460                 }
461         }
462
463         /* Otherwise, recurse through any VEVENT subcomponents.  We do NOT want the
464          * UID of the reply; we want the UID of the invitation being replied to.
465          */
466         for (subcomponent = icalcomponent_get_first_component(cal, ICAL_VEVENT_COMPONENT);
467             subcomponent != NULL;
468             subcomponent = icalcomponent_get_next_component(cal, ICAL_VEVENT_COMPONENT) ) {
469                 ical_learn_uid_of_reply(uidbuf, subcomponent);
470         }
471 }
472
473
474 /*
475  * ical_update_my_calendar_with_reply() refers to this callback function; when we
476  * locate the message containing the calendar event we're replying to, this function
477  * gets called.  It basically just sticks the message number in a supplied buffer.
478  */
479 void ical_hunt_for_event_to_update(long msgnum, void *data) {
480         long *msgnumptr;
481
482         msgnumptr = (long *) data;
483         *msgnumptr = msgnum;
484 }
485
486
487 struct original_event_container {
488         icalcomponent *c;
489 };
490
491 /*
492  * Callback function for mime parser that hunts for calendar content types
493  * and turns them into calendar objects (called by ical_update_my_calendar_with_reply()
494  * to fetch the object being updated)
495  */
496 void ical_locate_original_event(char *name, char *filename, char *partnum, char *disp,
497                 void *content, char *cbtype, size_t length, char *encoding,
498                 void *cbuserdata) {
499
500         struct original_event_container *oec = NULL;
501
502         if (strcasecmp(cbtype, "text/calendar")) {
503                 return;
504         }
505         oec = (struct original_event_container *) cbuserdata;
506         if (oec->c != NULL) {
507                 icalcomponent_free(oec->c);
508         }
509         oec->c = icalcomponent_new_from_string(content);
510 }
511
512
513 /*
514  * Merge updated attendee information from a REPLY into an existing event.
515  */
516 void ical_merge_attendee_reply(icalcomponent *event, icalcomponent *reply) {
517         icalcomponent *c;
518         icalproperty *e_attendee, *r_attendee;
519
520         /* First things first.  If we're not looking at a VEVENT component,
521          * recurse through subcomponents until we find one.
522          */
523         if (icalcomponent_isa(event) != ICAL_VEVENT_COMPONENT) {
524                 for (c = icalcomponent_get_first_component(event, ICAL_VEVENT_COMPONENT);
525                     c != NULL;
526                     c = icalcomponent_get_next_component(event, ICAL_VEVENT_COMPONENT) ) {
527                         ical_merge_attendee_reply(c, reply);
528                 }
529                 return;
530         }
531
532         /* Now do the same thing with the reply.
533          */
534         if (icalcomponent_isa(reply) != ICAL_VEVENT_COMPONENT) {
535                 for (c = icalcomponent_get_first_component(reply, ICAL_VEVENT_COMPONENT);
536                     c != NULL;
537                     c = icalcomponent_get_next_component(reply, ICAL_VEVENT_COMPONENT) ) {
538                         ical_merge_attendee_reply(event, c);
539                 }
540                 return;
541         }
542
543         /* Clone the reply, because we're going to rip its guts out. */
544         reply = icalcomponent_new_clone(reply);
545
546         /* At this point we're looking at the correct subcomponents.
547          * Iterate through the attendees looking for a match.
548          */
549 STARTOVER:
550         for (e_attendee = icalcomponent_get_first_property(event, ICAL_ATTENDEE_PROPERTY);
551             e_attendee != NULL;
552             e_attendee = icalcomponent_get_next_property(event, ICAL_ATTENDEE_PROPERTY)) {
553
554                 for (r_attendee = icalcomponent_get_first_property(reply, ICAL_ATTENDEE_PROPERTY);
555                     r_attendee != NULL;
556                     r_attendee = icalcomponent_get_next_property(reply, ICAL_ATTENDEE_PROPERTY)) {
557
558                         /* Check to see if these two attendees match...
559                          */
560                         if (!strcasecmp(
561                            icalproperty_get_attendee(e_attendee),
562                            icalproperty_get_attendee(r_attendee)
563                         )) {
564                                 /* ...and if they do, remove the attendee from the event
565                                  * and replace it with the attendee from the reply.  (The
566                                  * reply's copy will have the same address, but an updated
567                                  * status.)
568                                  */
569                                 TRACE;
570                                 icalcomponent_remove_property(event, e_attendee);
571                                 TRACE;
572                                 icalproperty_free(e_attendee);
573                                 TRACE;
574                                 icalcomponent_remove_property(reply, r_attendee);
575                                 TRACE;
576                                 icalcomponent_add_property(event, r_attendee);
577                                 TRACE;
578
579                                 /* Since we diddled both sets of attendees, we have to start
580                                  * the iteration over again.  This will not create an infinite
581                                  * loop because we removed the attendee from the reply.  (That's
582                                  * why we cloned the reply, and that's what we mean by "ripping
583                                  * its guts out.")
584                                  */
585                                 goto STARTOVER;
586                         }
587         
588                 }
589         }
590
591         /* Free the *clone* of the reply. */
592         icalcomponent_free(reply);
593 }
594
595
596
597
598 /*
599  * Handle an incoming RSVP (object with method==ICAL_METHOD_REPLY) for a
600  * calendar event.  The object has already been deserialized for us; all
601  * we have to do here is hunt for the event in our calendar, merge in the
602  * updated attendee status, and save it again.
603  *
604  * This function returns 0 on success, 1 if the event was not found in the
605  * user's calendar, or 2 if an internal error occurred.
606  */
607 int ical_update_my_calendar_with_reply(icalcomponent *cal) {
608         char uid[SIZ];
609         char hold_rm[ROOMNAMELEN];
610         long msgnum_being_replaced = 0;
611         struct CtdlMessage *template = NULL;
612         struct CtdlMessage *msg;
613         struct original_event_container oec;
614         icalcomponent *original_event;
615         char *serialized_event = NULL;
616         char roomname[ROOMNAMELEN];
617         char *message_text = NULL;
618
619         /* Figure out just what event it is we're dealing with */
620         strcpy(uid, "--==<< InVaLiD uId >>==--");
621         ical_learn_uid_of_reply(uid, cal);
622         lprintf(9, "UID of event being replied to is <%s>\n", uid);
623
624         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
625
626         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
627                 getroom(&CC->quickroom, hold_rm);
628                 lprintf(3, "cannot get user calendar room\n");
629                 return(2);
630         }
631
632         /*
633          * Pound through the user's calendar looking for a message with
634          * the Citadel EUID set to the value we're looking for.  Since
635          * Citadel always sets the message EUID to the vCalendar UID of
636          * the event, this will work.
637          */
638         template = (struct CtdlMessage *)
639                 mallok(sizeof(struct CtdlMessage));
640         memset(template, 0, sizeof(struct CtdlMessage));
641         template->cm_fields['E'] = strdoop(uid);
642         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
643                 template, ical_hunt_for_event_to_update, &msgnum_being_replaced);
644         CtdlFreeMessage(template);
645         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
646
647         lprintf(9, "msgnum_being_replaced == %ld\n", msgnum_being_replaced);
648         if (msgnum_being_replaced == 0) {
649                 return(1);                      /* no calendar event found */
650         }
651
652         /* Now we know the ID of the message containing the event being updated.
653          * We don't actually have to delete it; that'll get taken care of by the
654          * server when we save another event with the same UID.  This just gives
655          * us the ability to load the event into memory so we can diddle the
656          * attendees.
657          */
658         msg = CtdlFetchMessage(msgnum_being_replaced);
659         if (msg == NULL) {
660                 return(2);                      /* internal error */
661         }
662         oec.c = NULL;
663         mime_parser(msg->cm_fields['M'],
664                 NULL,
665                 *ical_locate_original_event,    /* callback function */
666                 NULL, NULL,
667                 &oec,                           /* user data */
668                 0
669         );
670         CtdlFreeMessage(msg);
671
672         original_event = oec.c;
673         if (original_event == NULL) {
674                 lprintf(3, "ERROR: Original_component is NULL.\n");
675                 return(2);
676         }
677
678         /* Merge the attendee's updated status into the event */
679         ical_merge_attendee_reply(original_event, cal);
680
681         /* Serialize it */
682         serialized_event = strdoop(icalcomponent_as_ical_string(original_event));
683         icalcomponent_free(original_event);     /* Don't need this anymore. */
684         if (serialized_event == NULL) return(2);
685
686         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
687
688         message_text = mallok(strlen(serialized_event) + SIZ);
689         if (message_text != NULL) {
690                 sprintf(message_text,
691                         "Content-type: text/calendar\r\n\r\n%s\r\n",
692                         serialized_event
693                 );
694
695                 msg = CtdlMakeMessage(&CC->usersupp,
696                         "",                     /* No recipient */
697                         roomname,
698                         0, FMT_RFC822,
699                         "",
700                         "",             /* no subject */
701                         message_text);
702         
703                 if (msg != NULL) {
704                         CIT_ICAL->avoid_sending_invitations = 1;
705                         CtdlSubmitMsg(msg, NULL, roomname);
706                         CtdlFreeMessage(msg);
707                         CIT_ICAL->avoid_sending_invitations = 0;
708                 }
709         }
710         phree(serialized_event);
711         return(0);
712 }
713
714
715 /*
716  * Handle an incoming RSVP for an event.  (This is the server subcommand part; it
717  * simply extracts the calendar object from the message, deserializes it, and
718  * passes it up to ical_update_my_calendar_with_reply() for processing.
719  */
720 void ical_handle_rsvp(long msgnum, char *partnum, char *action) {
721         struct CtdlMessage *msg;
722         struct ical_respond_data ird;
723         int ret;
724
725         if (
726            (strcasecmp(action, "update"))
727            && (strcasecmp(action, "ignore"))
728         ) {
729                 cprintf("%d Action must be 'update' or 'ignore'\n",
730                         ERROR + ILLEGAL_VALUE
731                 );
732                 return;
733         }
734
735         msg = CtdlFetchMessage(msgnum);
736         if (msg == NULL) {
737                 cprintf("%d Message %ld not found.\n",
738                         ERROR+ILLEGAL_VALUE,
739                         (long)msgnum
740                 );
741                 return;
742         }
743
744         memset(&ird, 0, sizeof ird);
745         strcpy(ird.desired_partnum, partnum);
746         mime_parser(msg->cm_fields['M'],
747                 NULL,
748                 *ical_locate_part,              /* callback function */
749                 NULL, NULL,
750                 (void *) &ird,                  /* user data */
751                 0
752         );
753
754         /* We're done with the incoming message, because we now have a
755          * calendar object in memory.
756          */
757         CtdlFreeMessage(msg);
758
759         /*
760          * Here is the real meat of this function.  Handle the event.
761          */
762         if (ird.cal != NULL) {
763                 /* Update the user's calendar if necessary */
764                 if (!strcasecmp(action, "update")) {
765                         ret = ical_update_my_calendar_with_reply(ird.cal);
766                         if (ret == 0) {
767                                 cprintf("%d Your calendar has been updated with this reply.\n",
768                                         CIT_OK);
769                         }
770                         else if (ret == 1) {
771                                 cprintf("%d This event does not exist in your calendar.\n",
772                                         ERROR + FILE_NOT_FOUND);
773                         }
774                         else {
775                                 cprintf("%d An internal error occurred.\n",
776                                         ERROR + INTERNAL_ERROR);
777                         }
778                 }
779                 else {
780                         cprintf("%d This reply has been ignored.\n", CIT_OK);
781                 }
782
783                 /* Now that we've processed this message, we don't need it
784                  * anymore.  So delete it.  (Maybe make this optional?)
785                  */
786                 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
787
788                 /* Free the memory we allocated and return a response. */
789                 icalcomponent_free(ird.cal);
790                 ird.cal = NULL;
791                 return;
792         }
793         else {
794                 cprintf("%d No calendar object found\n", ERROR);
795                 return;
796         }
797
798         /* should never get here */
799 }
800
801
802 /*
803  * Search for a property in both the top level and in a VEVENT subcomponent
804  */
805 icalproperty *ical_ctdl_get_subprop(
806                 icalcomponent *cal,
807                 icalproperty_kind which_prop
808 ) {
809         icalproperty *p;
810         icalcomponent *c;
811
812         p = icalcomponent_get_first_property(cal, which_prop);
813         if (p == NULL) {
814                 c = icalcomponent_get_first_component(cal,
815                                                         ICAL_VEVENT_COMPONENT);
816                 if (c != NULL) {
817                         p = icalcomponent_get_first_property(c, which_prop);
818                 }
819         }
820         return p;
821 }
822
823
824 /*
825  * Check to see if two events overlap.  Returns nonzero if they do.
826  */
827 int ical_ctdl_is_overlap(
828                         struct icaltimetype t1start,
829                         struct icaltimetype t1end,
830                         struct icaltimetype t2start,
831                         struct icaltimetype t2end
832 ) {
833
834         if (icaltime_is_null_time(t1start)) return(0);
835         if (icaltime_is_null_time(t2start)) return(0);
836
837         /* First, check for all-day events */
838         if (t1start.is_date) {
839                 if (!icaltime_compare_date_only(t1start, t2start)) {
840                         return(1);
841                 }
842                 if (!icaltime_is_null_time(t2end)) {
843                         if (!icaltime_compare_date_only(t1start, t2end)) {
844                                 return(1);
845                         }
846                 }
847         }
848
849         if (t2start.is_date) {
850                 if (!icaltime_compare_date_only(t2start, t1start)) {
851                         return(1);
852                 }
853                 if (!icaltime_is_null_time(t1end)) {
854                         if (!icaltime_compare_date_only(t2start, t1end)) {
855                                 return(1);
856                         }
857                 }
858         }
859
860         /* Now check for overlaps using date *and* time. */
861
862         /* First, bail out if either event 1 or event 2 is missing end time. */
863         if (icaltime_is_null_time(t1end)) return(0);
864         if (icaltime_is_null_time(t2end)) return(0);
865
866         /* If event 1 ends before event 2 starts, we're in the clear. */
867         if (icaltime_compare(t1end, t2start) <= 0) return(0);
868
869         /* If event 2 ends before event 1 starts, we're also ok. */
870         if (icaltime_compare(t2end, t1start) <= 0) return(0);
871
872         /* Otherwise, they overlap. */
873         return(1);
874 }
875
876
877
878 /*
879  * Backend for ical_hunt_for_conflicts()
880  */
881 void ical_hunt_for_conflicts_backend(long msgnum, void *data) {
882         icalcomponent *cal;
883         struct CtdlMessage *msg;
884         struct ical_respond_data ird;
885         struct icaltimetype t1start, t1end, t2start, t2end;
886         icalproperty *p;
887         char conflict_event_uid[SIZ];
888         char conflict_event_summary[SIZ];
889         char compare_uid[SIZ];
890
891         cal = (icalcomponent *)data;
892         strcpy(compare_uid, "");
893         strcpy(conflict_event_uid, "");
894         strcpy(conflict_event_summary, "");
895
896         msg = CtdlFetchMessage(msgnum);
897         if (msg == NULL) return;
898         memset(&ird, 0, sizeof ird);
899         strcpy(ird.desired_partnum, "_HUNT_");
900         mime_parser(msg->cm_fields['M'],
901                 NULL,
902                 *ical_locate_part,              /* callback function */
903                 NULL, NULL,
904                 (void *) &ird,                  /* user data */
905                 0
906         );
907         CtdlFreeMessage(msg);
908
909         if (ird.cal == NULL) return;
910
911         t1start = icaltime_null_time();
912         t1end = icaltime_null_time();
913         t2start = icaltime_null_time();
914         t1end = icaltime_null_time();
915
916         /* Now compare cal to ird.cal */
917         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTSTART_PROPERTY);
918         if (p == NULL) return;
919         if (p != NULL) t2start = icalproperty_get_dtstart(p);
920         
921         p = ical_ctdl_get_subprop(ird.cal, ICAL_DTEND_PROPERTY);
922         if (p != NULL) t2end = icalproperty_get_dtend(p);
923
924         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
925         if (p == NULL) return;
926         if (p != NULL) t1start = icalproperty_get_dtstart(p);
927         
928         p = ical_ctdl_get_subprop(cal, ICAL_DTEND_PROPERTY);
929         if (p != NULL) t1end = icalproperty_get_dtend(p);
930         
931         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
932         if (p != NULL) {
933                 strcpy(compare_uid, icalproperty_get_comment(p));
934         }
935
936         p = ical_ctdl_get_subprop(ird.cal, ICAL_UID_PROPERTY);
937         if (p != NULL) {
938                 strcpy(conflict_event_uid, icalproperty_get_comment(p));
939         }
940
941         p = ical_ctdl_get_subprop(ird.cal, ICAL_SUMMARY_PROPERTY);
942         if (p != NULL) {
943                 strcpy(conflict_event_summary, icalproperty_get_comment(p));
944         }
945
946         icalcomponent_free(ird.cal);
947
948         if (ical_ctdl_is_overlap(t1start, t1end, t2start, t2end)) {
949                 cprintf("%ld||%s|%s|%d|\n",
950                         msgnum,
951                         conflict_event_uid,
952                         conflict_event_summary,
953                         (       ((strlen(compare_uid)>0)
954                                 &&(!strcasecmp(compare_uid,
955                                 conflict_event_uid))) ? 1 : 0
956                         )
957                 );
958         }
959 }
960
961
962
963 /* 
964  * Phase 2 of "hunt for conflicts" operation.
965  * At this point we have a calendar object which represents the VEVENT that
966  * we're considering adding to the calendar.  Now hunt through the user's
967  * calendar room, and output zero or more existing VEVENTs which conflict
968  * with this one.
969  */
970 void ical_hunt_for_conflicts(icalcomponent *cal) {
971         char hold_rm[ROOMNAMELEN];
972
973         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
974
975         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
976                 getroom(&CC->quickroom, hold_rm);
977                 cprintf("%d You do not have a calendar.\n", ERROR);
978                 return;
979         }
980
981         cprintf("%d Conflicting events:\n", LISTING_FOLLOWS);
982
983         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
984                 NULL,
985                 ical_hunt_for_conflicts_backend,
986                 (void *) cal
987         );
988
989         cprintf("000\n");
990         getroom(&CC->quickroom, hold_rm);       /* return to saved room */
991
992 }
993
994
995
996 /*
997  * Hunt for conflicts (Phase 1 -- retrieve the object and call Phase 2)
998  */
999 void ical_conflicts(long msgnum, char *partnum) {
1000         struct CtdlMessage *msg;
1001         struct ical_respond_data ird;
1002
1003         msg = CtdlFetchMessage(msgnum);
1004         if (msg == NULL) {
1005                 cprintf("%d Message %ld not found.\n",
1006                         ERROR+ILLEGAL_VALUE,
1007                         (long)msgnum
1008                 );
1009                 return;
1010         }
1011
1012         memset(&ird, 0, sizeof ird);
1013         strcpy(ird.desired_partnum, partnum);
1014         mime_parser(msg->cm_fields['M'],
1015                 NULL,
1016                 *ical_locate_part,              /* callback function */
1017                 NULL, NULL,
1018                 (void *) &ird,                  /* user data */
1019                 0
1020         );
1021
1022         CtdlFreeMessage(msg);
1023
1024         if (ird.cal != NULL) {
1025                 ical_hunt_for_conflicts(ird.cal);
1026                 icalcomponent_free(ird.cal);
1027                 return;
1028         }
1029         else {
1030                 cprintf("%d No calendar object found\n", ERROR);
1031                 return;
1032         }
1033
1034         /* should never get here */
1035 }
1036
1037
1038
1039 /*
1040  * Look for busy time in a VEVENT and add it to the supplied VFREEBUSY.
1041  */
1042 void ical_add_to_freebusy(icalcomponent *fb, icalcomponent *cal) {
1043         icalproperty *p;
1044         icalvalue *v;
1045         struct icalperiodtype my_period;
1046
1047         if (cal == NULL) return;
1048         my_period = icalperiodtype_null_period();
1049
1050         if (icalcomponent_isa(cal) != ICAL_VEVENT_COMPONENT) {
1051                 ical_add_to_freebusy(fb,
1052                         icalcomponent_get_first_component(
1053                                 cal, ICAL_VEVENT_COMPONENT
1054                         )
1055                 );
1056                 return;
1057         }
1058
1059         ical_dezonify(cal);
1060
1061         /* If this event is not opaque, the user isn't publishing it as
1062          * busy time, so don't bother doing anything else.
1063          */
1064         p = icalcomponent_get_first_property(cal, ICAL_TRANSP_PROPERTY);
1065         if (p != NULL) {
1066                 v = icalproperty_get_value(p);
1067                 if (v != NULL) {
1068                         if (icalvalue_get_transp(v) != ICAL_TRANSP_OPAQUE) {
1069                                 return;
1070                         }
1071                 }
1072         }
1073
1074         /* Convert the DTSTART and DTEND properties to an icalperiod. */
1075         p = icalcomponent_get_first_property(cal, ICAL_DTSTART_PROPERTY);
1076         if (p != NULL) {
1077                 my_period.start = icalproperty_get_dtstart(p);
1078         }
1079
1080         p = icalcomponent_get_first_property(cal, ICAL_DTEND_PROPERTY);
1081         if (p != NULL) {
1082                 my_period.end = icalproperty_get_dtstart(p);
1083         }
1084
1085         /* Now add it. */
1086         icalcomponent_add_property(fb,
1087                 icalproperty_new_freebusy(my_period)
1088         );
1089
1090 }
1091
1092
1093
1094 /*
1095  * Backend for ical_freebusy()
1096  *
1097  * This function simply loads the messages in the user's calendar room,
1098  * which contain VEVENTs, then strips them of all non-freebusy data, and
1099  * adds them to the supplied VCALENDAR.
1100  *
1101  */
1102 void ical_freebusy_backend(long msgnum, void *data) {
1103         icalcomponent *cal;
1104         struct CtdlMessage *msg;
1105         struct ical_respond_data ird;
1106
1107         cal = (icalcomponent *)data;
1108
1109         msg = CtdlFetchMessage(msgnum);
1110         if (msg == NULL) return;
1111         memset(&ird, 0, sizeof ird);
1112         strcpy(ird.desired_partnum, "_HUNT_");
1113         mime_parser(msg->cm_fields['M'],
1114                 NULL,
1115                 *ical_locate_part,              /* callback function */
1116                 NULL, NULL,
1117                 (void *) &ird,                  /* user data */
1118                 0
1119         );
1120         CtdlFreeMessage(msg);
1121
1122         if (ird.cal == NULL) return;
1123
1124         ical_add_to_freebusy(cal, ird.cal);
1125
1126         /* Now free the memory. */
1127         icalcomponent_free(ird.cal);
1128 }
1129
1130
1131
1132 /*
1133  * Grab another user's free/busy times
1134  */
1135 void ical_freebusy(char *who) {
1136         struct usersupp usbuf;
1137         char calendar_room_name[ROOMNAMELEN];
1138         char hold_rm[ROOMNAMELEN];
1139         char *serialized_request = NULL;
1140         icalcomponent *encaps = NULL;
1141         icalcomponent *fb = NULL;
1142
1143         if (getuser(&usbuf, who) != 0) {
1144                 cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1145                 return;
1146         }
1147
1148         MailboxName(calendar_room_name, sizeof calendar_room_name,
1149                 &usbuf, USERCALENDARROOM);
1150
1151         strcpy(hold_rm, CC->quickroom.QRname);  /* save current room */
1152
1153         if (getroom(&CC->quickroom, USERCALENDARROOM) != 0) {
1154                 cprintf("%d Cannot open calendar\n", ERROR+ROOM_NOT_FOUND);
1155                 getroom(&CC->quickroom, hold_rm);
1156                 return;
1157         }
1158
1159
1160         /* Create a VCALENDAR in which we will encapsulate all the VFREEBUSYs */
1161         encaps = icalcomponent_new_citadel_vcalendar();
1162         if (encaps == NULL) {
1163                 cprintf("%d Internal error: cannot allocate memory.\n",
1164                         ERROR+INTERNAL_ERROR);
1165                 getroom(&CC->quickroom, hold_rm);
1166                 return;
1167         }
1168
1169         /* Create a VFREEBUSY subcomponent */
1170         fb = icalcomponent_new(ICAL_VFREEBUSY_COMPONENT);
1171         if (fb == NULL) {
1172                 cprintf("%d Internal error: cannot allocate memory.\n",
1173                         ERROR+INTERNAL_ERROR);
1174                 icalcomponent_free(encaps);
1175                 getroom(&CC->quickroom, hold_rm);
1176                 return;
1177         }
1178
1179         /* Put the freebusy component into the calendar component */
1180         icalcomponent_add_component(encaps, fb);
1181
1182         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
1183                 NULL, ical_freebusy_backend, (void *)fb
1184         );
1185
1186         /* Serialize it */
1187         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1188         icalcomponent_free(encaps);     /* Don't need this anymore. */
1189
1190         cprintf("%d Here is the free/busy data:\n", LISTING_FOLLOWS);
1191         if (serialized_request != NULL) {
1192                 client_write(serialized_request, strlen(serialized_request));
1193         }
1194         cprintf("\n000\n");
1195
1196         /* Go back to the room from which we came... */
1197         getroom(&CC->quickroom, hold_rm);
1198
1199         cprintf("%d not implemented yet\n", ERROR);
1200 }
1201
1202
1203
1204
1205 /*
1206  * All Citadel calendar commands from the client come through here.
1207  */
1208 void cmd_ical(char *argbuf)
1209 {
1210         char subcmd[SIZ];
1211         long msgnum;
1212         char partnum[SIZ];
1213         char action[SIZ];
1214         char who[SIZ];
1215
1216         if (CtdlAccessCheck(ac_logged_in)) return;
1217
1218         extract(subcmd, argbuf, 0);
1219
1220         if (!strcmp(subcmd, "test")) {
1221                 cprintf("%d This server supports calendaring\n", CIT_OK);
1222                 return;
1223         }
1224
1225         else if (!strcmp(subcmd, "respond")) {
1226                 msgnum = extract_long(argbuf, 1);
1227                 extract(partnum, argbuf, 2);
1228                 extract(action, argbuf, 3);
1229                 ical_respond(msgnum, partnum, action);
1230         }
1231
1232         else if (!strcmp(subcmd, "handle_rsvp")) {
1233                 msgnum = extract_long(argbuf, 1);
1234                 extract(partnum, argbuf, 2);
1235                 extract(action, argbuf, 3);
1236                 ical_handle_rsvp(msgnum, partnum, action);
1237         }
1238
1239         else if (!strcmp(subcmd, "conflicts")) {
1240                 msgnum = extract_long(argbuf, 1);
1241                 extract(partnum, argbuf, 2);
1242                 ical_conflicts(msgnum, partnum);
1243         }
1244
1245         else if (!strcmp(subcmd, "freebusy")) {
1246                 extract(who, argbuf, 1);
1247                 ical_freebusy(who);
1248         }
1249
1250         else {
1251                 cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
1252                 return;
1253         }
1254
1255         /* should never get here */
1256 }
1257
1258
1259
1260 /*
1261  * We don't know if the calendar room exists so we just create it at login
1262  */
1263 void ical_create_room(void)
1264 {
1265         struct quickroom qr;
1266         struct visit vbuf;
1267
1268         /* Create the calendar room if it doesn't already exist */
1269         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
1270
1271         /* Set expiration policy to manual; otherwise objects will be lost! */
1272         if (lgetroom(&qr, USERCALENDARROOM)) {
1273                 lprintf(3, "Couldn't get the user calendar room!\n");
1274                 return;
1275         }
1276         qr.QRep.expire_mode = EXPIRE_MANUAL;
1277         qr.QRdefaultview = 3;   /* 3 = calendar view */
1278         lputroom(&qr);
1279
1280         /* Set the view to a calendar view */
1281         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1282         vbuf.v_view = 3;        /* 3 = calendar */
1283         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1284
1285         /* Create the tasks list room if it doesn't already exist */
1286         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
1287
1288         /* Set expiration policy to manual; otherwise objects will be lost! */
1289         if (lgetroom(&qr, USERTASKSROOM)) {
1290                 lprintf(3, "Couldn't get the user calendar room!\n");
1291                 return;
1292         }
1293         qr.QRep.expire_mode = EXPIRE_MANUAL;
1294         qr.QRdefaultview = 4;   /* 4 = tasks view */
1295         lputroom(&qr);
1296
1297         /* Set the view to a task list view */
1298         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1299         vbuf.v_view = 4;        /* 4 = tasks */
1300         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1301
1302         return;
1303 }
1304
1305
1306 /*
1307  * ical_send_out_invitations() is called by ical_saving_vevent() when it
1308  * finds a VEVENT.
1309  */
1310 void ical_send_out_invitations(icalcomponent *cal) {
1311         icalcomponent *the_request = NULL;
1312         char *serialized_request = NULL;
1313         icalcomponent *encaps = NULL;
1314         char *request_message_text = NULL;
1315         struct CtdlMessage *msg = NULL;
1316         struct recptypes *valid = NULL;
1317         char attendees_string[SIZ];
1318         int num_attendees = 0;
1319         char this_attendee[SIZ];
1320         icalproperty *attendee = NULL;
1321         char summary_string[SIZ];
1322         icalproperty *summary = NULL;
1323
1324         if (cal == NULL) {
1325                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
1326                 return;
1327         }
1328
1329
1330         /* If this is a VCALENDAR component, look for a VEVENT subcomponent. */
1331         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1332                 ical_send_out_invitations(
1333                         icalcomponent_get_first_component(
1334                                 cal, ICAL_VEVENT_COMPONENT
1335                         )
1336                 );
1337                 return;
1338         }
1339
1340         /* Clone the event */
1341         the_request = icalcomponent_new_clone(cal);
1342         if (the_request == NULL) {
1343                 lprintf(3, "ERROR: cannot clone calendar object\n");
1344                 return;
1345         }
1346
1347         /* Extract the summary string -- we'll use it as the
1348          * message subject for the request
1349          */
1350         strcpy(summary_string, "Meeting request");
1351         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
1352         if (summary != NULL) {
1353                 if (icalproperty_get_summary(summary)) {
1354                         strcpy(summary_string,
1355                                 icalproperty_get_summary(summary) );
1356                 }
1357         }
1358
1359         /* Determine who the recipients of this message are (the attendees) */
1360         strcpy(attendees_string, "");
1361         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
1362                 if (icalproperty_get_attendee(attendee)) {
1363                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
1364                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
1365                                 strcpy(this_attendee, &this_attendee[7]);
1366                                 snprintf(&attendees_string[strlen(attendees_string)],
1367                                         sizeof(attendees_string) - strlen(attendees_string),
1368                                         "%s, ",
1369                                         this_attendee
1370                                 );
1371                                 ++num_attendees;
1372                         }
1373                 }
1374         }
1375
1376         lprintf(9, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
1377
1378         /* If there are no attendees, there are no invitations to send, so...
1379          * don't bother putting one together!  Punch out, Maverick!
1380          */
1381         if (num_attendees == 0) {
1382                 icalcomponent_free(the_request);
1383                 return;
1384         }
1385
1386         /* Encapsulate the VEVENT component into a complete VCALENDAR */
1387         encaps = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
1388         if (encaps == NULL) {
1389                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
1390                         __FILE__, __LINE__);
1391                 icalcomponent_free(the_request);
1392                 return;
1393         }
1394
1395         /* Set the Product ID */
1396         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1397
1398         /* Set the Version Number */
1399         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1400
1401         /* Set the method to REQUEST */
1402         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
1403
1404         /* Now make sure all of the DTSTART and DTEND properties are UTC. */
1405         ical_dezonify(the_request);
1406
1407         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1408          * are responsible for "the_request"'s memory -- it will be freed
1409          * when we free "encaps".
1410          */
1411         icalcomponent_add_component(encaps, the_request);
1412
1413         /* Serialize it */
1414         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1415         icalcomponent_free(encaps);     /* Don't need this anymore. */
1416         if (serialized_request == NULL) return;
1417
1418         request_message_text = mallok(strlen(serialized_request) + SIZ);
1419         if (request_message_text != NULL) {
1420                 sprintf(request_message_text,
1421                         "Content-type: text/calendar\r\n\r\n%s\r\n",
1422                         serialized_request
1423                 );
1424
1425                 msg = CtdlMakeMessage(&CC->usersupp,
1426                         "",                     /* No single recipient here */
1427                         CC->quickroom.QRname, 0, FMT_RFC822,
1428                         "",
1429                         summary_string,         /* Use summary for subject */
1430                         request_message_text);
1431         
1432                 if (msg != NULL) {
1433                         valid = validate_recipients(attendees_string);
1434                         CtdlSubmitMsg(msg, valid, "");
1435                         CtdlFreeMessage(msg);
1436                 }
1437         }
1438         phree(serialized_request);
1439 }
1440
1441
1442 /*
1443  * When a calendar object is being saved, determine whether it's a VEVENT
1444  * and the user saving it is the organizer.  If so, send out invitations
1445  * to any listed attendees.
1446  *
1447  */
1448 void ical_saving_vevent(icalcomponent *cal) {
1449         icalcomponent *c;
1450         icalproperty *organizer = NULL;
1451         char organizer_string[SIZ];
1452
1453         /* Don't send out invitations if we've been asked not to. */
1454         lprintf(9, "CIT_ICAL->avoid_sending_invitations = %d\n",
1455                 CIT_ICAL->avoid_sending_invitations);
1456         if (CIT_ICAL->avoid_sending_invitations > 0) {
1457                 return;
1458         }
1459
1460         strcpy(organizer_string, "");
1461         /*
1462          * The VEVENT subcomponent is the one we're interested in.
1463          * Send out invitations if, and only if, this user is the Organizer.
1464          */
1465         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
1466                 organizer = icalcomponent_get_first_property(cal,
1467                                                 ICAL_ORGANIZER_PROPERTY);
1468                 if (organizer != NULL) {
1469                         if (icalproperty_get_organizer(organizer)) {
1470                                 strcpy(organizer_string,
1471                                         icalproperty_get_organizer(organizer));
1472                         }
1473                 }
1474                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
1475                         strcpy(organizer_string, &organizer_string[7]);
1476                         striplt(organizer_string);
1477                         /*
1478                          * If the user saving the event is listed as the
1479                          * organizer, then send out invitations.
1480                          */
1481                         if (CtdlIsMe(organizer_string)) {
1482                                 ical_send_out_invitations(cal);
1483                         }
1484                 }
1485         }
1486
1487         /* If the component has subcomponents, recurse through them. */
1488         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1489             (c != NULL);
1490             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1491                 /* Recursively process subcomponent */
1492                 ical_saving_vevent(c);
1493         }
1494
1495 }
1496
1497
1498
1499 /*
1500  * Back end for ical_obj_beforesave()
1501  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
1502  * the summary of the event (becomes message subject),
1503  * and the start time (becomes message date/time).
1504  */
1505 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1506                 char *disp, void *content, char *cbtype, size_t length,
1507                 char *encoding, void *cbuserdata)
1508 {
1509         icalcomponent *cal;
1510         icalproperty *p;
1511         struct icalmessagemod *imm;
1512
1513         imm = (struct icalmessagemod *)cbuserdata;
1514
1515         /* If this is a text/calendar object, hunt for the UID and drop it in
1516          * the "user data" pointer for the MIME parser.  When
1517          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1518          * to that string.
1519          */
1520         if (!strcasecmp(cbtype, "text/calendar")) {
1521                 cal = icalcomponent_new_from_string(content);
1522                 if (cal != NULL) {
1523                         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1524                                 cal = icalcomponent_get_first_component(
1525                                         cal, ICAL_VEVENT_COMPONENT
1526                                 );
1527                         }
1528                 }
1529                 if (cal != NULL) {
1530                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1531                         if (p != NULL) {
1532                                 strcpy(imm->uid, icalproperty_get_comment(p));
1533                         }
1534                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
1535                         if (p != NULL) {
1536                                 strcpy(imm->subject,
1537                                                 icalproperty_get_comment(p));
1538                         }
1539                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
1540                         if (p != NULL) {
1541                                 imm->dtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
1542                         }
1543                         icalcomponent_free(cal);
1544                 }
1545         }
1546 }
1547
1548
1549
1550
1551
1552 /*
1553  * See if we need to prevent the object from being saved (we don't allow
1554  * MIME types other than text/calendar in the Calendar> room).  Also, when
1555  * saving an event to the calendar, set the message's Citadel extended message
1556  * ID to the UID of the object.  This causes our replication checker to
1557  * automatically delete any existing instances of the same object.  (Isn't
1558  * that cool?)
1559  *
1560  * We also set the message's Subject to the event summary, and the Date/time to
1561  * the event start time.
1562  */
1563 int ical_obj_beforesave(struct CtdlMessage *msg)
1564 {
1565         char roomname[ROOMNAMELEN];
1566         char *p;
1567         int a;
1568         struct icalmessagemod imm;
1569
1570         /*
1571          * Only messages with content-type text/calendar
1572          * may be saved to Calendar>.  If the message is bound for
1573          * Calendar> but doesn't have this content-type, throw an error
1574          * so that the message may not be posted.
1575          */
1576
1577         /* First determine if this is our room */
1578         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1579         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1580                 return 0;       /* It's not the Calendar room. */
1581         }
1582
1583         /* Then determine content-type of the message */
1584         
1585         /* It must be an RFC822 message! */
1586         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1587         if (msg->cm_format_type != 4)
1588                 return 1;       /* You tried to save a non-RFC822 message! */
1589         
1590         /* Find the Content-Type: header */
1591         p = msg->cm_fields['M'];
1592         a = strlen(p);
1593         while (--a > 0) {
1594                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1595                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1596                                 memset(&imm, 0, sizeof(struct icalmessagemod));
1597                                 mime_parser(msg->cm_fields['M'],
1598                                         NULL,
1599                                         *ical_ctdl_set_extended_msgid,
1600                                         NULL, NULL,
1601                                         (void *)&imm,
1602                                         0
1603                                 );
1604                                 if (strlen(imm.uid) > 0) {
1605                                         if (msg->cm_fields['E'] != NULL) {
1606                                                 phree(msg->cm_fields['E']);
1607                                         }
1608                                         msg->cm_fields['E'] = strdoop(imm.uid);
1609                                 }
1610                                 if (strlen(imm.subject) > 0) {
1611                                         if (msg->cm_fields['U'] != NULL) {
1612                                                 phree(msg->cm_fields['U']);
1613                                         }
1614                                         msg->cm_fields['U'] = strdoop(imm.subject);
1615                                 }
1616                                 if (imm.dtstart > 0) {
1617                                         if (msg->cm_fields['T'] != NULL) {
1618                                                 phree(msg->cm_fields['T']);
1619                                         }
1620                                         msg->cm_fields['T'] = strdoop("000000000000000000");
1621                                         sprintf(msg->cm_fields['T'], "%ld", imm.dtstart);
1622                                 }
1623                                 return 0;
1624                         }
1625                         else {
1626                                 return 1;
1627                         }
1628                 }
1629                 p++;
1630         }
1631         
1632         /* Oops!  No Content-Type in this message!  How'd that happen? */
1633         lprintf(7, "RFC822 message with no Content-Type header!\n");
1634         return 1;
1635 }
1636
1637
1638 /*
1639  * Things we need to do after saving a calendar event.
1640  */
1641 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1642                 char *disp, void *content, char *cbtype, size_t length,
1643                 char *encoding, void *cbuserdata)
1644 {
1645         icalcomponent *cal;
1646
1647         /* If this is a text/calendar object, hunt for the UID and drop it in
1648          * the "user data" pointer for the MIME parser.  When
1649          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1650          * to that string.
1651          */
1652         if (!strcasecmp(cbtype, "text/calendar")) {
1653                 cal = icalcomponent_new_from_string(content);
1654                 if (cal != NULL) {
1655                         ical_saving_vevent(cal);
1656                         icalcomponent_free(cal);
1657                 }
1658         }
1659 }
1660
1661
1662 /* 
1663  * Things we need to do after saving a calendar event.
1664  */
1665 int ical_obj_aftersave(struct CtdlMessage *msg)
1666 {
1667         char roomname[ROOMNAMELEN];
1668         char *p;
1669         int a;
1670
1671         /*
1672          * If this isn't the Calendar> room, no further action is necessary.
1673          */
1674
1675         /* First determine if this is our room */
1676         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1677         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1678                 return 0;       /* It's not the Calendar room. */
1679         }
1680
1681         /* Then determine content-type of the message */
1682         
1683         /* It must be an RFC822 message! */
1684         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1685         if (msg->cm_format_type != 4) return(1);
1686         
1687         /* Find the Content-Type: header */
1688         p = msg->cm_fields['M'];
1689         a = strlen(p);
1690         while (--a > 0) {
1691                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1692                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1693                                 mime_parser(msg->cm_fields['M'],
1694                                         NULL,
1695                                         *ical_obj_aftersave_backend,
1696                                         NULL, NULL,
1697                                         NULL,
1698                                         0
1699                                 );
1700                                 return 0;
1701                         }
1702                         else {
1703                                 return 1;
1704                         }
1705                 }
1706                 p++;
1707         }
1708         
1709         /* Oops!  No Content-Type in this message!  How'd that happen? */
1710         lprintf(7, "RFC822 message with no Content-Type header!\n");
1711         return 1;
1712 }
1713
1714
1715 void ical_session_startup(void) {
1716         CtdlAllocUserData(SYM_CIT_ICAL, sizeof(struct cit_ical));
1717         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
1718 }
1719
1720
1721 #endif  /* CITADEL_WITH_CALENDAR_SERVICE */
1722
1723 /*
1724  * Register this module with the Citadel server.
1725  */
1726 char *serv_calendar_init(void)
1727 {
1728 #ifdef CITADEL_WITH_CALENDAR_SERVICE
1729         SYM_CIT_ICAL = CtdlGetDynamicSymbol();
1730         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1731         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1732         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1733         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1734         CtdlRegisterSessionHook(ical_session_startup, EVT_START);
1735 #endif
1736         return "$Id$";
1737 }