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