* now hold / sort the ical events in our hashlist.
[citadel.git] / webcit / calendar.c
1 /*
2  * $Id$
3  *
4  * Functions which handle calendar objects and their processing/display.
5  */
6
7 #include "webcit.h"
8 #include "webserver.h"
9
10
11 /*
12  * \brief Process a calendar object
13  * ...at this point it's already been deserialized by cal_process_attachment()
14  * \param cal the calendar object
15  * \param recursion_level call stack depth ??????
16  * \param msgnum number of the mesage in our db
17  * \param cal_partnum of the calendar object ???? 
18  */
19 void cal_process_object(icalcomponent *cal,
20                         int recursion_level,
21                         long msgnum,
22                         char *cal_partnum) 
23 {
24         icalcomponent *c;
25         icalproperty *method = NULL;
26         icalproperty_method the_method = ICAL_METHOD_NONE;
27         icalproperty *p;
28         struct icaltimetype t;
29         time_t tt;
30         char buf[256];
31         char conflict_name[256];
32         char conflict_message[256];
33         int is_update = 0;
34         char divname[32];
35         static int divcount = 0;
36
37         sprintf(divname, "rsvp%04x", ++divcount);
38
39         /** Leading HTML for the display of this object */
40         if (recursion_level == 0) {
41                 wprintf("<div class=\"mimepart\">\n");
42         }
43
44         /** Look for a method */
45         method = icalcomponent_get_first_property(cal, ICAL_METHOD_PROPERTY);
46
47         /** See what we need to do with this */
48         if (method != NULL) {
49                 the_method = icalproperty_get_method(method);
50                 char *title;
51
52                 wprintf("<div id=\"%s_title\">", divname);
53                 wprintf("<img src=\"static/calarea_48x.gif\">");
54                 wprintf("<span>");
55                 switch(the_method) {
56                 case ICAL_METHOD_REQUEST:
57                         title = _("Meeting invitation");
58                         break;
59                 case ICAL_METHOD_REPLY:
60                         title = _("Attendee's reply to your invitation");
61                         break;
62                 case ICAL_METHOD_PUBLISH:
63                         title = _("Published event");
64                         break;
65                 default:
66                         title = _("This is an unknown type of calendar item.");
67                         break;
68                 }
69                 wprintf("</span>");
70
71                 wprintf("&nbsp;&nbsp;%s",title);
72                 wprintf("</div>");
73         }
74
75         wprintf("<dl>");
76         p = icalcomponent_get_first_property(cal, ICAL_SUMMARY_PROPERTY);
77         if (p != NULL) {
78                 wprintf("<dt>");
79                 wprintf(_("Summary:"));
80                 wprintf("</dt><dd>");
81                 escputs((char *)icalproperty_get_comment(p));
82                 wprintf("</dd>\n");
83         }
84
85         p = icalcomponent_get_first_property(cal, ICAL_LOCATION_PROPERTY);
86         if (p != NULL) {
87                 wprintf("<dt>");
88                 wprintf(_("Location:"));
89                 wprintf("</dt><dd>");
90                 escputs((char *)icalproperty_get_comment(p));
91                 wprintf("</dd>\n");
92         }
93
94         /**
95          * Only show start/end times if we're actually looking at the VEVENT
96          * component.  Otherwise it shows bogus dates for things like timezone.
97          */
98         if (icalcomponent_isa(cal) == ICAL_VEVENT_COMPONENT) {
99
100                 p = icalcomponent_get_first_property(cal,
101                                                      ICAL_DTSTART_PROPERTY);
102                 if (p != NULL) {
103                         t = icalproperty_get_dtstart(p);
104
105                         if (t.is_date) {
106                                 struct tm d_tm;
107                                 char d_str[32];
108                                 memset(&d_tm, 0, sizeof d_tm);
109                                 d_tm.tm_year = t.year - 1900;
110                                 d_tm.tm_mon = t.month - 1;
111                                 d_tm.tm_mday = t.day;
112                                 wc_strftime(d_str, sizeof d_str, "%x", &d_tm);
113                                 wprintf("<dt>");
114                                 wprintf(_("Date:"));
115                                 wprintf("</dt><dd>%s</dd>", d_str);
116                         }
117                         else {
118                                 tt = icaltime_as_timet(t);
119                                 webcit_fmt_date(buf, tt, 0);
120                                 wprintf("<dt>");
121                                 wprintf(_("Starting date/time:"));
122                                 wprintf("</dt><dd>%s</dd>", buf);
123                         }
124                 }
125         
126                 p = icalcomponent_get_first_property(cal, ICAL_DTEND_PROPERTY);
127                 if (p != NULL) {
128                         t = icalproperty_get_dtend(p);
129                         tt = icaltime_as_timet(t);
130                         webcit_fmt_date(buf, tt, 0);
131                         wprintf("<dt>");
132                         wprintf(_("Ending date/time:"));
133                         wprintf("</dt><dd>%s</dd>", buf);
134                 }
135
136         }
137
138         p = icalcomponent_get_first_property(cal, ICAL_DESCRIPTION_PROPERTY);
139         if (p != NULL) {
140                 wprintf("<dt>");
141                 wprintf(_("Description:"));
142                 wprintf("</dt><dd>");
143                 escputs((char *)icalproperty_get_comment(p));
144                 wprintf("</dd>\n");
145         }
146
147         /** If the component has attendees, iterate through them. */
148         for (p = icalcomponent_get_first_property(cal, ICAL_ATTENDEE_PROPERTY); 
149              (p != NULL); 
150              p = icalcomponent_get_next_property(cal, ICAL_ATTENDEE_PROPERTY)) {
151                 wprintf("<dt>");
152                 wprintf(_("Attendee:"));
153                 wprintf("</dt><dd>");
154                 safestrncpy(buf, icalproperty_get_attendee(p), sizeof buf);
155                 if (!strncasecmp(buf, "MAILTO:", 7)) {
156
157                         /** screen name or email address */
158                         strcpy(buf, &buf[7]);
159                         striplt(buf);
160                         escputs(buf);
161                         wprintf(" ");
162
163                         /** participant status */
164                         partstat_as_string(buf, p);
165                         escputs(buf);
166                 }
167                 wprintf("</dd>\n");
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                 cal_process_object(c, recursion_level+1, msgnum, cal_partnum);
176         }
177
178         /** If this is a REQUEST, display conflicts and buttons */
179         if (the_method == ICAL_METHOD_REQUEST) {
180
181                 /* Check for conflicts */
182                 lprintf(9, "Checking server calendar for conflicts...\n");
183                 serv_printf("ICAL conflicts|%ld|%s|", msgnum, cal_partnum);
184                 serv_getln(buf, sizeof buf);
185                 if (buf[0] == '1') {
186                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
187                                 extract_token(conflict_name, buf, 3, '|', sizeof conflict_name);
188                                 is_update = extract_int(buf, 4);
189
190                                 if (is_update) {
191                                         snprintf(conflict_message, sizeof conflict_message,
192                                                  _("This is an update of '%s' which is already in your calendar."), conflict_name);
193                                 }
194                                 else {
195                                         snprintf(conflict_message, sizeof conflict_message,
196                                                  _("This event would conflict with '%s' which is already in your calendar."), conflict_name);
197                                 }
198
199                                 wprintf("<dt>%s",
200                                         (is_update ?
201                                          _("Update:") :
202                                          _("CONFLICT:")
203                                                 )
204                                         );
205                                 wprintf("</dt><dd>");
206                                 escputs(conflict_message);
207                                 wprintf("</dd>\n");
208                         }
209                 }
210                 lprintf(9, "...done.\n");
211
212                 wprintf("</dl>");
213
214                 /** Display the Accept/Decline buttons */
215                 wprintf("<p id=\"%s_question\">"
216                         "%s "
217                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
218                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Accept');\">%s</a>"
219                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
220                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Tentative');\">%s</a>"
221                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
222                         "<a href=\"javascript:RespondToInvitation('%s_question','%s_title','%ld','%s','Decline');\">%s</a>"
223                         "</span></p>\n",
224                         divname,
225                         _("How would you like to respond to this invitation?"),
226                         divname, divname, msgnum, cal_partnum, _("Accept"),
227                         divname, divname, msgnum, cal_partnum, _("Tentative"),
228                         divname, divname, msgnum, cal_partnum, _("Decline")
229                         );
230
231         }
232
233         /** If this is a REPLY, display update button */
234         if (the_method == ICAL_METHOD_REPLY) {
235
236                 /** \todo  In the future, if we want to validate this object before \
237                  * continuing, we can do it this way:
238                  serv_printf("ICAL whatever|%ld|%s|", msgnum, cal_partnum);
239                  serv_getln(buf, sizeof buf);
240                  }
241                 ***********/
242
243                 /** Display the update buttons */
244                 wprintf("<p id=\"%s_question\" >"
245                         "%s "
246                         "&nbsp;&nbsp;&nbsp;<span class=\"button_link\"> "
247                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Update');\">%s</a>"
248                         "</span>&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
249                         "<a href=\"javascript:HandleRSVP('%s_question','%s_title','%ld','%s','Ignore');\">%s</a>"
250                         "</span></p>\n",
251                         divname,
252                         _("Click <i>Update</i> to accept this reply and update your calendar."),
253                         divname, divname, msgnum, cal_partnum, _("Update"),
254                         divname, divname, msgnum, cal_partnum, _("Ignore")
255                         );
256         
257         }
258         
259         /** Trailing HTML for the display of this object */
260         if (recursion_level == 0) {
261                 wprintf("<p>&nbsp;</p></div>\n");
262         }
263 }
264
265
266 /**
267  * \brief process calendar mail atachment
268  * Deserialize a calendar object in a message so it can be processed.
269  * (This is the main entry point for these things)
270  * \param part_source the part of the message we want to parse
271  * \param msgnum number of the mesage in our db
272  * \param cal_partnum the number of the calendar item
273  */
274 void cal_process_attachment(char *part_source, long msgnum, char *cal_partnum) 
275 {
276         icalcomponent *cal;
277
278         cal = icalcomponent_new_from_string(part_source);
279
280         if (cal == NULL) {
281                 wprintf(_("There was an error parsing this calendar item."));
282                 wprintf("<br />\n");
283                 return;
284         }
285
286         ical_dezonify(cal);
287         cal_process_object(cal, 0, msgnum, cal_partnum);
288
289         /* Free the memory we obtained from libical's constructor */
290         icalcomponent_free(cal);
291 }
292
293
294
295
296 /**
297  * \brief accept/decline meeting
298  * Respond to a meeting request
299  */
300 void respond_to_request(void) 
301 {
302         char buf[1024];
303
304         begin_ajax_response();
305
306         serv_printf("ICAL respond|%s|%s|%s|",
307                 bstr("msgnum"),
308                 bstr("cal_partnum"),
309                 bstr("sc")
310         );
311         serv_getln(buf, sizeof buf);
312
313         if (buf[0] == '2') {
314                 wprintf("<img src=\"static/calarea_48x.gif\"><span>");
315                 if (!strcasecmp(bstr("sc"), "accept")) {
316                         wprintf(_("You have accepted this meeting invitation.  "
317                                 "It has been entered into your calendar.")
318                         );
319                 } else if (!strcasecmp(bstr("sc"), "tentative")) {
320                         wprintf(_("You have tentatively accepted this meeting invitation.  "
321                                 "It has been 'pencilled in' to your calendar.")
322                         );
323                 } else if (!strcasecmp(bstr("sc"), "decline")) {
324                         wprintf(_("You have declined this meeting invitation.  "
325                                   "It has <b>not</b> been entered into your calendar.")
326                                 );
327                 }
328                 wprintf(" ");
329                 wprintf(_("A reply has been sent to the meeting organizer."));
330                 wprintf("</span>");
331         } else {
332                 wprintf("<img align=\"center\" src=\"static/error.gif\"><span>");
333                 wprintf("%s\n", &buf[4]);
334                 wprintf("</span>");
335         }
336
337         end_ajax_response();
338 }
339
340
341
342 /**
343  * \brief Handle an incoming RSVP
344  */
345 void handle_rsvp(void) 
346 {
347         char buf[1024];
348
349         begin_ajax_response();
350
351         serv_printf("ICAL handle_rsvp|%s|%s|%s|",
352                 bstr("msgnum"),
353                 bstr("cal_partnum"),
354                 bstr("sc")
355         );
356         serv_getln(buf, sizeof buf);
357
358         if (buf[0] == '2') {
359                 wprintf("<img src=\"static/calarea_48x.gif\"><span>");
360                 if (!strcasecmp(bstr("sc"), "update")) {
361                         wprintf(_("Your calendar has been updated to reflect this RSVP."));
362                 } else if (!strcasecmp(bstr("sc"), "ignore")) {
363                         wprintf(_("You have chosen to ignore this RSVP. "
364                                   "Your calendar has <b>not</b> been updated.")
365                                 );
366                 }
367                 wprintf("</span>");
368         } else {
369                 wprintf("<img src=\"static/error.gif\"><span> %s\n", &buf[4]);
370                 wprintf("</span>");
371         }
372
373         end_ajax_response();
374 }
375
376
377
378 /*@}*/
379 /*-----------------------------------------------------------------------**/
380
381
382
383 /**
384  * \defgroup MsgDisplayHandlers Display handlers for message reading 
385  * \ingroup Calendaring
386  */
387
388 /*@{*/
389
390 int Flathash(const char *str, long len)
391 {
392         if (len != sizeof (int))
393                 return 0;
394         else return *(int*)str;
395 }
396
397
398
399 /**
400  * \brief clean up ical memory
401  * todo this could get trouble with future ical versions 
402  */
403 void delete_cal(void *vCal)
404 {
405         disp_cal *Cal = (disp_cal*) vCal;
406         icalcomponent_free(Cal->cal);
407         free(Cal->from);
408         free(Cal);
409 }
410
411 /**
412  * \brief get items, keep them.
413  * If we're reading calendar items, just store them for now.  We have to
414  * sort and re-output them later when we draw the calendar.
415  * \param cal Our calendar to process
416  * \param msgnum number of the mesage in our db
417  */
418 void display_individual_cal(icalcomponent *cal, long msgnum, char *from, int unread)
419 {
420         icalproperty *ps = NULL;
421         struct icaltimetype t;
422         struct wcsession *WCC = WC;
423         disp_cal *Cal;
424         size_t len;
425         
426         if (WCC->disp_cal_items == NULL)
427                 WCC->disp_cal_items = NewHash(0, Flathash);
428         
429         Cal = (disp_cal*) malloc(sizeof(disp_cal));
430         memset(Cal, 0, sizeof(disp_cal));
431
432         Cal->cal = icalcomponent_new_clone(cal);
433         Cal->unread = unread;
434         len = strlen(from);
435         Cal->from = (char*)malloc(len+ 1);
436         memcpy(Cal->from, from, len + 1);
437         ical_dezonify(Cal->cal);
438         Cal->cal_msgnum = msgnum;
439
440         //! Precalculate some Values we can use for easy comparison later.
441         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTSTART_PROPERTY);
442         if (ps != NULL) {
443                 t = icalproperty_get_dtstart(ps);
444                 Cal->event_start = icaltime_as_timet(t);
445         }
446         ps = icalcomponent_get_first_property(Cal->cal, ICAL_DTEND_PROPERTY);
447         if (ps != NULL) { //!  Precalc the end day and end day + hour
448                 t = icalproperty_get_dtstart(ps);
449                 Cal->event_end = icaltime_as_timet(t);
450         }
451         Put(WCC->disp_cal_items, 
452             (char*) &Cal->event_start,
453             sizeof(Cal->event_start), 
454             Cal, 
455             delete_cal);
456 }
457
458
459
460 /**
461  * \brief edit a task
462  * Display a task by itself (for editing)
463  * \param supplied_vtodo the todo item we want to edit
464  * \param msgnum number of the mesage in our db
465  */
466 void display_edit_individual_task(icalcomponent *supplied_vtodo, long msgnum, char *from, int unread) 
467 {
468         icalcomponent *vtodo;
469         icalproperty *p;
470         struct icaltimetype IcalTime;
471         time_t now;
472         int created_new_vtodo = 0;
473         icalproperty_status todoStatus;
474
475         now = time(NULL);
476
477         if (supplied_vtodo != NULL) {
478                 vtodo = supplied_vtodo;
479
480                 /**
481                  * If we're looking at a fully encapsulated VCALENDAR
482                  * rather than a VTODO component, attempt to use the first
483                  * relevant VTODO subcomponent.  If there is none, the
484                  * NULL returned by icalcomponent_get_first_component() will
485                  * tell the next iteration of this function to create a
486                  * new one.
487                  */
488                 if (icalcomponent_isa(vtodo) == ICAL_VCALENDAR_COMPONENT) {
489                         display_edit_individual_task(
490                                 icalcomponent_get_first_component(
491                                         vtodo, ICAL_VTODO_COMPONENT
492                                         ), 
493                                 msgnum,
494                                 from, unread
495                                 );
496                         return;
497                 }
498         }
499         else {
500                 vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
501                 created_new_vtodo = 1;
502         }
503         
504         // TODO: Can we take all this and move it into a template?      
505         output_headers(1, 1, 1, 0, 0, 0);
506         wprintf("<!-- start task edit form -->");
507         p = icalcomponent_get_first_property(vtodo, ICAL_SUMMARY_PROPERTY);
508         // Get summary early for title
509         wprintf("<div class=\"box\">\n");
510         wprintf("<div class=\"boxlabel\">");
511         wprintf(_("Edit task"));
512         wprintf("- ");
513         if (p != NULL) {
514                 escputs((char *)icalproperty_get_comment(p));
515         }
516         wprintf("</div>");
517         
518         wprintf("<div class=\"boxcontent\">\n");
519         wprintf("<FORM METHOD=\"POST\" action=\"save_task\">\n");
520         wprintf("<div style=\"display: none;\">\n       ");
521         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%ld\">\n", WC->nonce);
522         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgnum\" VALUE=\"%ld\">\n",
523                 msgnum);
524         wprintf("</div>");
525         wprintf("<table class=\"calendar_background\"><tr><td>");
526         wprintf("<TABLE STYLE=\"border: none;\">\n");
527
528         wprintf("<TR><TD>");
529         wprintf(_("Summary:"));
530         wprintf("</TD><TD>"
531                 "<INPUT TYPE=\"text\" NAME=\"summary\" "
532                 "MAXLENGTH=\"64\" SIZE=\"64\" VALUE=\"");
533         p = icalcomponent_get_first_property(vtodo, ICAL_SUMMARY_PROPERTY);
534         if (p != NULL) {
535                 escputs((char *)icalproperty_get_comment(p));
536         }
537         wprintf("\"></TD></TR>\n");
538
539         wprintf("<TR><TD>");
540         wprintf(_("Start date:"));
541         wprintf("</TD><TD>");
542         p = icalcomponent_get_first_property(vtodo, ICAL_DTSTART_PROPERTY);
543         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"nodtstart\" ID=\"nodtstart\" VALUE=\"NODTSTART\" ");
544         if (p == NULL) {
545                 wprintf("CHECKED=\"CHECKED\"");
546         }
547         wprintf(">");
548         wprintf(_("No date"));
549         
550         wprintf(" ");
551         wprintf(_("or"));
552         wprintf(" ");
553         if (p != NULL) {
554                 IcalTime = icalproperty_get_dtstart(p);
555         }
556         else
557                 IcalTime = icaltime_current_time_with_zone(get_default_icaltimezone());
558         display_icaltimetype_as_webform(&IcalTime, "dtstart");
559         wprintf("</TD></TR>\n");
560
561         wprintf("<TR><TD>");
562         wprintf(_("Due date:"));
563         wprintf("</TD><TD>");
564         p = icalcomponent_get_first_property(vtodo, ICAL_DUE_PROPERTY);
565         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"nodue\" ID=\"nodue\" VALUE=\"NODUE\"");
566         if (p == NULL) {
567                 wprintf("CHECKED=\"CHECKED\"");
568         }
569         wprintf(">");
570         wprintf(_("No date"));
571         wprintf(" ");
572         wprintf(_("or"));
573         wprintf(" ");
574         if (p != NULL) {
575                 IcalTime = icalproperty_get_due(p);
576         }
577         else
578                 IcalTime = icaltime_current_time_with_zone(get_default_icaltimezone());
579         display_icaltimetype_as_webform(&IcalTime, "due");
580                 
581         wprintf("</TD></TR>\n");
582         todoStatus = icalcomponent_get_status(vtodo);
583         wprintf("<TR><TD>\n");
584         wprintf(_("Completed:"));
585         wprintf("</TD><TD>");
586         wprintf("<INPUT TYPE=\"CHECKBOX\" NAME=\"STATUS\" VALUE=\"COMPLETED\"");
587         if (todoStatus == ICAL_STATUS_COMPLETED) {
588                 wprintf(" CHECKED=\"CHECKED\"");
589         } 
590         wprintf(" >");
591         wprintf("</TD></TR>");
592         // start category field
593         p = icalcomponent_get_first_property(vtodo, ICAL_CATEGORIES_PROPERTY);
594         wprintf("<TR><TD>");
595         wprintf(_("Category:"));
596         wprintf("</TD><TD>");
597         wprintf("<INPUT TYPE=\"text\" NAME=\"category\" MAXLENGTH=\"32\" SIZE=\"32\" VALUE=\"");
598         if (p != NULL) {
599                 escputs((char *)icalproperty_get_categories(p));
600         }
601         wprintf("\">");
602         wprintf("</TD></TR>\n   ");
603         // end category field
604         wprintf("<TR><TD>");
605         wprintf(_("Description:"));
606         wprintf("</TD><TD>");
607         wprintf("<TEXTAREA NAME=\"description\" "
608                 "ROWS=\"10\" COLS=\"80\">\n"
609                 );
610         p = icalcomponent_get_first_property(vtodo, ICAL_DESCRIPTION_PROPERTY);
611         if (p != NULL) {
612                 escputs((char *)icalproperty_get_comment(p));
613         }
614         wprintf("</TEXTAREA></TD></TR></TABLE>\n");
615
616         wprintf("<SPAN STYLE=\"text-align: center;\">"
617                 "<INPUT TYPE=\"submit\" NAME=\"save_button\" VALUE=\"%s\">"
618                 "&nbsp;&nbsp;"
619                 "<INPUT TYPE=\"submit\" NAME=\"delete_button\" VALUE=\"%s\">\n"
620                 "&nbsp;&nbsp;"
621                 "<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">\n"
622                 "</SPAN>\n",
623                 _("Save"),
624                 _("Delete"),
625                 _("Cancel")
626                 );
627         wprintf("</td></tr></table>");
628         wprintf("</FORM>\n");
629         wprintf("</div></div></div>\n");
630         wprintf("<!-- end task edit form -->");
631         wDumpContent(1);
632
633         if (created_new_vtodo) {
634                 icalcomponent_free(vtodo);
635         }
636 }
637
638 /*
639  * \brief Save an edited task
640  * \param supplied_vtodo the task to save
641  * \param msgnum number of the mesage in our db
642  */
643 void save_individual_task(icalcomponent *supplied_vtodo, long msgnum, char* from, int unread) 
644 {
645         char buf[SIZ];
646         int delete_existing = 0;
647         icalproperty *prop;
648         icalcomponent *vtodo, *encaps;
649         int created_new_vtodo = 0;
650         int i;
651         int sequence = 0;
652         struct icaltimetype t;
653
654         if (supplied_vtodo != NULL) {
655                 vtodo = supplied_vtodo;
656                 /**
657                  * If we're looking at a fully encapsulated VCALENDAR
658                  * rather than a VTODO component, attempt to use the first
659                  * relevant VTODO subcomponent.  If there is none, the
660                  * NULL returned by icalcomponent_get_first_component() will
661                  * tell the next iteration of this function to create a
662                  * new one.
663                  */
664                 if (icalcomponent_isa(vtodo) == ICAL_VCALENDAR_COMPONENT) {
665                         save_individual_task(
666                                 icalcomponent_get_first_component(
667                                         vtodo, ICAL_VTODO_COMPONENT), 
668                                 msgnum, from, unread
669                                 );
670                         return;
671                 }
672         }
673         else {
674                 vtodo = icalcomponent_new(ICAL_VTODO_COMPONENT);
675                 created_new_vtodo = 1;
676         }
677
678         if (havebstr("save_button")) {
679
680                 /** Replace values in the component with ones from the form */
681
682                 while (prop = icalcomponent_get_first_property(vtodo,
683                                                                ICAL_SUMMARY_PROPERTY), prop != NULL) {
684                         icalcomponent_remove_property(vtodo, prop);
685                         icalproperty_free(prop);
686                 }
687                 if (havebstr("summary")) {
688
689                         icalcomponent_add_property(vtodo,
690                                                    icalproperty_new_summary(bstr("summary")));
691                 } else {
692                         icalcomponent_add_property(vtodo,
693                                                    icalproperty_new_summary("Untitled Task"));
694                 }
695         
696                 while (prop = icalcomponent_get_first_property(vtodo,
697                                                                ICAL_DESCRIPTION_PROPERTY), prop != NULL) {
698                         icalcomponent_remove_property(vtodo, prop);
699                         icalproperty_free(prop);
700                 }
701                 if (!IsEmptyStr(bstr("description"))) {
702                         icalcomponent_add_property(vtodo,
703                                                    icalproperty_new_description(bstr("description")));
704                 }
705         
706                 while (prop = icalcomponent_get_first_property(vtodo,
707                                                                ICAL_DTSTART_PROPERTY), prop != NULL) {
708                         icalcomponent_remove_property(vtodo, prop);
709                         icalproperty_free(prop);
710                 }
711                 if (IsEmptyStr(bstr("nodtstart"))) {
712                         icaltime_from_webform(&t, "dtstart");
713                         icalcomponent_add_property(vtodo,
714                                                    icalproperty_new_dtstart(t)
715                                 );
716                 }
717                 while(prop = icalcomponent_get_first_property(vtodo,
718                                                               ICAL_STATUS_PROPERTY), prop != NULL) {
719                         icalcomponent_remove_property(vtodo,prop);
720                         icalproperty_free(prop);
721                 }
722                 if (!IsEmptyStr(bstr("status"))) {
723                         icalproperty_status taskStatus = icalproperty_string_to_status(
724                                 bstr("status"));
725                         icalcomponent_set_status(vtodo, taskStatus);
726                 }
727                 while (prop = icalcomponent_get_first_property(vtodo,
728                                                                ICAL_CATEGORIES_PROPERTY), prop != NULL) {
729                         icalcomponent_remove_property(vtodo,prop);
730                         icalproperty_free(prop);
731                 }
732                 if (!IsEmptyStr(bstr("category"))) {
733                         prop = icalproperty_new_categories(bstr("category"));
734                         icalcomponent_add_property(vtodo,prop);
735                 }
736                 while (prop = icalcomponent_get_first_property(vtodo,
737                                                                ICAL_DUE_PROPERTY), prop != NULL) {
738                         icalcomponent_remove_property(vtodo, prop);
739                         icalproperty_free(prop);
740                 }
741                 if (IsEmptyStr(bstr("nodue"))) {
742                         icaltime_from_webform(&t, "due");
743                         icalcomponent_add_property(vtodo,
744                                                    icalproperty_new_due(t)
745                                 );
746                 }
747                 /** Give this task a UID if it doesn't have one. */
748                 lprintf(9, "Give this task a UID if it doesn't have one.\n");
749                 if (icalcomponent_get_first_property(vtodo,
750                                                      ICAL_UID_PROPERTY) == NULL) {
751                         generate_uuid(buf);
752                         icalcomponent_add_property(vtodo,
753                                                    icalproperty_new_uid(buf)
754                                 );
755                 }
756
757                 /** Increment the sequence ID */
758                 lprintf(9, "Increment the sequence ID\n");
759                 while (prop = icalcomponent_get_first_property(vtodo,
760                                                                ICAL_SEQUENCE_PROPERTY), (prop != NULL) ) {
761                         i = icalproperty_get_sequence(prop);
762                         lprintf(9, "Sequence was %d\n", i);
763                         if (i > sequence) sequence = i;
764                         icalcomponent_remove_property(vtodo, prop);
765                         icalproperty_free(prop);
766                 }
767                 ++sequence;
768                 lprintf(9, "New sequence is %d.  Adding...\n", sequence);
769                 icalcomponent_add_property(vtodo,
770                                            icalproperty_new_sequence(sequence)
771                         );
772
773                 /**
774                  * Encapsulate event into full VCALENDAR component.  Clone it first,
775                  * for two reasons: one, it's easier to just free the whole thing
776                  * when we're done instead of unbundling, but more importantly, we
777                  * can't encapsulate something that may already be encapsulated
778                  * somewhere else.
779                  */
780                 lprintf(9, "Encapsulating into a full VCALENDAR component\n");
781                 encaps = ical_encapsulate_subcomponent(icalcomponent_new_clone(vtodo));
782
783                 /* Serialize it and save it to the message base */
784                 serv_puts("ENT0 1|||4");
785                 serv_getln(buf, sizeof buf);
786                 if (buf[0] == '4') {
787                         serv_puts("Content-type: text/calendar");
788                         serv_puts("");
789                         serv_puts(icalcomponent_as_ical_string(encaps));
790                         serv_puts("000");
791
792                         /**
793                          * Probably not necessary; the server will see the UID
794                          * of the object and delete the old one anyway, but
795                          * just in case...
796                          */
797                         delete_existing = 1;
798                 }
799                 icalcomponent_free(encaps);
800         }
801
802         /**
803          * If the user clicked 'Delete' then explicitly delete the message.
804          */
805         if (havebstr("delete_button")) {
806                 delete_existing = 1;
807         }
808
809         if ( (delete_existing) && (msgnum > 0L) ) {
810                 serv_printf("DELE %ld", lbstr("msgnum"));
811                 serv_getln(buf, sizeof buf);
812         }
813
814         if (created_new_vtodo) {
815                 icalcomponent_free(vtodo);
816         }
817
818         /** Go back to the task list */
819         readloop("readfwd");
820 }
821
822
823
824 /**
825  * \brief generic item handler
826  * Code common to all display handlers.  Given a message number and a MIME
827  * type, we load the message and hunt for that MIME type.  If found, we load
828  * the relevant part, deserialize it into a libical component, filter it for
829  * the requested object type, and feed it to the specified handler.
830  * \param mimetype mimetyp of our object
831  * \param which_kind sort of ical type
832  * \param msgnum number of the mesage in our db
833  * \param callback a funcion \todo
834  *
835  */
836 void display_using_handler(long msgnum, int unread,
837                            icalcomponent_kind which_kind,
838                            void (*callback)(icalcomponent *, long, char*, int)
839         ) 
840 {
841         char buf[1024];
842         char from[128] = "";
843         char mime_partnum[256];
844         char mime_filename[256];
845         char mime_content_type[256];
846         char mime_disposition[256];
847         int mime_length;
848         char relevant_partnum[256];
849         char *relevant_source = NULL;
850         icalcomponent *cal, *c;
851
852         relevant_partnum[0] = '\0';
853         sprintf(buf, "MSG4 %ld", msgnum);       /* we need the mime headers */
854         serv_puts(buf);
855         serv_getln(buf, sizeof buf);
856         if (buf[0] != '1') return;
857
858         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
859                 if (!strncasecmp(buf, "part=", 5)) {
860                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
861                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
862                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
863                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
864                         mime_length = extract_int(&buf[5], 5);
865
866                         if (  (!strcasecmp(mime_content_type, "text/calendar"))
867                               || (!strcasecmp(mime_content_type, "application/ics"))
868                               || (!strcasecmp(mime_content_type, "text/vtodo"))
869                                 ) {
870                                 strcpy(relevant_partnum, mime_partnum);
871                         }
872                 }
873                 else if (!strncasecmp(buf, "from=", 4)) {
874                         extract_token(from, buf, 1, '=', sizeof(from));
875                 }
876         }
877
878         if (!IsEmptyStr(relevant_partnum)) {
879                 relevant_source = load_mimepart(msgnum, relevant_partnum);
880                 if (relevant_source != NULL) {
881
882                         cal = icalcomponent_new_from_string(relevant_source);
883                         if (cal != NULL) {
884
885                                 ical_dezonify(cal);
886
887                                 /** Simple components of desired type */
888                                 if (icalcomponent_isa(cal) == which_kind) {
889                                         callback(cal, msgnum, from, unread);
890                                 }
891
892                                 /** Subcomponents of desired type */
893                                 for (c = icalcomponent_get_first_component(cal,
894                                                                            which_kind);
895                                      (c != 0);
896                                      c = icalcomponent_get_next_component(cal,
897                                                                           which_kind)) {
898                                         callback(c, msgnum, from, unread);
899                                 }
900                                 icalcomponent_free(cal);
901                         }
902                         free(relevant_source);
903                 }
904         }
905         icalmemory_free_ring();
906 }
907
908 /**
909  * \brief display whole calendar
910  * \param msgnum number of the mesage in our db
911  */
912 void display_calendar(long msgnum, int unread) {
913         display_using_handler(msgnum, unread,
914                               ICAL_VEVENT_COMPONENT,
915                               display_individual_cal);
916 }
917
918 /**
919  * \brief display whole taksview
920  * \param msgnum number of the mesage in our db
921  */
922 void display_task(long msgnum, int unread) {
923         display_using_handler(msgnum, unread,
924                               ICAL_VTODO_COMPONENT,
925                               display_individual_cal);
926 }
927
928 /**
929  * \brief display the editor component for a task
930  */
931 void display_edit_task(void) {
932         long msgnum = 0L;
933                         
934         /** Force change the room if we have to */
935         if (havebstr("taskrm")) {
936                 gotoroom((char *)bstr("taskrm"));
937         }
938
939         msgnum = lbstr("msgnum");
940         if (msgnum > 0L) {
941                 /** existing task */
942                 display_using_handler(msgnum, 0,
943                                       ICAL_VTODO_COMPONENT,
944                                       display_edit_individual_task);
945         }
946         else {
947                 /** new task */
948                 display_edit_individual_task(NULL, 0L, "", 0);
949         }
950 }
951
952 /**
953  *\brief save an edited task
954  */
955 void save_task(void) {
956         long msgnum = 0L;
957
958         msgnum = lbstr("msgnum");
959         if (msgnum > 0L) {
960                 display_using_handler(msgnum, 0,
961                                       ICAL_VTODO_COMPONENT,
962                                       save_individual_task);
963         }
964         else {
965                 save_individual_task(NULL, 0L, "", 0);
966         }
967 }
968
969 /**
970  * \brief display the editor component for an event
971  */
972 void display_edit_event(void) {
973         long msgnum = 0L;
974
975         msgnum = lbstr("msgnum");
976         if (msgnum > 0L) {
977                 /* existing event */
978                 display_using_handler(msgnum, 0,
979                                       ICAL_VEVENT_COMPONENT,
980                                       display_edit_individual_event);
981         }
982         else {
983                 /* new event */
984                 display_edit_individual_event(NULL, 0L, "", 0);
985         }
986 }
987
988 /**
989  * \brief save an edited event
990  */
991 void save_event(void) {
992         long msgnum = 0L;
993
994         msgnum = lbstr("msgnum");
995
996         if (msgnum > 0L) {
997                 display_using_handler(msgnum, 0,
998                                       ICAL_VEVENT_COMPONENT,
999                                       save_individual_event);
1000         }
1001         else {
1002                 save_individual_event(NULL, 0L, "", 0);
1003         }
1004 }
1005
1006
1007
1008
1009
1010 /**
1011  * \brief freebusy display (for client software)
1012  * \param req dunno. ?????
1013  */
1014 void do_freebusy(char *req) {
1015         char who[SIZ];
1016         char buf[SIZ];
1017         char *fb;
1018         int len;
1019
1020         extract_token(who, req, 1, ' ', sizeof who);
1021         if (!strncasecmp(who, "/freebusy/", 10)) {
1022                 strcpy(who, &who[10]);
1023         }
1024         unescape_input(who);
1025
1026         len = strlen(who);
1027         if ( (!strcasecmp(&who[len-4], ".vcf"))
1028              || (!strcasecmp(&who[len-4], ".ifb"))
1029              || (!strcasecmp(&who[len-4], ".vfb")) ) {
1030                 who[len-4] = 0;
1031         }
1032
1033         lprintf(9, "freebusy requested for <%s>\n", who);
1034         serv_printf("ICAL freebusy|%s", who);
1035         serv_getln(buf, sizeof buf);
1036
1037         if (buf[0] != '1') {
1038                 wprintf("HTTP/1.1 404 %s\n", &buf[4]);
1039                 output_headers(0, 0, 0, 0, 0, 0);
1040                 wprintf("Content-Type: text/plain\r\n");
1041                 wprintf("\r\n");
1042                 wprintf("%s\n", &buf[4]);
1043                 return;
1044         }
1045
1046         fb = read_server_text();
1047         http_transmit_thing(fb, strlen(fb), "text/calendar", 0);
1048         free(fb);
1049 }
1050