]> code.citadel.org Git - citadel.git/blob - citadel/serv_calendar.c
* Still trying to fix bug in freebusy publish
[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_vcalendar();
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         /* Create a VFREEBUSY subcomponent */
1160         lprintf(9, "Creating VFREEBUSY component\n");
1161         fb = icalcomponent_new_vfreebusy();
1162         if (fb == NULL) {
1163                 cprintf("%d Internal error: cannot allocate memory.\n",
1164                         ERROR+INTERNAL_ERROR);
1165                 icalcomponent_free(encaps);
1166                 getroom(&CC->quickroom, hold_rm);
1167                 return;
1168         }
1169
1170         lprintf(9, "Adding busy time from events\n");
1171         CtdlForEachMessage(MSGS_ALL, 0, "text/calendar",
1172                 NULL, ical_freebusy_backend, (void *)fb
1173         );
1174
1175         lprintf(9, "Before encapsulation:\n---------\n%s\n----------\n",
1176                 icalcomponent_as_ical_string(fb));
1177
1178         /* Put the freebusy component into the calendar component */
1179         lprintf(9, "Encapsulating\n");
1180         encaps = ical_encapsulate_subcomponent(fb);
1181         if (encaps == NULL) {
1182                 icalcomponent_free(fb);
1183                 cprintf("%d Internal error: cannot allocate memory.\n",
1184                         ERROR+INTERNAL_ERROR);
1185                 getroom(&CC->quickroom, hold_rm);
1186                 return;
1187         }
1188
1189         /* Set the method to PUBLISH */
1190         lprintf(9, "Setting method\n");
1191         icalcomponent_set_method(encaps, ICAL_METHOD_PUBLISH);
1192
1193         /* Serialize it */
1194         lprintf(9, "Serializing\n");
1195         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1196         icalcomponent_free(encaps);     /* Don't need this anymore. */
1197
1198         cprintf("%d Here is the free/busy data:\n", LISTING_FOLLOWS);
1199         if (serialized_request != NULL) {
1200                 client_write(serialized_request, strlen(serialized_request));
1201                 phree(serialized_request);
1202         }
1203         cprintf("\n000\n");
1204
1205         /* Go back to the room from which we came... */
1206         getroom(&CC->quickroom, hold_rm);
1207 }
1208
1209
1210
1211
1212 /*
1213  * All Citadel calendar commands from the client come through here.
1214  */
1215 void cmd_ical(char *argbuf)
1216 {
1217         char subcmd[SIZ];
1218         long msgnum;
1219         char partnum[SIZ];
1220         char action[SIZ];
1221         char who[SIZ];
1222
1223         if (CtdlAccessCheck(ac_logged_in)) return;
1224
1225         extract(subcmd, argbuf, 0);
1226
1227         if (!strcmp(subcmd, "test")) {
1228                 cprintf("%d This server supports calendaring\n", CIT_OK);
1229                 return;
1230         }
1231
1232         else if (!strcmp(subcmd, "respond")) {
1233                 msgnum = extract_long(argbuf, 1);
1234                 extract(partnum, argbuf, 2);
1235                 extract(action, argbuf, 3);
1236                 ical_respond(msgnum, partnum, action);
1237         }
1238
1239         else if (!strcmp(subcmd, "handle_rsvp")) {
1240                 msgnum = extract_long(argbuf, 1);
1241                 extract(partnum, argbuf, 2);
1242                 extract(action, argbuf, 3);
1243                 ical_handle_rsvp(msgnum, partnum, action);
1244         }
1245
1246         else if (!strcmp(subcmd, "conflicts")) {
1247                 msgnum = extract_long(argbuf, 1);
1248                 extract(partnum, argbuf, 2);
1249                 ical_conflicts(msgnum, partnum);
1250         }
1251
1252         else if (!strcmp(subcmd, "freebusy")) {
1253                 extract(who, argbuf, 1);
1254                 ical_freebusy(who);
1255         }
1256
1257         else {
1258                 cprintf("%d Invalid subcommand\n", ERROR+CMD_NOT_SUPPORTED);
1259                 return;
1260         }
1261
1262         /* should never get here */
1263 }
1264
1265
1266
1267 /*
1268  * We don't know if the calendar room exists so we just create it at login
1269  */
1270 void ical_create_room(void)
1271 {
1272         struct quickroom qr;
1273         struct visit vbuf;
1274
1275         /* Create the calendar room if it doesn't already exist */
1276         create_room(USERCALENDARROOM, 4, "", 0, 1, 0);
1277
1278         /* Set expiration policy to manual; otherwise objects will be lost! */
1279         if (lgetroom(&qr, USERCALENDARROOM)) {
1280                 lprintf(3, "Couldn't get the user calendar room!\n");
1281                 return;
1282         }
1283         qr.QRep.expire_mode = EXPIRE_MANUAL;
1284         qr.QRdefaultview = 3;   /* 3 = calendar view */
1285         lputroom(&qr);
1286
1287         /* Set the view to a calendar view */
1288         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1289         vbuf.v_view = 3;        /* 3 = calendar */
1290         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1291
1292         /* Create the tasks list room if it doesn't already exist */
1293         create_room(USERTASKSROOM, 4, "", 0, 1, 0);
1294
1295         /* Set expiration policy to manual; otherwise objects will be lost! */
1296         if (lgetroom(&qr, USERTASKSROOM)) {
1297                 lprintf(3, "Couldn't get the user calendar room!\n");
1298                 return;
1299         }
1300         qr.QRep.expire_mode = EXPIRE_MANUAL;
1301         qr.QRdefaultview = 4;   /* 4 = tasks view */
1302         lputroom(&qr);
1303
1304         /* Set the view to a task list view */
1305         CtdlGetRelationship(&vbuf, &CC->usersupp, &qr);
1306         vbuf.v_view = 4;        /* 4 = tasks */
1307         CtdlSetRelationship(&vbuf, &CC->usersupp, &qr);
1308
1309         return;
1310 }
1311
1312
1313 /*
1314  * ical_send_out_invitations() is called by ical_saving_vevent() when it
1315  * finds a VEVENT.
1316  */
1317 void ical_send_out_invitations(icalcomponent *cal) {
1318         icalcomponent *the_request = NULL;
1319         char *serialized_request = NULL;
1320         icalcomponent *encaps = NULL;
1321         char *request_message_text = NULL;
1322         struct CtdlMessage *msg = NULL;
1323         struct recptypes *valid = NULL;
1324         char attendees_string[SIZ];
1325         int num_attendees = 0;
1326         char this_attendee[SIZ];
1327         icalproperty *attendee = NULL;
1328         char summary_string[SIZ];
1329         icalproperty *summary = NULL;
1330
1331         if (cal == NULL) {
1332                 lprintf(3, "ERROR: trying to reply to NULL event?\n");
1333                 return;
1334         }
1335
1336
1337         /* If this is a VCALENDAR component, look for a VEVENT subcomponent. */
1338         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1339                 ical_send_out_invitations(
1340                         icalcomponent_get_first_component(
1341                                 cal, ICAL_VEVENT_COMPONENT
1342                         )
1343                 );
1344                 return;
1345         }
1346
1347         /* Clone the event */
1348         the_request = icalcomponent_new_clone(cal);
1349         if (the_request == NULL) {
1350                 lprintf(3, "ERROR: cannot clone calendar object\n");
1351                 return;
1352         }
1353
1354         /* Extract the summary string -- we'll use it as the
1355          * message subject for the request
1356          */
1357         strcpy(summary_string, "Meeting request");
1358         summary = icalcomponent_get_first_property(the_request, ICAL_SUMMARY_PROPERTY);
1359         if (summary != NULL) {
1360                 if (icalproperty_get_summary(summary)) {
1361                         strcpy(summary_string,
1362                                 icalproperty_get_summary(summary) );
1363                 }
1364         }
1365
1366         /* Determine who the recipients of this message are (the attendees) */
1367         strcpy(attendees_string, "");
1368         for (attendee = icalcomponent_get_first_property(the_request, ICAL_ATTENDEE_PROPERTY); attendee != NULL; attendee = icalcomponent_get_next_property(the_request, ICAL_ATTENDEE_PROPERTY)) {
1369                 if (icalproperty_get_attendee(attendee)) {
1370                         strcpy(this_attendee, icalproperty_get_attendee(attendee) );
1371                         if (!strncasecmp(this_attendee, "MAILTO:", 7)) {
1372                                 strcpy(this_attendee, &this_attendee[7]);
1373                                 snprintf(&attendees_string[strlen(attendees_string)],
1374                                         sizeof(attendees_string) - strlen(attendees_string),
1375                                         "%s, ",
1376                                         this_attendee
1377                                 );
1378                                 ++num_attendees;
1379                         }
1380                 }
1381         }
1382
1383         lprintf(9, "<%d> attendees: <%s>\n", num_attendees, attendees_string);
1384
1385         /* If there are no attendees, there are no invitations to send, so...
1386          * don't bother putting one together!  Punch out, Maverick!
1387          */
1388         if (num_attendees == 0) {
1389                 icalcomponent_free(the_request);
1390                 return;
1391         }
1392
1393         /* Encapsulate the VEVENT component into a complete VCALENDAR */
1394         encaps = icalcomponent_new_vcalendar();
1395         if (encaps == NULL) {
1396                 lprintf(3, "Error at %s:%d - could not allocate component!\n",
1397                         __FILE__, __LINE__);
1398                 icalcomponent_free(the_request);
1399                 return;
1400         }
1401
1402         /* Set the Product ID */
1403         icalcomponent_add_property(encaps, icalproperty_new_prodid(PRODID));
1404
1405         /* Set the Version Number */
1406         icalcomponent_add_property(encaps, icalproperty_new_version("2.0"));
1407
1408         /* Set the method to REQUEST */
1409         icalcomponent_set_method(encaps, ICAL_METHOD_REQUEST);
1410
1411         /* Now make sure all of the DTSTART and DTEND properties are UTC. */
1412         ical_dezonify(the_request);
1413
1414         /* Here we go: put the VEVENT into the VCALENDAR.  We now no longer
1415          * are responsible for "the_request"'s memory -- it will be freed
1416          * when we free "encaps".
1417          */
1418         icalcomponent_add_component(encaps, the_request);
1419
1420         /* Serialize it */
1421         serialized_request = strdoop(icalcomponent_as_ical_string(encaps));
1422         icalcomponent_free(encaps);     /* Don't need this anymore. */
1423         if (serialized_request == NULL) return;
1424
1425         request_message_text = mallok(strlen(serialized_request) + SIZ);
1426         if (request_message_text != NULL) {
1427                 sprintf(request_message_text,
1428                         "Content-type: text/calendar\r\n\r\n%s\r\n",
1429                         serialized_request
1430                 );
1431
1432                 msg = CtdlMakeMessage(&CC->usersupp,
1433                         "",                     /* No single recipient here */
1434                         CC->quickroom.QRname, 0, FMT_RFC822,
1435                         "",
1436                         summary_string,         /* Use summary for subject */
1437                         request_message_text);
1438         
1439                 if (msg != NULL) {
1440                         valid = validate_recipients(attendees_string);
1441                         CtdlSubmitMsg(msg, valid, "");
1442                         CtdlFreeMessage(msg);
1443                 }
1444         }
1445         phree(serialized_request);
1446 }
1447
1448
1449 /*
1450  * When a calendar object is being saved, determine whether it's a VEVENT
1451  * and the user saving it is the organizer.  If so, send out invitations
1452  * to any listed attendees.
1453  *
1454  */
1455 void ical_saving_vevent(icalcomponent *cal) {
1456         icalcomponent *c;
1457         icalproperty *organizer = NULL;
1458         char organizer_string[SIZ];
1459
1460         /* Don't send out invitations if we've been asked not to. */
1461         lprintf(9, "CIT_ICAL->avoid_sending_invitations = %d\n",
1462                 CIT_ICAL->avoid_sending_invitations);
1463         if (CIT_ICAL->avoid_sending_invitations > 0) {
1464                 return;
1465         }
1466
1467         strcpy(organizer_string, "");
1468         /*
1469          * The VEVENT subcomponent is the one we're interested in.
1470          * Send out invitations if, and only if, this user is the Organizer.
1471          */
1472         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
1473                 organizer = icalcomponent_get_first_property(cal,
1474                                                 ICAL_ORGANIZER_PROPERTY);
1475                 if (organizer != NULL) {
1476                         if (icalproperty_get_organizer(organizer)) {
1477                                 strcpy(organizer_string,
1478                                         icalproperty_get_organizer(organizer));
1479                         }
1480                 }
1481                 if (!strncasecmp(organizer_string, "MAILTO:", 7)) {
1482                         strcpy(organizer_string, &organizer_string[7]);
1483                         striplt(organizer_string);
1484                         /*
1485                          * If the user saving the event is listed as the
1486                          * organizer, then send out invitations.
1487                          */
1488                         if (CtdlIsMe(organizer_string)) {
1489                                 ical_send_out_invitations(cal);
1490                         }
1491                 }
1492         }
1493
1494         /* If the component has subcomponents, recurse through them. */
1495         for (c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
1496             (c != NULL);
1497             c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)) {
1498                 /* Recursively process subcomponent */
1499                 ical_saving_vevent(c);
1500         }
1501
1502 }
1503
1504
1505
1506 /*
1507  * Back end for ical_obj_beforesave()
1508  * This hunts for the UID of the calendar event (becomes Citadel msg EUID),
1509  * the summary of the event (becomes message subject),
1510  * and the start time (becomes message date/time).
1511  */
1512 void ical_ctdl_set_extended_msgid(char *name, char *filename, char *partnum,
1513                 char *disp, void *content, char *cbtype, size_t length,
1514                 char *encoding, void *cbuserdata)
1515 {
1516         icalcomponent *cal;
1517         icalproperty *p;
1518         struct icalmessagemod *imm;
1519
1520         imm = (struct icalmessagemod *)cbuserdata;
1521
1522         /* If this is a text/calendar object, hunt for the UID and drop it in
1523          * the "user data" pointer for the MIME parser.  When
1524          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1525          * to that string.
1526          */
1527         if (!strcasecmp(cbtype, "text/calendar")) {
1528                 cal = icalcomponent_new_from_string(content);
1529                 if (cal != NULL) {
1530                         if (icalcomponent_isa(cal) == ICAL_VCALENDAR_COMPONENT) {
1531                                 cal = icalcomponent_get_first_component(
1532                                         cal, ICAL_VEVENT_COMPONENT
1533                                 );
1534                         }
1535                 }
1536                 if (cal != NULL) {
1537                         p = ical_ctdl_get_subprop(cal, ICAL_UID_PROPERTY);
1538                         if (p != NULL) {
1539                                 strcpy(imm->uid, icalproperty_get_comment(p));
1540                         }
1541                         p = ical_ctdl_get_subprop(cal, ICAL_SUMMARY_PROPERTY);
1542                         if (p != NULL) {
1543                                 strcpy(imm->subject,
1544                                                 icalproperty_get_comment(p));
1545                         }
1546                         p = ical_ctdl_get_subprop(cal, ICAL_DTSTART_PROPERTY);
1547                         if (p != NULL) {
1548                                 imm->dtstart = icaltime_as_timet(icalproperty_get_dtstart(p));
1549                         }
1550                         icalcomponent_free(cal);
1551                 }
1552         }
1553 }
1554
1555
1556
1557
1558
1559 /*
1560  * See if we need to prevent the object from being saved (we don't allow
1561  * MIME types other than text/calendar in the Calendar> room).  Also, when
1562  * saving an event to the calendar, set the message's Citadel extended message
1563  * ID to the UID of the object.  This causes our replication checker to
1564  * automatically delete any existing instances of the same object.  (Isn't
1565  * that cool?)
1566  *
1567  * We also set the message's Subject to the event summary, and the Date/time to
1568  * the event start time.
1569  */
1570 int ical_obj_beforesave(struct CtdlMessage *msg)
1571 {
1572         char roomname[ROOMNAMELEN];
1573         char *p;
1574         int a;
1575         struct icalmessagemod imm;
1576
1577         /*
1578          * Only messages with content-type text/calendar
1579          * may be saved to Calendar>.  If the message is bound for
1580          * Calendar> but doesn't have this content-type, throw an error
1581          * so that the message may not be posted.
1582          */
1583
1584         /* First determine if this is our room */
1585         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1586         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1587                 return 0;       /* It's not the Calendar room. */
1588         }
1589
1590         /* Then determine content-type of the message */
1591         
1592         /* It must be an RFC822 message! */
1593         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1594         if (msg->cm_format_type != 4)
1595                 return 1;       /* You tried to save a non-RFC822 message! */
1596         
1597         /* Find the Content-Type: header */
1598         p = msg->cm_fields['M'];
1599         a = strlen(p);
1600         while (--a > 0) {
1601                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1602                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1603                                 memset(&imm, 0, sizeof(struct icalmessagemod));
1604                                 mime_parser(msg->cm_fields['M'],
1605                                         NULL,
1606                                         *ical_ctdl_set_extended_msgid,
1607                                         NULL, NULL,
1608                                         (void *)&imm,
1609                                         0
1610                                 );
1611                                 if (strlen(imm.uid) > 0) {
1612                                         if (msg->cm_fields['E'] != NULL) {
1613                                                 phree(msg->cm_fields['E']);
1614                                         }
1615                                         msg->cm_fields['E'] = strdoop(imm.uid);
1616                                 }
1617                                 if (strlen(imm.subject) > 0) {
1618                                         if (msg->cm_fields['U'] != NULL) {
1619                                                 phree(msg->cm_fields['U']);
1620                                         }
1621                                         msg->cm_fields['U'] = strdoop(imm.subject);
1622                                 }
1623                                 if (imm.dtstart > 0) {
1624                                         if (msg->cm_fields['T'] != NULL) {
1625                                                 phree(msg->cm_fields['T']);
1626                                         }
1627                                         msg->cm_fields['T'] = strdoop("000000000000000000");
1628                                         sprintf(msg->cm_fields['T'], "%ld", imm.dtstart);
1629                                 }
1630                                 return 0;
1631                         }
1632                         else {
1633                                 return 1;
1634                         }
1635                 }
1636                 p++;
1637         }
1638         
1639         /* Oops!  No Content-Type in this message!  How'd that happen? */
1640         lprintf(7, "RFC822 message with no Content-Type header!\n");
1641         return 1;
1642 }
1643
1644
1645 /*
1646  * Things we need to do after saving a calendar event.
1647  */
1648 void ical_obj_aftersave_backend(char *name, char *filename, char *partnum,
1649                 char *disp, void *content, char *cbtype, size_t length,
1650                 char *encoding, void *cbuserdata)
1651 {
1652         icalcomponent *cal;
1653
1654         /* If this is a text/calendar object, hunt for the UID and drop it in
1655          * the "user data" pointer for the MIME parser.  When
1656          * ical_obj_beforesave() sees it there, it'll set the Extended msgid
1657          * to that string.
1658          */
1659         if (!strcasecmp(cbtype, "text/calendar")) {
1660                 cal = icalcomponent_new_from_string(content);
1661                 if (cal != NULL) {
1662                         ical_saving_vevent(cal);
1663                         icalcomponent_free(cal);
1664                 }
1665         }
1666 }
1667
1668
1669 /* 
1670  * Things we need to do after saving a calendar event.
1671  */
1672 int ical_obj_aftersave(struct CtdlMessage *msg)
1673 {
1674         char roomname[ROOMNAMELEN];
1675         char *p;
1676         int a;
1677
1678         /*
1679          * If this isn't the Calendar> room, no further action is necessary.
1680          */
1681
1682         /* First determine if this is our room */
1683         MailboxName(roomname, sizeof roomname, &CC->usersupp, USERCALENDARROOM);
1684         if (strcasecmp(roomname, CC->quickroom.QRname)) {
1685                 return 0;       /* It's not the Calendar room. */
1686         }
1687
1688         /* Then determine content-type of the message */
1689         
1690         /* It must be an RFC822 message! */
1691         /* FIXME: Not handling MIME multipart messages; implement with IMIP */
1692         if (msg->cm_format_type != 4) return(1);
1693         
1694         /* Find the Content-Type: header */
1695         p = msg->cm_fields['M'];
1696         a = strlen(p);
1697         while (--a > 0) {
1698                 if (!strncasecmp(p, "Content-Type: ", 14)) {    /* Found it */
1699                         if (!strncasecmp(p + 14, "text/calendar", 13)) {
1700                                 mime_parser(msg->cm_fields['M'],
1701                                         NULL,
1702                                         *ical_obj_aftersave_backend,
1703                                         NULL, NULL,
1704                                         NULL,
1705                                         0
1706                                 );
1707                                 return 0;
1708                         }
1709                         else {
1710                                 return 1;
1711                         }
1712                 }
1713                 p++;
1714         }
1715         
1716         /* Oops!  No Content-Type in this message!  How'd that happen? */
1717         lprintf(7, "RFC822 message with no Content-Type header!\n");
1718         return 1;
1719 }
1720
1721
1722 void ical_session_startup(void) {
1723         CtdlAllocUserData(SYM_CIT_ICAL, sizeof(struct cit_ical));
1724         memset(CIT_ICAL, 0, sizeof(struct cit_ical));
1725 }
1726
1727
1728 #endif  /* CITADEL_WITH_CALENDAR_SERVICE */
1729
1730 /*
1731  * Register this module with the Citadel server.
1732  */
1733 char *serv_calendar_init(void)
1734 {
1735 #ifdef CITADEL_WITH_CALENDAR_SERVICE
1736         SYM_CIT_ICAL = CtdlGetDynamicSymbol();
1737         CtdlRegisterMessageHook(ical_obj_beforesave, EVT_BEFORESAVE);
1738         CtdlRegisterMessageHook(ical_obj_aftersave, EVT_AFTERSAVE);
1739         CtdlRegisterSessionHook(ical_create_room, EVT_LOGIN);
1740         CtdlRegisterProtoHook(cmd_ical, "ICAL", "Citadel iCal commands");
1741         CtdlRegisterSessionHook(ical_session_startup, EVT_START);
1742 #endif
1743         return "$Id$";
1744 }