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