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