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