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