35ee6e05d82aef38aa059787a46099ad8af66bec
[citadel.git] / webcit / messages.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup MsgDisp Functions which deal with the fetching and displaying of messages.
6  * \ingroup WebcitDisplayItems
7  *
8  */
9 /*@{*/
10 #include "webcit.h"
11 #include "vcard.h"
12 #include "webserver.h"
13 #include "groupdav.h"
14
15 #define SUBJ_COL_WIDTH_PCT              50      /**< Mailbox view column width */
16 #define SENDER_COL_WIDTH_PCT            30      /**< Mailbox view column width */
17 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /**< Mailbox view column width */
18
19 /**
20  * Address book entry (keep it short and sweet, it's just a quickie lookup
21  * which we can use to get to the real meat and bones later)
22  */
23 struct addrbookent {
24         char ab_name[64]; /**< name string */
25         long ab_msgnum;   /**< message number of address book entry */
26 };
27
28
29
30 #ifdef HAVE_ICONV
31 /**
32  * \brief  Handle subjects with RFC2047 encoding
33  *  such as:
34  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
35  * \param buf the stringbuffer to process
36  */
37 void utf8ify_rfc822_string(char *buf) {
38         char *start, *end;
39         char newbuf[1024];
40         char charset[128];
41         char encoding[16];
42         char istr[1024];
43         iconv_t ic = (iconv_t)(-1) ;
44         char *ibuf;                /**< Buffer of characters to be converted */
45         char *obuf;                /**< Buffer for converted characters      */
46         size_t ibuflen;    /**< Length of input buffer         */
47         size_t obuflen;    /**< Length of output buffer       */
48         char *isav;                /**< Saved pointer to input buffer   */
49         char *osav;                /**< Saved pointer to output buffer       */
50         int passes = 0;
51
52         while (start=strstr(buf, "=?"), end=strstr(buf, "?="),
53                 ((start != NULL) && (end != NULL) && (end > start)) )
54         {
55                 extract_token(charset, start, 1, '?', sizeof charset);
56                 extract_token(encoding, start, 2, '?', sizeof encoding);
57                 extract_token(istr, start, 3, '?', sizeof istr);
58
59                 /*strcpy(start, "");
60                 ++end;
61                 ++end;*/
62
63                 ibuf = malloc(1024);
64                 isav = ibuf;
65                 if (!strcasecmp(encoding, "B")) {       /**< base64 */
66                         ibuflen = CtdlDecodeBase64(ibuf, istr, strlen(istr));
67                 }
68                 else if (!strcasecmp(encoding, "Q")) {  /**< quoted-printable */
69                         ibuflen = CtdlDecodeQuotedPrintable(ibuf, istr, strlen(istr));
70                 }
71                 else {
72                         strcpy(ibuf, istr);             /**< huh? */
73                         ibuflen = strlen(istr);
74                 }
75
76                 ic = iconv_open("UTF-8", charset);
77                 if (ic != (iconv_t)(-1) ) {
78                         obuf = malloc(1024);
79                         obuflen = 1024;
80                         obuf = (char *) malloc(obuflen);
81                         osav = obuf;
82                         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
83                         osav[1024-obuflen] = 0;
84
85                         end = start;
86                         end++;
87                         strcpy(start, "");
88                         remove_token(end, 0, '?');
89                         remove_token(end, 0, '?');
90                         remove_token(end, 0, '?');
91                         remove_token(end, 0, '?');
92                         strcpy(end, &end[1]);
93
94                         snprintf(newbuf, sizeof newbuf, "%s%s%s", buf, osav, end);
95                         strcpy(buf, newbuf);
96                         free(osav);
97                         iconv_close(ic);
98                 }
99                 else {
100                         end = start;
101                         end++;
102                         strcpy(start, "");
103                         remove_token(end, 0, '?');
104                         remove_token(end, 0, '?');
105                         remove_token(end, 0, '?');
106                         remove_token(end, 0, '?');
107                         strcpy(end, &end[1]);
108
109                         snprintf(newbuf, sizeof newbuf, "%s(unreadable)%s", buf, end);
110                         strcpy(buf, newbuf);
111                 }
112
113                 free(isav);
114
115                 /**
116                  * Since spammers will go to all sorts of absurd lengths to get their
117                  * messages through, there are LOTS of corrupt headers out there.
118                  * So, prevent a really badly formed RFC2047 header from throwing
119                  * this function into an infinite loop.
120                  */
121                 ++passes;
122                 if (passes > 20) return;
123         }
124
125 }
126 #endif
127
128
129 /**
130  * \brief Look for URL's embedded in a buffer and make them linkable.  We use a
131  * target window in order to keep the BBS session in its own window.
132  * \param buf the message buffer
133  */
134 void url(char *buf)
135 {
136
137         int pos;
138         int start, end;
139         char ench;
140         char urlbuf[SIZ];
141         char outbuf[1024];
142
143         start = (-1);
144         end = strlen(buf);
145         ench = 0;
146
147         for (pos = 0; pos < strlen(buf); ++pos) {
148                 if (!strncasecmp(&buf[pos], "http://", 7))
149                         start = pos;
150                 if (!strncasecmp(&buf[pos], "ftp://", 6))
151                         start = pos;
152         }
153
154         if (start < 0)
155                 return;
156
157         if ((start > 0) && (buf[start - 1] == '<'))
158                 ench = '>';
159         if ((start > 0) && (buf[start - 1] == '['))
160                 ench = ']';
161         if ((start > 0) && (buf[start - 1] == '('))
162                 ench = ')';
163         if ((start > 0) && (buf[start - 1] == '{'))
164                 ench = '}';
165
166         for (pos = strlen(buf); pos > start; --pos) {
167                 if ((buf[pos] == ' ') || (buf[pos] == ench))
168                         end = pos;
169         }
170
171         strncpy(urlbuf, &buf[start], end - start);
172         urlbuf[end - start] = 0;
173
174         strncpy(outbuf, buf, start);
175         sprintf(&outbuf[start], "%ca href=%c%s%c TARGET=%c%s%c%c%s%c/A%c",
176                 LB, QU, urlbuf, QU, QU, TARGET, QU, RB, urlbuf, LB, RB);
177         strcat(outbuf, &buf[end]);
178         if ( strlen(outbuf) < 250 )
179                 strcpy(buf, outbuf);
180 }
181
182
183 /**
184  * \brief Turn a vCard "n" (name) field into something displayable.
185  * \param name the name field to convert
186  */
187 void vcard_n_prettyize(char *name)
188 {
189         char *original_name;
190         int i;
191
192         original_name = strdup(name);
193         for (i=0; i<5; ++i) {
194                 if (strlen(original_name) > 0) {
195                         if (original_name[strlen(original_name)-1] == ' ') {
196                                 original_name[strlen(original_name)-1] = 0;
197                         }
198                         if (original_name[strlen(original_name)-1] == ';') {
199                                 original_name[strlen(original_name)-1] = 0;
200                         }
201                 }
202         }
203         strcpy(name, "");
204         for (i=0; i<strlen(original_name); ++i) {
205                 if (original_name[i] == ';') {
206                         strcat(name, ", ");
207                 }
208                 else {
209                         name[strlen(name)+1] = 0;
210                         name[strlen(name)] = original_name[i];
211                 }
212         }
213         free(original_name);
214 }
215
216
217
218
219 /**
220  * \brief preparse a vcard name
221  * display_vcard() calls this after parsing the textual vCard into
222  * our 'struct vCard' data object.
223  * This gets called instead of display_parsed_vcard() if we are only looking
224  * to extract the person's name instead of displaying the card.
225  * \param v the vcard to retrieve the name from
226  * \param storename where to put the name at
227  */
228 void fetchname_parsed_vcard(struct vCard *v, char *storename) {
229         char *name;
230
231         strcpy(storename, "");
232
233         name = vcard_get_prop(v, "n", 1, 0, 0);
234         if (name != NULL) {
235                 strcpy(storename, name);
236                 /* vcard_n_prettyize(storename); */
237         }
238
239 }
240
241
242
243 /**
244  * \brief html print a vcard
245  * display_vcard() calls this after parsing the textual vCard into
246  * our 'struct vCard' data object.
247  *
248  * Set 'full' to nonzero to display the full card, otherwise it will only
249  * show a summary line.
250  *
251  * This code is a bit ugly, so perhaps an explanation is due: we do this
252  * in two passes through the vCard fields.  On the first pass, we process
253  * fields we understand, and then render them in a pretty fashion at the
254  * end.  Then we make a second pass, outputting all the fields we don't
255  * understand in a simple two-column name/value format.
256  * \param v the vCard to display
257  * \param full display all items of the vcard?
258  */
259 void display_parsed_vcard(struct vCard *v, int full) {
260         int i, j;
261         char buf[SIZ];
262         char *name;
263         int is_qp = 0;
264         int is_b64 = 0;
265         char *thisname, *thisvalue;
266         char firsttoken[SIZ];
267         int pass;
268
269         char fullname[SIZ];
270         char title[SIZ];
271         char org[SIZ];
272         char phone[SIZ];
273         char mailto[SIZ];
274
275         strcpy(fullname, "");
276         strcpy(phone, "");
277         strcpy(mailto, "");
278         strcpy(title, "");
279         strcpy(org, "");
280
281         if (!full) {
282                 wprintf("<TD>");
283                 name = vcard_get_prop(v, "fn", 1, 0, 0);
284                 if (name != NULL) {
285                         escputs(name);
286                 }
287                 else if (name = vcard_get_prop(v, "n", 1, 0, 0), name != NULL) {
288                         strcpy(fullname, name);
289                         vcard_n_prettyize(fullname);
290                         escputs(fullname);
291                 }
292                 else {
293                         wprintf("&nbsp;");
294                 }
295                 wprintf("</TD>");
296                 return;
297         }
298
299         wprintf("<div align=center><table bgcolor=#aaaaaa width=50%%>");
300         for (pass=1; pass<=2; ++pass) {
301
302                 if (v->numprops) for (i=0; i<(v->numprops); ++i) {
303
304                         thisname = strdup(v->prop[i].name);
305                         extract_token(firsttoken, thisname, 0, ';', sizeof firsttoken);
306         
307                         for (j=0; j<num_tokens(thisname, ';'); ++j) {
308                                 extract_token(buf, thisname, j, ';', sizeof buf);
309                                 if (!strcasecmp(buf, "encoding=quoted-printable")) {
310                                         is_qp = 1;
311                                         remove_token(thisname, j, ';');
312                                 }
313                                 if (!strcasecmp(buf, "encoding=base64")) {
314                                         is_b64 = 1;
315                                         remove_token(thisname, j, ';');
316                                 }
317                         }
318         
319                         if (is_qp) {
320                                 thisvalue = malloc(strlen(v->prop[i].value) + 50);
321                                 j = CtdlDecodeQuotedPrintable(
322                                         thisvalue, v->prop[i].value,
323                                         strlen(v->prop[i].value) );
324                                 thisvalue[j] = 0;
325                         }
326                         else if (is_b64) {
327                                 thisvalue = malloc(strlen(v->prop[i].value) + 50);
328                                 CtdlDecodeBase64(
329                                         thisvalue, v->prop[i].value,
330                                         strlen(v->prop[i].value) );
331                         }
332                         else {
333                                 thisvalue = strdup(v->prop[i].value);
334                         }
335         
336                         /** Various fields we may encounter ***/
337         
338                         /** N is name, but only if there's no FN already there */
339                         if (!strcasecmp(firsttoken, "n")) {
340                                 if (strlen(fullname) == 0) {
341                                         strcpy(fullname, thisvalue);
342                                         vcard_n_prettyize(fullname);
343                                 }
344                         }
345         
346                         /** FN (full name) is a true 'display name' field */
347                         else if (!strcasecmp(firsttoken, "fn")) {
348                                 strcpy(fullname, thisvalue);
349                         }
350
351                         /** title */
352                         else if (!strcasecmp(firsttoken, "title")) {
353                                 strcpy(title, thisvalue);
354                         }
355         
356                         /** organization */
357                         else if (!strcasecmp(firsttoken, "org")) {
358                                 strcpy(org, thisvalue);
359                         }
360         
361                         else if (!strcasecmp(firsttoken, "email")) {
362                                 if (strlen(mailto) > 0) strcat(mailto, "<br />");
363                                 strcat(mailto,
364                                         "<a href=\"display_enter"
365                                         "?force_room=_MAIL_?recp=");
366
367                                 urlesc(&mailto[strlen(mailto)], fullname);
368                                 urlesc(&mailto[strlen(mailto)], " <");
369                                 urlesc(&mailto[strlen(mailto)], thisvalue);
370                                 urlesc(&mailto[strlen(mailto)], ">");
371
372                                 strcat(mailto, "\">");
373                                 stresc(&mailto[strlen(mailto)], thisvalue, 1, 1);
374                                 strcat(mailto, "</A>");
375                         }
376                         else if (!strcasecmp(firsttoken, "tel")) {
377                                 if (strlen(phone) > 0) strcat(phone, "<br />");
378                                 strcat(phone, thisvalue);
379                                 for (j=0; j<num_tokens(thisname, ';'); ++j) {
380                                         extract_token(buf, thisname, j, ';', sizeof buf);
381                                         if (!strcasecmp(buf, "tel"))
382                                                 strcat(phone, "");
383                                         else if (!strcasecmp(buf, "work"))
384                                                 strcat(phone, _(" (work)"));
385                                         else if (!strcasecmp(buf, "home"))
386                                                 strcat(phone, _(" (home)"));
387                                         else if (!strcasecmp(buf, "cell"))
388                                                 strcat(phone, _(" (cell)"));
389                                         else {
390                                                 strcat(phone, " (");
391                                                 strcat(phone, buf);
392                                                 strcat(phone, ")");
393                                         }
394                                 }
395                         }
396                         else if (!strcasecmp(firsttoken, "adr")) {
397                                 if (pass == 2) {
398                                         wprintf("<TR><TD>");
399                                         wprintf(_("Address:"));
400                                         wprintf("</TD><TD>");
401                                         for (j=0; j<num_tokens(thisvalue, ';'); ++j) {
402                                                 extract_token(buf, thisvalue, j, ';', sizeof buf);
403                                                 if (strlen(buf) > 0) {
404                                                         escputs(buf);
405                                                         if (j<3) wprintf("<br />");
406                                                         else wprintf(" ");
407                                                 }
408                                         }
409                                         wprintf("</TD></TR>\n");
410                                 }
411                         }
412                         else if (!strcasecmp(firsttoken, "version")) {
413                                 /* ignore */
414                         }
415                         else if (!strcasecmp(firsttoken, "rev")) {
416                                 /* ignore */
417                         }
418                         else if (!strcasecmp(firsttoken, "label")) {
419                                 /* ignore */
420                         }
421                         else {
422
423                                 /*** Don't show extra fields.  They're ugly.
424                                 if (pass == 2) {
425                                         wprintf("<TR><TD>");
426                                         escputs(thisname);
427                                         wprintf("</TD><TD>");
428                                         escputs(thisvalue);
429                                         wprintf("</TD></TR>\n");
430                                 }
431                                 ***/
432                         }
433         
434                         free(thisname);
435                         free(thisvalue);
436                 }
437         
438                 if (pass == 1) {
439                         wprintf("<TR BGCOLOR=\"#AAAAAA\">"
440                         "<TD COLSPAN=2 BGCOLOR=\"#FFFFFF\">"
441                         "<IMG ALIGN=CENTER src=\"static/viewcontacts_48x.gif\">"
442                         "<FONT SIZE=+1><B>");
443                         escputs(fullname);
444                         wprintf("</B></FONT>");
445                         if (strlen(title) > 0) {
446                                 wprintf("<div align=right>");
447                                 escputs(title);
448                                 wprintf("</div>");
449                         }
450                         if (strlen(org) > 0) {
451                                 wprintf("<div align=right>");
452                                 escputs(org);
453                                 wprintf("</div>");
454                         }
455                         wprintf("</TD></TR>\n");
456                 
457                         if (strlen(phone) > 0) {
458                                 wprintf("<tr><td>");
459                                 wprintf(_("Telephone:"));
460                                 wprintf("</td><td>%s</td></tr>\n", phone);
461                         }
462                         if (strlen(mailto) > 0) {
463                                 wprintf("<tr><td>");
464                                 wprintf(_("E-mail:"));
465                                 wprintf("</td><td>%s</td></tr>\n", mailto);
466                         }
467                 }
468
469         }
470
471         wprintf("</table></div>\n");
472 }
473
474
475
476 /**
477  * \brief  Display a textual vCard
478  * (Converts to a vCard object and then calls the actual display function)
479  * Set 'full' to nonzero to display the whole card instead of a one-liner.
480  * Or, if "storename" is non-NULL, just store the person's name in that
481  * buffer instead of displaying the card at all.
482  * \param vcard_source the buffer containing the vcard text
483  * \param alpha what???
484  * \param full should we usse all lines?
485  * \param storename where to store???
486  */
487 void display_vcard(char *vcard_source, char alpha, int full, char *storename) {
488         struct vCard *v;
489         char *name;
490         char buf[SIZ];
491         char this_alpha = 0;
492
493         v = vcard_load(vcard_source);
494         if (v == NULL) return;
495
496         name = vcard_get_prop(v, "n", 1, 0, 0);
497         if (name != NULL) {
498                 strcpy(buf, name);
499                 this_alpha = buf[0];
500         }
501
502         if (storename != NULL) {
503                 fetchname_parsed_vcard(v, storename);
504         }
505         else if (       (alpha == 0)
506                         || ((isalpha(alpha)) && (tolower(alpha) == tolower(this_alpha)) )
507                         || ((!isalpha(alpha)) && (!isalpha(this_alpha)))
508                 ) {
509                 display_parsed_vcard(v, full);
510         }
511
512         vcard_free(v);
513 }
514
515
516 /**
517  * \brief I wanna SEE that message!  
518  * \param msgnum the citadel number of the message to display
519  * \param printable_view are we doing a print view?
520  * \param section Optional for encapsulated message/rfc822 submessage)
521  */
522 void read_message(long msgnum, int printable_view, char *section) {
523         char buf[SIZ];
524         char mime_partnum[256];
525         char mime_filename[256];
526         char mime_content_type[256];
527         char mime_charset[256];
528         char mime_disposition[256];
529         int mime_length;
530         char mime_http[SIZ];
531         char mime_submessages[256];
532         char m_subject[256];
533         char m_cc[1024];
534         char from[256];
535         char node[256];
536         char rfca[256];
537         char reply_to[512];
538         char reply_all[4096];
539         char now[64];
540         int format_type = 0;
541         int nhdr = 0;
542         int bq = 0;
543         int i = 0;
544         char vcard_partnum[256];
545         char cal_partnum[256];
546         char *part_source = NULL;
547 #ifdef HAVE_ICONV
548         iconv_t ic = (iconv_t)(-1) ;
549         char *ibuf;                /**< Buffer of characters to be converted */
550         char *obuf;                /**< Buffer for converted characters      */
551         size_t ibuflen;    /**< Length of input buffer         */
552         size_t obuflen;    /**< Length of output buffer       */
553         char *osav;                /**< Saved pointer to output buffer       */
554 #endif
555
556         strcpy(from, "");
557         strcpy(node, "");
558         strcpy(rfca, "");
559         strcpy(reply_to, "");
560         strcpy(reply_all, "");
561         strcpy(vcard_partnum, "");
562         strcpy(cal_partnum, "");
563         strcpy(mime_http, "");
564         strcpy(mime_content_type, "text/plain");
565         strcpy(mime_charset, "us-ascii");
566         strcpy(mime_submessages, "");
567
568         serv_printf("MSG4 %ld|%s", msgnum, section);
569         serv_getln(buf, sizeof buf);
570         if (buf[0] != '1') {
571                 wprintf("<STRONG>");
572                 wprintf(_("ERROR:"));
573                 wprintf("</STRONG> %s<br />\n", &buf[4]);
574                 return;
575         }
576
577         /** begin everythingamundo table */
578         if (!printable_view) {
579                 wprintf("<div class=\"fix_scrollbar_bug\">\n");
580                 wprintf("<table width=100%% border=1 cellspacing=0 "
581                         "cellpadding=0><TR><TD>\n");
582         }
583
584         /** begin message header table */
585         wprintf("<table width=100%% border=0 cellspacing=0 "
586                 "cellpadding=1 bgcolor=\"#CCCCCC\"><tr><td>\n");
587
588         wprintf("<span class=\"message_header\">");
589         strcpy(m_subject, "");
590         strcpy(m_cc, "");
591
592         while (serv_getln(buf, sizeof buf), strcasecmp(buf, "text")) {
593                 if (!strcmp(buf, "000")) {
594                         wprintf("<i>");
595                         wprintf(_("unexpected end of message"));
596                         wprintf("</i><br /><br />\n");
597                         wprintf("</span>\n");
598                         return;
599                 }
600                 if (!strncasecmp(buf, "nhdr=yes", 8))
601                         nhdr = 1;
602                 if (nhdr == 1)
603                         buf[0] = '_';
604                 if (!strncasecmp(buf, "type=", 5))
605                         format_type = atoi(&buf[5]);
606                 if (!strncasecmp(buf, "from=", 5)) {
607                         strcpy(from, &buf[5]);
608                         wprintf(_("from "));
609                         wprintf("<a href=\"showuser?who=");
610 #ifdef HAVE_ICONV
611                         utf8ify_rfc822_string(from);
612 #endif
613                         urlescputs(from);
614                         wprintf("\">");
615                         escputs(from);
616                         wprintf("</a> ");
617                 }
618                 if (!strncasecmp(buf, "subj=", 5)) {
619                         safestrncpy(m_subject, &buf[5], sizeof m_subject);
620                 }
621                 if (!strncasecmp(buf, "cccc=", 5)) {
622                         safestrncpy(m_cc, &buf[5], sizeof m_cc);
623                         if (strlen(reply_all) > 0) {
624                                 strcat(reply_all, ", ");
625                         }
626                         safestrncpy(&reply_all[strlen(reply_all)], &buf[5],
627                                 (sizeof reply_all - strlen(reply_all)) );
628                 }
629                 if ((!strncasecmp(buf, "hnod=", 5))
630                     && (strcasecmp(&buf[5], serv_info.serv_humannode))) {
631                         wprintf("(%s) ", &buf[5]);
632                 }
633                 if ((!strncasecmp(buf, "room=", 5))
634                     && (strcasecmp(&buf[5], WC->wc_roomname))
635                     && (strlen(&buf[5])>0) ) {
636                         wprintf(_("in "));
637                         wprintf("%s&gt; ", &buf[5]);
638                 }
639                 if (!strncasecmp(buf, "rfca=", 5)) {
640                         strcpy(rfca, &buf[5]);
641                         wprintf("&lt;");
642                         escputs(rfca);
643                         wprintf("&gt; ");
644                 }
645
646                 if (!strncasecmp(buf, "node=", 5)) {
647                         strcpy(node, &buf[5]);
648                         if ( ((WC->room_flags & QR_NETWORK)
649                         || ((strcasecmp(&buf[5], serv_info.serv_nodename)
650                         && (strcasecmp(&buf[5], serv_info.serv_fqdn)))))
651                         && (strlen(rfca)==0)
652                         ) {
653                                 wprintf("@%s ", &buf[5]);
654                         }
655                 }
656                 if (!strncasecmp(buf, "rcpt=", 5)) {
657                         wprintf(_("to "));
658                         if (strlen(reply_all) > 0) {
659                                 strcat(reply_all, ", ");
660                         }
661                         safestrncpy(&reply_all[strlen(reply_all)], &buf[5],
662                                 (sizeof reply_all - strlen(reply_all)) );
663 #ifdef HAVE_ICONV
664                         utf8ify_rfc822_string(&buf[5]);
665 #endif
666                         escputs(&buf[5]);
667                         wprintf(" ");
668                 }
669                 if (!strncasecmp(buf, "time=", 5)) {
670                         fmt_date(now, atol(&buf[5]), 0);
671                         wprintf("%s ", now);
672                 }
673
674                 if (!strncasecmp(buf, "part=", 5)) {
675                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
676                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
677                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
678                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
679                         mime_length = extract_int(&buf[5], 5);
680
681                         if (!strcasecmp(mime_content_type, "message/rfc822")) {
682                                 if (strlen(mime_submessages) > 0) {
683                                         strcat(mime_submessages, "|");
684                                 }
685                                 strcat(mime_submessages, mime_partnum);
686                         }
687                         else if ((!strcasecmp(mime_disposition, "inline"))
688                            && (!strncasecmp(mime_content_type, "image/", 6)) ){
689                                 snprintf(&mime_http[strlen(mime_http)],
690                                         (sizeof(mime_http) - strlen(mime_http) - 1),
691                                         "<img src=\"mimepart/%ld/%s/%s\">",
692                                         msgnum, mime_partnum, mime_filename);
693                         }
694                         else if ( (!strcasecmp(mime_disposition, "attachment")) 
695                              || (!strcasecmp(mime_disposition, "inline")) ) {
696                                 snprintf(&mime_http[strlen(mime_http)],
697                                         (sizeof(mime_http) - strlen(mime_http) - 1),
698                                         "<img src=\"static/diskette_24x.gif\" "
699                                         "border=0 align=middle>\n"
700                                         "%s (%s, %d bytes) [ "
701                                         "<a href=\"mimepart/%ld/%s/%s\""
702                                         "target=\"wc.%ld.%s\">%s</a>"
703                                         " | "
704                                         "<a href=\"mimepart_download/%ld/%s/%s\">%s</a>"
705                                         " ]<br />\n",
706                                         mime_filename,
707                                         mime_content_type, mime_length,
708                                         msgnum, mime_partnum, mime_filename,
709                                         msgnum, mime_partnum,
710                                         _("View"),
711                                         msgnum, mime_partnum, mime_filename,
712                                         _("Download")
713                                 );
714                         }
715
716                         /** begin handler prep ***/
717                         if (!strcasecmp(mime_content_type, "text/x-vcard")) {
718                                 strcpy(vcard_partnum, mime_partnum);
719                         }
720
721                         if (!strcasecmp(mime_content_type, "text/calendar")) {
722                                 strcpy(cal_partnum, mime_partnum);
723                         }
724
725                         /** end handler prep ***/
726
727                 }
728
729         }
730
731         /** Generate a reply-to address */
732         if (strlen(rfca) > 0) {
733                 strcpy(reply_to, rfca);
734         }
735         else {
736                 if ( (strlen(node) > 0)
737                    && (strcasecmp(node, serv_info.serv_nodename))
738                    && (strcasecmp(node, serv_info.serv_humannode)) ) {
739                         snprintf(reply_to, sizeof(reply_to), "%s @ %s",
740                                 from, node);
741                 }
742                 else {
743                         snprintf(reply_to, sizeof(reply_to), "%s", from);
744                 }
745         }
746
747         if (nhdr == 1) {
748                 wprintf("****");
749         }
750
751         wprintf("</span>");
752 #ifdef HAVE_ICONV
753         utf8ify_rfc822_string(m_cc);
754         utf8ify_rfc822_string(m_subject);
755 #endif
756         if (strlen(m_cc) > 0) {
757                 wprintf("<br />"
758                         "<span class=\"message_subject\">");
759                 wprintf(_("CC:"));
760                 wprintf(" ");
761                 escputs(m_cc);
762                 wprintf("</span>");
763         }
764         if (strlen(m_subject) > 0) {
765                 wprintf("<br />"
766                         "<span class=\"message_subject\">");
767                 wprintf(_("Subject:"));
768                 wprintf(" ");
769                 escputs(m_subject);
770                 wprintf("</span>");
771         }
772         wprintf("</td>\n");
773
774         /** start msg buttons */
775         if (!printable_view) {
776                 wprintf("<td align=right><span class=\"msgbuttons\">\n");
777
778                 /** Reply */
779                 if ( (WC->wc_view == VIEW_MAILBOX) || (WC->wc_view == VIEW_BBS) ) {
780                         wprintf("<a href=\"display_enter");
781                         if (WC->is_mailbox) {
782                                 wprintf("?replyquote=%ld", msgnum);
783                         }
784                         wprintf("?recp=");
785                         urlescputs(reply_to);
786                         if (strlen(m_subject) > 0) {
787                                 wprintf("?subject=");
788                                 if (strncasecmp(m_subject, "Re:", 3)) wprintf("Re:%20");
789                                 urlescputs(m_subject);
790                         }
791                         wprintf("\">[%s]</a> ", _("Reply"));
792                 }
793
794                 /** ReplyQuoted */
795                 if ( (WC->wc_view == VIEW_MAILBOX) || (WC->wc_view == VIEW_BBS) ) {
796                         if (!WC->is_mailbox) {
797                                 wprintf("<a href=\"display_enter");
798                                 wprintf("?replyquote=%ld", msgnum);
799                                 wprintf("?recp=");
800                                 urlescputs(reply_to);
801                                 if (strlen(m_subject) > 0) {
802                                         wprintf("?subject=");
803                                         if (strncasecmp(m_subject, "Re:", 3)) wprintf("Re:%20");
804                                         urlescputs(m_subject);
805                                 }
806                                 wprintf("\">[%s]</a> ", _("ReplyQuoted"));
807                         }
808                 }
809
810                 /** ReplyAll */
811                 if (WC->wc_view == VIEW_MAILBOX) {
812                         wprintf("<a href=\"display_enter");
813                         wprintf("?replyquote=%ld", msgnum);
814                         wprintf("?recp=");
815                         urlescputs(reply_to);
816                         wprintf("?cc=");
817                         urlescputs(reply_all);
818                         if (strlen(m_subject) > 0) {
819                                 wprintf("?subject=");
820                                 if (strncasecmp(m_subject, "Re:", 3)) wprintf("Re:%20");
821                                 urlescputs(m_subject);
822                         }
823                         wprintf("\">[%s]</a> ", _("ReplyAll"));
824                 }
825
826                 /** Forward */
827                 if (WC->wc_view == VIEW_MAILBOX) {
828                         wprintf("<a href=\"display_enter?fwdquote=%ld?subject=", msgnum);
829                         if (strncasecmp(m_subject, "Fwd:", 4)) wprintf("Fwd:%20");
830                         urlescputs(m_subject);
831                         wprintf("\">[%s]</a> ", _("Forward"));
832                 }
833
834                 /** If this is one of my own rooms, or if I'm an Aide or Room Aide, I can move/delete */
835                 if ( (WC->is_room_aide) || (WC->is_mailbox) ) {
836                         /** Move */
837                         wprintf("<a href=\"confirm_move_msg?msgid=%ld\">[%s]</a> ",
838                                 msgnum, _("Move"));
839         
840                         /** Delete */
841                         wprintf("<a href=\"delete_msg?msgid=%ld\" "
842                                 "onClick=\"return confirm('%s');\">"
843                                 "[%s]</a> ", msgnum, _("Delete this message?"), _("Delete")
844                         );
845                 }
846
847                 /** Headers */
848                 wprintf("<a href=\"#\" onClick=\"window.open('msgheaders/%ld', 'headers%ld', 'toolbar=no,location=no,directories=no,copyhistory=no,status=yes,scrollbars=yes,resizable=yes,width=600,height=400'); \" >"
849                         "[%s]</a>", msgnum, msgnum, _("Headers"));
850
851
852                 /** Print */
853                 wprintf("<a href=\"#\" onClick=\"window.open('printmsg/%ld', 'print%ld', 'toolbar=no,location=no,directories=no,copyhistory=no,status=yes,scrollbars=yes,resizable=yes,width=600,height=400'); \" >"
854                         "[%s]</a>", msgnum, msgnum, _("Print"));
855
856                 wprintf("</span></td>");
857         }
858
859         wprintf("</tr></table>\n");
860
861         /** Begin body */
862         wprintf("<table border=0 width=100%% bgcolor=\"#FFFFFF\" "
863                 "cellpadding=1 cellspacing=0><tr><td>");
864
865         /**
866          * Learn the content type
867          */
868         strcpy(mime_content_type, "text/plain");
869         while (serv_getln(buf, sizeof buf), (strlen(buf) > 0)) {
870                 if (!strcmp(buf, "000")) {
871                         wprintf("<i>");
872                         wprintf(_("unexpected end of message"));
873                         wprintf("</i><br /><br />\n");
874                         goto ENDBODY;
875                 }
876                 if (!strncasecmp(buf, "Content-type: ", 14)) {
877                         safestrncpy(mime_content_type, &buf[14],
878                                 sizeof(mime_content_type));
879                         for (i=0; i<strlen(mime_content_type); ++i) {
880                                 if (!strncasecmp(&mime_content_type[i], "charset=", 8)) {
881                                         safestrncpy(mime_charset, &mime_content_type[i+8],
882                                                 sizeof mime_charset);
883                                 }
884                         }
885                         for (i=0; i<strlen(mime_content_type); ++i) {
886                                 if (mime_content_type[i] == ';') {
887                                         mime_content_type[i] = 0;
888                                 }
889                         }
890                 }
891         }
892
893         /** Set up a character set conversion if we need to (and if we can) */
894 #ifdef HAVE_ICONV
895         if (strchr(mime_charset, ';')) strcpy(strchr(mime_charset, ';'), "");
896         if ( (strcasecmp(mime_charset, "us-ascii"))
897            && (strcasecmp(mime_charset, "UTF-8"))
898            && (strcasecmp(mime_charset, ""))
899         ) {
900                 ic = iconv_open("UTF-8", mime_charset);
901                 if (ic == (iconv_t)(-1) ) {
902                         lprintf(5, "%s:%d iconv_open(UTF-8, %s) failed: %s\n",
903                                 __FILE__, __LINE__, mime_charset, strerror(errno));
904                 }
905         }
906 #endif
907
908         /** Messages in legacy Citadel variformat get handled thusly... */
909         if (!strcasecmp(mime_content_type, "text/x-citadel-variformat")) {
910                 fmout("JUSTIFY");
911         }
912
913         /** Boring old 80-column fixed format text gets handled this way... */
914         else if ( (!strcasecmp(mime_content_type, "text/plain"))
915                 || (!strcasecmp(mime_content_type, "text")) ) {
916                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
917                         if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0;
918                         if (buf[strlen(buf)-1] == '\r') buf[strlen(buf)-1] = 0;
919
920 #ifdef HAVE_ICONV
921                         if (ic != (iconv_t)(-1) ) {
922                                 ibuf = buf;
923                                 ibuflen = strlen(ibuf);
924                                 obuflen = SIZ;
925                                 obuf = (char *) malloc(obuflen);
926                                 osav = obuf;
927                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
928                                 osav[SIZ-obuflen] = 0;
929                                 safestrncpy(buf, osav, sizeof buf);
930                                 free(osav);
931                         }
932 #endif
933
934                         while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
935                                 buf[strlen(buf) - 1] = 0;
936                         if ((bq == 0) &&
937                         ((!strncmp(buf, ">", 1)) || (!strncmp(buf, " >", 2)) )) {
938                                 wprintf("<blockquote>");
939                                 bq = 1;
940                         } else if ((bq == 1) &&
941                                 (strncmp(buf, ">", 1)) && (strncmp(buf, " >", 2)) ) {
942                                 wprintf("</blockquote>");
943                                 bq = 0;
944                         }
945                         wprintf("<tt>");
946                         url(buf);
947                         escputs(buf);
948                         wprintf("</tt><br />\n");
949                 }
950                 wprintf("</i><br />");
951         }
952
953         else /** HTML is fun, but we've got to strip it first */
954         if (!strcasecmp(mime_content_type, "text/html")) {
955                 output_html(mime_charset, (WC->wc_view == VIEW_WIKI ? 1 : 0));
956         }
957
958         /** Unknown weirdness */
959         else {
960                 wprintf(_("I don't know how to display %s"), mime_content_type);
961                 wprintf("<br />\n", mime_content_type);
962                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) { }
963         }
964
965         /** If there are attached submessages, display them now... */
966         if ( (strlen(mime_submessages) > 0) && (!section[0]) ) {
967                 for (i=0; i<num_tokens(mime_submessages, '|'); ++i) {
968                         extract_token(buf, mime_submessages, i, '|', sizeof buf);
969                         /** use printable_view to suppress buttons */
970                         wprintf("<blockquote>");
971                         read_message(msgnum, 1, buf);
972                         wprintf("</blockquote>");
973                 }
974         }
975
976
977         /** Afterwards, offer links to download attachments 'n' such */
978         if ( (strlen(mime_http) > 0) && (!section[0]) ) {
979                 wprintf("%s", mime_http);
980         }
981
982         /** Handler for vCard parts */
983         if (strlen(vcard_partnum) > 0) {
984                 part_source = load_mimepart(msgnum, vcard_partnum);
985                 if (part_source != NULL) {
986
987                         /** If it's my vCard I can edit it */
988                         if (    (!strcasecmp(WC->wc_roomname, USERCONFIGROOM))
989                                 || (!strcasecmp(&WC->wc_roomname[11], USERCONFIGROOM))
990                                 || (WC->wc_view == VIEW_ADDRESSBOOK)
991                         ) {
992                                 wprintf("<a href=\"edit_vcard?"
993                                         "msgnum=%ld?partnum=%s\">",
994                                         msgnum, vcard_partnum);
995                                 wprintf("[%s]</a>", _("edit"));
996                         }
997
998                         /** In all cases, display the full card */
999                         display_vcard(part_source, 0, 1, NULL);
1000                 }
1001         }
1002
1003         /** Handler for calendar parts */
1004         if (strlen(cal_partnum) > 0) {
1005                 part_source = load_mimepart(msgnum, cal_partnum);
1006                 if (part_source != NULL) {
1007                         cal_process_attachment(part_source,
1008                                                 msgnum, cal_partnum);
1009                 }
1010         }
1011
1012         if (part_source) {
1013                 free(part_source);
1014                 part_source = NULL;
1015         }
1016
1017 ENDBODY:
1018         wprintf("</td></tr></table>\n");
1019
1020         /** end everythingamundo table */
1021         if (!printable_view) {
1022                 wprintf("</td></tr></table>\n");
1023                 wprintf("</div><br />\n");
1024         }
1025
1026 #ifdef HAVE_ICONV
1027         if (ic != (iconv_t)(-1) ) {
1028                 iconv_close(ic);
1029         }
1030 #endif
1031 }
1032
1033
1034
1035 /**
1036  * \brief Unadorned HTML output of an individual message, suitable
1037  * for placing in a hidden iframe, for printing, or whatever
1038  *
1039  * \param msgnum_as_string Message number, as a string instead of as a long int
1040  */
1041 void embed_message(char *msgnum_as_string) {
1042         long msgnum = 0L;
1043
1044         msgnum = atol(msgnum_as_string);
1045         begin_ajax_response();
1046         read_message(msgnum, 0, "");
1047         end_ajax_response();
1048 }
1049
1050
1051 /**
1052  * \brief Printable view of a message
1053  *
1054  * \param msgnum_as_string Message number, as a string instead of as a long int
1055  */
1056 void print_message(char *msgnum_as_string) {
1057         long msgnum = 0L;
1058
1059         msgnum = atol(msgnum_as_string);
1060         output_headers(0, 0, 0, 0, 0, 0);
1061
1062         wprintf("Content-type: text/html\r\n"
1063                 "Server: %s\r\n"
1064                 "Connection: close\r\n",
1065                 SERVER);
1066         begin_burst();
1067
1068         wprintf("\r\n\r\n<html>\n"
1069                 "<head><title>Printable view</title></head>\n"
1070                 "<body onLoad=\" window.print(); window.close(); \">\n"
1071         );
1072         
1073         read_message(msgnum, 1, "");
1074
1075         wprintf("\n</body></html>\n\n");
1076         wDumpContent(0);
1077 }
1078
1079
1080
1081 /**
1082  * \brief Display a message's headers
1083  *
1084  * \param msgnum_as_string Message number, as a string instead of as a long int
1085  */
1086 void display_headers(char *msgnum_as_string) {
1087         long msgnum = 0L;
1088         char buf[1024];
1089
1090         msgnum = atol(msgnum_as_string);
1091         output_headers(0, 0, 0, 0, 0, 0);
1092
1093         wprintf("Content-type: text/plain\r\n"
1094                 "Server: %s\r\n"
1095                 "Connection: close\r\n",
1096                 SERVER);
1097         begin_burst();
1098
1099         serv_printf("MSG2 %ld|3", msgnum);
1100         serv_getln(buf, sizeof buf);
1101         if (buf[0] == '1') {
1102                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1103                         wprintf("%s\n", buf);
1104                 }
1105         }
1106
1107         wDumpContent(0);
1108 }
1109
1110
1111
1112 /**
1113  * \brief Read message in simple, JavaScript-embeddable form for 'forward'
1114  *        or 'reply quoted' operations.
1115  *
1116  * NOTE: it is VITALLY IMPORTANT that we output no single-quotes or linebreaks
1117  *       in this function.  Doing so would throw a JavaScript error in the
1118  *       'supplied text' argument to the editor.
1119  *
1120  * \param msgnum Message number of the message we want to quote
1121  * \param forward_attachments Nonzero if we want attachments to be forwarded
1122  */
1123 void pullquote_message(long msgnum, int forward_attachments, int include_headers) {
1124         char buf[SIZ];
1125         char mime_partnum[256];
1126         char mime_filename[256];
1127         char mime_content_type[256];
1128         char mime_charset[256];
1129         char mime_disposition[256];
1130         int mime_length;
1131         char mime_http[SIZ];
1132         char *attachments = NULL;
1133         int num_attachments = 0;
1134         struct wc_attachment *att, *aptr;
1135         char m_subject[256];
1136         char from[256];
1137         char node[256];
1138         char rfca[256];
1139         char reply_to[512];
1140         char now[256];
1141         int format_type = 0;
1142         int nhdr = 0;
1143         int bq = 0;
1144         int i = 0;
1145 #ifdef HAVE_ICONV
1146         iconv_t ic = (iconv_t)(-1) ;
1147         char *ibuf;                /**< Buffer of characters to be converted */
1148         char *obuf;                /**< Buffer for converted characters      */
1149         size_t ibuflen;    /**< Length of input buffer         */
1150         size_t obuflen;    /**< Length of output buffer       */
1151         char *osav;                /**< Saved pointer to output buffer       */
1152 #endif
1153
1154         strcpy(from, "");
1155         strcpy(node, "");
1156         strcpy(rfca, "");
1157         strcpy(reply_to, "");
1158         strcpy(mime_http, "");
1159         strcpy(mime_content_type, "text/plain");
1160         strcpy(mime_charset, "us-ascii");
1161
1162         serv_printf("MSG4 %ld", msgnum);
1163         serv_getln(buf, sizeof buf);
1164         if (buf[0] != '1') {
1165                 wprintf(_("ERROR:"));
1166                 wprintf("%s<br />", &buf[4]);
1167                 return;
1168         }
1169
1170         strcpy(m_subject, "");
1171
1172         while (serv_getln(buf, sizeof buf), strcasecmp(buf, "text")) {
1173                 if (!strcmp(buf, "000")) {
1174                         wprintf(_("unexpected end of message"));
1175                         return;
1176                 }
1177                 if (include_headers) {
1178                         if (!strncasecmp(buf, "nhdr=yes", 8))
1179                                 nhdr = 1;
1180                         if (nhdr == 1)
1181                                 buf[0] = '_';
1182                         if (!strncasecmp(buf, "type=", 5))
1183                                 format_type = atoi(&buf[5]);
1184                         if (!strncasecmp(buf, "from=", 5)) {
1185                                 strcpy(from, &buf[5]);
1186                                 wprintf(_("from "));
1187 #ifdef HAVE_ICONV
1188                                 utf8ify_rfc822_string(from);
1189 #endif
1190                                 msgescputs(from);
1191                         }
1192                         if (!strncasecmp(buf, "subj=", 5)) {
1193                                 strcpy(m_subject, &buf[5]);
1194                         }
1195                         if ((!strncasecmp(buf, "hnod=", 5))
1196                             && (strcasecmp(&buf[5], serv_info.serv_humannode))) {
1197                                 wprintf("(%s) ", &buf[5]);
1198                         }
1199                         if ((!strncasecmp(buf, "room=", 5))
1200                             && (strcasecmp(&buf[5], WC->wc_roomname))
1201                             && (strlen(&buf[5])>0) ) {
1202                                 wprintf(_("in "));
1203                                 wprintf("%s&gt; ", &buf[5]);
1204                         }
1205                         if (!strncasecmp(buf, "rfca=", 5)) {
1206                                 strcpy(rfca, &buf[5]);
1207                                 wprintf("&lt;");
1208                                 msgescputs(rfca);
1209                                 wprintf("&gt; ");
1210                         }
1211         
1212                         if (!strncasecmp(buf, "node=", 5)) {
1213                                 strcpy(node, &buf[5]);
1214                                 if ( ((WC->room_flags & QR_NETWORK)
1215                                 || ((strcasecmp(&buf[5], serv_info.serv_nodename)
1216                                 && (strcasecmp(&buf[5], serv_info.serv_fqdn)))))
1217                                 && (strlen(rfca)==0)
1218                                 ) {
1219                                         wprintf("@%s ", &buf[5]);
1220                                 }
1221                         }
1222                         if (!strncasecmp(buf, "rcpt=", 5)) {
1223                                 wprintf(_("to "));
1224                                 wprintf("%s ", &buf[5]);
1225                         }
1226                         if (!strncasecmp(buf, "time=", 5)) {
1227                                 fmt_date(now, atol(&buf[5]), 0);
1228                                 wprintf("%s ", now);
1229                         }
1230                 }
1231
1232                 /**
1233                  * Save attachment info for later.  We can't start downloading them
1234                  * yet because we're in the middle of a server transaction.
1235                  */
1236                 if (!strncasecmp(buf, "part=", 5)) {
1237                         ++num_attachments;
1238                         attachments = realloc(attachments, (num_attachments * 1024));
1239                         strcat(attachments, &buf[5]);
1240                         strcat(attachments, "\n");
1241                 }
1242
1243         }
1244
1245         if (include_headers) {
1246                 wprintf("<br>");
1247
1248 #ifdef HAVE_ICONV
1249                 utf8ify_rfc822_string(m_subject);
1250 #endif
1251                 if (strlen(m_subject) > 0) {
1252                         wprintf(_("Subject:"));
1253                         wprintf(" ");
1254                         msgescputs(m_subject);
1255                         wprintf("<br />");
1256                 }
1257
1258                 /**
1259                  * Begin body
1260                  */
1261                 wprintf("<br />");
1262         }
1263
1264         /**
1265          * Learn the content type
1266          */
1267         strcpy(mime_content_type, "text/plain");
1268         while (serv_getln(buf, sizeof buf), (strlen(buf) > 0)) {
1269                 if (!strcmp(buf, "000")) {
1270                         wprintf(_("unexpected end of message"));
1271                         goto ENDBODY;
1272                 }
1273                 if (!strncasecmp(buf, "Content-type: ", 14)) {
1274                         safestrncpy(mime_content_type, &buf[14],
1275                                 sizeof(mime_content_type));
1276                         for (i=0; i<strlen(mime_content_type); ++i) {
1277                                 if (!strncasecmp(&mime_content_type[i], "charset=", 8)) {
1278                                         safestrncpy(mime_charset, &mime_content_type[i+8],
1279                                                 sizeof mime_charset);
1280                                 }
1281                         }
1282                         for (i=0; i<strlen(mime_content_type); ++i) {
1283                                 if (mime_content_type[i] == ';') {
1284                                         mime_content_type[i] = 0;
1285                                 }
1286                         }
1287                 }
1288         }
1289
1290         /** Set up a character set conversion if we need to (and if we can) */
1291 #ifdef HAVE_ICONV
1292         if ( (strcasecmp(mime_charset, "us-ascii"))
1293            && (strcasecmp(mime_charset, "UTF-8"))
1294            && (strcasecmp(mime_charset, ""))
1295         ) {
1296                 ic = iconv_open("UTF-8", mime_charset);
1297                 if (ic == (iconv_t)(-1) ) {
1298                         lprintf(5, "%s:%d iconv_open() failed: %s\n",
1299                                 __FILE__, __LINE__, strerror(errno));
1300                 }
1301         }
1302 #endif
1303
1304         /** Messages in legacy Citadel variformat get handled thusly... */
1305         if (!strcasecmp(mime_content_type, "text/x-citadel-variformat")) {
1306                 pullquote_fmout();
1307         }
1308
1309         /* Boring old 80-column fixed format text gets handled this way... */
1310         else if (!strcasecmp(mime_content_type, "text/plain")) {
1311                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1312                         if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0;
1313                         if (buf[strlen(buf)-1] == '\r') buf[strlen(buf)-1] = 0;
1314
1315 #ifdef HAVE_ICONV
1316                         if (ic != (iconv_t)(-1) ) {
1317                                 ibuf = buf;
1318                                 ibuflen = strlen(ibuf);
1319                                 obuflen = SIZ;
1320                                 obuf = (char *) malloc(obuflen);
1321                                 osav = obuf;
1322                                 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1323                                 osav[SIZ-obuflen] = 0;
1324                                 safestrncpy(buf, osav, sizeof buf);
1325                                 free(osav);
1326                         }
1327 #endif
1328
1329                         while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
1330                                 buf[strlen(buf) - 1] = 0;
1331                         if ((bq == 0) &&
1332                         ((!strncmp(buf, ">", 1)) || (!strncmp(buf, " >", 2)) )) {
1333                                 wprintf("<blockquote>");
1334                                 bq = 1;
1335                         } else if ((bq == 1) &&
1336                                 (strncmp(buf, ">", 1)) && (strncmp(buf, " >", 2)) ) {
1337                                 wprintf("</blockquote>");
1338                                 bq = 0;
1339                         }
1340                         wprintf("<tt>");
1341                         url(buf);
1342                         msgescputs(buf);
1343                         wprintf("</tt><br />");
1344                 }
1345                 wprintf("</i><br />");
1346         }
1347
1348         /** HTML just gets escaped and stuffed back into the editor */
1349         else if (!strcasecmp(mime_content_type, "text/html")) {
1350                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1351                         strcat(buf, "\n");
1352                         msgescputs(buf);
1353                 }
1354         }
1355
1356         /** Unknown weirdness ... don't know how to handle this content type */
1357         else {
1358                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) { }
1359         }
1360
1361 ENDBODY:
1362         /** end of body handler */
1363
1364         /*
1365          * If there were attachments, we have to download them and insert them
1366          * into the attachment chain for the forwarded message we are composing.
1367          */
1368         if ( (forward_attachments) && (num_attachments) ) {
1369                 for (i=0; i<num_attachments; ++i) {
1370                         extract_token(buf, attachments, i, '\n', sizeof buf);
1371                         extract_token(mime_filename, buf, 1, '|', sizeof mime_filename);
1372                         extract_token(mime_partnum, buf, 2, '|', sizeof mime_partnum);
1373                         extract_token(mime_disposition, buf, 3, '|', sizeof mime_disposition);
1374                         extract_token(mime_content_type, buf, 4, '|', sizeof mime_content_type);
1375                         mime_length = extract_int(buf, 5);
1376
1377                         /*
1378                          * tracing  ... uncomment if necessary
1379                          *
1380                         lprintf(9, "fwd filename: %s\n", mime_filename);
1381                         lprintf(9, "fwd partnum : %s\n", mime_partnum);
1382                         lprintf(9, "fwd conttype: %s\n", mime_content_type);
1383                         lprintf(9, "fwd dispose : %s\n", mime_disposition);
1384                         lprintf(9, "fwd length  : %d\n", mime_length);
1385                          */
1386
1387                         if ( (!strcasecmp(mime_disposition, "inline"))
1388                            || (!strcasecmp(mime_disposition, "attachment")) ) {
1389                 
1390                                 /* Create an attachment struct from this mime part... */
1391                                 att = malloc(sizeof(struct wc_attachment));
1392                                 memset(att, 0, sizeof(struct wc_attachment));
1393                                 att->length = mime_length;
1394                                 strcpy(att->content_type, mime_content_type);
1395                                 strcpy(att->filename, mime_filename);
1396                                 att->next = NULL;
1397                                 att->data = load_mimepart(msgnum, mime_partnum);
1398                 
1399                                 /* And add it to the list. */
1400                                 if (WC->first_attachment == NULL) {
1401                                         WC->first_attachment = att;
1402                                 }
1403                                 else {
1404                                         aptr = WC->first_attachment;
1405                                         while (aptr->next != NULL) aptr = aptr->next;
1406                                         aptr->next = att;
1407                                 }
1408                         }
1409
1410                 }
1411                 free(attachments);
1412         }
1413
1414 #ifdef HAVE_ICONV
1415         if (ic != (iconv_t)(-1) ) {
1416                 iconv_close(ic);
1417         }
1418 #endif
1419 }
1420
1421 /**
1422  * \brief Display one row in the mailbox summary view
1423  *
1424  * \param num The row number to be displayed
1425  */
1426 void display_summarized(int num) {
1427         char datebuf[64];
1428
1429         wprintf("<tr id=\"m%ld\" style=\"width:100%%;font-weight:%s;background-color:#ffffff\" "
1430                 "onMouseDown=\"CtdlMoveMsgMouseDown(event,%ld)\">",
1431                 WC->summ[num].msgnum,
1432                 (WC->summ[num].is_new ? "bold" : "normal"),
1433                 WC->summ[num].msgnum
1434         );
1435
1436         wprintf("<td width=%d%%>", SUBJ_COL_WIDTH_PCT);
1437         escputs(WC->summ[num].subj);
1438         wprintf("</td>");
1439
1440         wprintf("<td width=%d%%>", SENDER_COL_WIDTH_PCT);
1441         escputs(WC->summ[num].from);
1442         wprintf("</td>");
1443
1444         wprintf("<td width=%d%%>", DATE_PLUS_BUTTONS_WIDTH_PCT);
1445         fmt_date(datebuf, WC->summ[num].date, 1);       /* brief */
1446         escputs(datebuf);
1447         wprintf("</td>");
1448
1449         wprintf("</tr>\n");
1450 }
1451
1452
1453
1454 /**
1455  * \brief display the adressbook overview
1456  * \param msgnum the citadel message number
1457  * \param alpha what????
1458  */
1459 void display_addressbook(long msgnum, char alpha) {
1460         char buf[SIZ];
1461         char mime_partnum[SIZ];
1462         char mime_filename[SIZ];
1463         char mime_content_type[SIZ];
1464         char mime_disposition[SIZ];
1465         int mime_length;
1466         char vcard_partnum[SIZ];
1467         char *vcard_source = NULL;
1468         struct message_summary summ;
1469
1470         memset(&summ, 0, sizeof(summ));
1471         safestrncpy(summ.subj, _("(no subject)"), sizeof summ.subj);
1472
1473         sprintf(buf, "MSG0 %ld|1", msgnum);     /* ask for headers only */
1474         serv_puts(buf);
1475         serv_getln(buf, sizeof buf);
1476         if (buf[0] != '1') return;
1477
1478         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1479                 if (!strncasecmp(buf, "part=", 5)) {
1480                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
1481                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
1482                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
1483                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
1484                         mime_length = extract_int(&buf[5], 5);
1485
1486                         if (!strcasecmp(mime_content_type, "text/x-vcard")) {
1487                                 strcpy(vcard_partnum, mime_partnum);
1488                         }
1489
1490                 }
1491         }
1492
1493         if (strlen(vcard_partnum) > 0) {
1494                 vcard_source = load_mimepart(msgnum, vcard_partnum);
1495                 if (vcard_source != NULL) {
1496
1497                         /** Display the summary line */
1498                         display_vcard(vcard_source, alpha, 0, NULL);
1499
1500                         /** If it's my vCard I can edit it */
1501                         if (    (!strcasecmp(WC->wc_roomname, USERCONFIGROOM))
1502                                 || (!strcasecmp(&WC->wc_roomname[11], USERCONFIGROOM))
1503                                 || (WC->wc_view == VIEW_ADDRESSBOOK)
1504                         ) {
1505                                 wprintf("<a href=\"edit_vcard?"
1506                                         "msgnum=%ld?partnum=%s\">",
1507                                         msgnum, vcard_partnum);
1508                                 wprintf("[%s]</a>", _("edit"));
1509                         }
1510
1511                         free(vcard_source);
1512                 }
1513         }
1514
1515 }
1516
1517
1518
1519 /**
1520  * \brief  If it's an old "Firstname Lastname" style record, try to convert it.
1521  * \param namebuf name to analyze, reverse if nescessary
1522  */
1523 void lastfirst_firstlast(char *namebuf) {
1524         char firstname[SIZ];
1525         char lastname[SIZ];
1526         int i;
1527
1528         if (namebuf == NULL) return;
1529         if (strchr(namebuf, ';') != NULL) return;
1530
1531         i = num_tokens(namebuf, ' ');
1532         if (i < 2) return;
1533
1534         extract_token(lastname, namebuf, i-1, ' ', sizeof lastname);
1535         remove_token(namebuf, i-1, ' ');
1536         strcpy(firstname, namebuf);
1537         sprintf(namebuf, "%s; %s", lastname, firstname);
1538 }
1539
1540 /**
1541  * \brief fetch what??? name
1542  * \param msgnum the citadel message number
1543  * \param namebuf where to put the name in???
1544  */
1545 void fetch_ab_name(long msgnum, char *namebuf) {
1546         char buf[SIZ];
1547         char mime_partnum[SIZ];
1548         char mime_filename[SIZ];
1549         char mime_content_type[SIZ];
1550         char mime_disposition[SIZ];
1551         int mime_length;
1552         char vcard_partnum[SIZ];
1553         char *vcard_source = NULL;
1554         int i;
1555         struct message_summary summ;
1556
1557         if (namebuf == NULL) return;
1558         strcpy(namebuf, "");
1559
1560         memset(&summ, 0, sizeof(summ));
1561         safestrncpy(summ.subj, "(no subject)", sizeof summ.subj);
1562
1563         sprintf(buf, "MSG0 %ld|1", msgnum);     /** ask for headers only */
1564         serv_puts(buf);
1565         serv_getln(buf, sizeof buf);
1566         if (buf[0] != '1') return;
1567
1568         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1569                 if (!strncasecmp(buf, "part=", 5)) {
1570                         extract_token(mime_filename, &buf[5], 1, '|', sizeof mime_filename);
1571                         extract_token(mime_partnum, &buf[5], 2, '|', sizeof mime_partnum);
1572                         extract_token(mime_disposition, &buf[5], 3, '|', sizeof mime_disposition);
1573                         extract_token(mime_content_type, &buf[5], 4, '|', sizeof mime_content_type);
1574                         mime_length = extract_int(&buf[5], 5);
1575
1576                         if (!strcasecmp(mime_content_type, "text/x-vcard")) {
1577                                 strcpy(vcard_partnum, mime_partnum);
1578                         }
1579
1580                 }
1581         }
1582
1583         if (strlen(vcard_partnum) > 0) {
1584                 vcard_source = load_mimepart(msgnum, vcard_partnum);
1585                 if (vcard_source != NULL) {
1586
1587                         /* Grab the name off the card */
1588                         display_vcard(vcard_source, 0, 0, namebuf);
1589
1590                         free(vcard_source);
1591                 }
1592         }
1593
1594         lastfirst_firstlast(namebuf);
1595         striplt(namebuf);
1596         for (i=0; i<strlen(namebuf); ++i) {
1597                 if (namebuf[i] != ';') return;
1598         }
1599         strcpy(namebuf, _("(no name)"));
1600 }
1601
1602
1603
1604 /**
1605  * \brief Record compare function for sorting address book indices
1606  * \param ab1 adressbook one
1607  * \param ab2 adressbook two
1608  */
1609 int abcmp(const void *ab1, const void *ab2) {
1610         return(strcasecmp(
1611                 (((const struct addrbookent *)ab1)->ab_name),
1612                 (((const struct addrbookent *)ab2)->ab_name)
1613         ));
1614 }
1615
1616
1617 /**
1618  * \brief Helper function for do_addrbook_view()
1619  * Converts a name into a three-letter tab label
1620  * \param tabbuf the tabbuffer to add name to
1621  * \param name the name to add to the tabbuffer
1622  */
1623 void nametab(char *tabbuf, char *name) {
1624         stresc(tabbuf, name, 0, 0);
1625         tabbuf[0] = toupper(tabbuf[0]);
1626         tabbuf[1] = tolower(tabbuf[1]);
1627         tabbuf[2] = tolower(tabbuf[2]);
1628         tabbuf[3] = 0;
1629 }
1630
1631
1632 /**
1633  * \brief Render the address book using info we gathered during the scan
1634  * \param addrbook the addressbook to render
1635  * \param num_ab the number of the addressbook
1636  */
1637 void do_addrbook_view(struct addrbookent *addrbook, int num_ab) {
1638         int i = 0;
1639         int displayed = 0;
1640         int bg = 0;
1641         static int NAMESPERPAGE = 60;
1642         int num_pages = 0;
1643         int page = 0;
1644         int tabfirst = 0;
1645         char tabfirst_label[SIZ];
1646         int tablast = 0;
1647         char tablast_label[SIZ];
1648
1649         if (num_ab == 0) {
1650                 wprintf("<br /><br /><br /><div align=\"center\"><i>");
1651                 wprintf(_("This address book is empty."));
1652                 wprintf("</i></div>\n");
1653                 return;
1654         }
1655
1656         if (num_ab > 1) {
1657                 qsort(addrbook, num_ab, sizeof(struct addrbookent), abcmp);
1658         }
1659
1660         num_pages = num_ab / NAMESPERPAGE;
1661
1662         page = atoi(bstr("page"));
1663
1664         wprintf("Page: ");
1665         for (i=0; i<=num_pages; ++i) {
1666                 if (i != page) {
1667                         wprintf("<a href=\"readfwd?page=%d\">", i);
1668                 }
1669                 else {
1670                         wprintf("<B>");
1671                 }
1672                 tabfirst = i * NAMESPERPAGE;
1673                 tablast = tabfirst + NAMESPERPAGE - 1;
1674                 if (tablast > (num_ab - 1)) tablast = (num_ab - 1);
1675                 nametab(tabfirst_label, addrbook[tabfirst].ab_name);
1676                 nametab(tablast_label, addrbook[tablast].ab_name);
1677                 wprintf("[%s&nbsp;-&nbsp;%s]",
1678                         tabfirst_label, tablast_label
1679                 );
1680                 if (i != page) {
1681                         wprintf("</A>\n");
1682                 }
1683                 else {
1684                         wprintf("</B>\n");
1685                 }
1686         }
1687         wprintf("<br />\n");
1688
1689         wprintf("<table border=0 cellspacing=0 "
1690                 "cellpadding=3 width=100%%>\n"
1691         );
1692
1693         for (i=0; i<num_ab; ++i) {
1694
1695                 if ((i / NAMESPERPAGE) == page) {
1696
1697                         if ((displayed % 4) == 0) {
1698                                 if (displayed > 0) {
1699                                         wprintf("</tr>\n");
1700                                 }
1701                                 bg = 1 - bg;
1702                                 wprintf("<tr bgcolor=\"#%s\">",
1703                                         (bg ? "DDDDDD" : "FFFFFF")
1704                                 );
1705                         }
1706         
1707                         wprintf("<td>");
1708         
1709                         wprintf("<a href=\"readfwd?startmsg=%ld&is_singlecard=1",
1710                                 addrbook[i].ab_msgnum);
1711                         wprintf("?maxmsgs=1?summary=0?alpha=%s\">", bstr("alpha"));
1712                         vcard_n_prettyize(addrbook[i].ab_name);
1713                         escputs(addrbook[i].ab_name);
1714                         wprintf("</a></td>\n");
1715                         ++displayed;
1716                 }
1717         }
1718
1719         wprintf("</tr></table>\n");
1720 }
1721
1722
1723
1724 /**
1725  * \brief load message pointers from the server
1726  * \param servcmd the citadel command to send to the citserver
1727  * \param with_headers what headers???
1728  */
1729 int load_msg_ptrs(char *servcmd, int with_headers)
1730 {
1731         char buf[1024];
1732         time_t datestamp;
1733         char fullname[128];
1734         char nodename[128];
1735         char inetaddr[128];
1736         char subject[256];
1737         int nummsgs;
1738         int maxload = 0;
1739
1740         int num_summ_alloc = 0;
1741
1742         if (WC->summ != NULL) {
1743                 free(WC->summ);
1744                 WC->num_summ = 0;
1745                 WC->summ = NULL;
1746         }
1747         num_summ_alloc = 100;
1748         WC->num_summ = 0;
1749         WC->summ = malloc(num_summ_alloc * sizeof(struct message_summary));
1750
1751         nummsgs = 0;
1752         maxload = sizeof(WC->msgarr) / sizeof(long) ;
1753         serv_puts(servcmd);
1754         serv_getln(buf, sizeof buf);
1755         if (buf[0] != '1') {
1756                 wprintf("<EM>%s</EM><br />\n", &buf[4]);
1757                 return (nummsgs);
1758         }
1759         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1760                 if (nummsgs < maxload) {
1761                         WC->msgarr[nummsgs] = extract_long(buf, 0);
1762                         datestamp = extract_long(buf, 1);
1763                         extract_token(fullname, buf, 2, '|', sizeof fullname);
1764                         extract_token(nodename, buf, 3, '|', sizeof nodename);
1765                         extract_token(inetaddr, buf, 4, '|', sizeof inetaddr);
1766                         extract_token(subject, buf, 5, '|', sizeof subject);
1767                         ++nummsgs;
1768
1769                         if (with_headers) {
1770                                 if (nummsgs > num_summ_alloc) {
1771                                         num_summ_alloc *= 2;
1772                                         WC->summ = realloc(WC->summ,
1773                                                 num_summ_alloc * sizeof(struct message_summary));
1774                                 }
1775                                 ++WC->num_summ;
1776
1777                                 memset(&WC->summ[nummsgs-1], 0, sizeof(struct message_summary));
1778                                 WC->summ[nummsgs-1].msgnum = WC->msgarr[nummsgs-1];
1779                                 safestrncpy(WC->summ[nummsgs-1].subj,
1780                                         _("(no subject)"), sizeof WC->summ[nummsgs-1].subj);
1781                                 if (strlen(fullname) > 0) {
1782                                         safestrncpy(WC->summ[nummsgs-1].from,
1783                                                 fullname, sizeof WC->summ[nummsgs-1].from);
1784                                 }
1785                                 if (strlen(subject) > 0) {
1786                                 safestrncpy(WC->summ[nummsgs-1].subj, subject,
1787                                         sizeof WC->summ[nummsgs-1].subj);
1788                                 }
1789 #ifdef HAVE_ICONV
1790                                 /** Handle subjects with RFC2047 encoding */
1791                                 utf8ify_rfc822_string(WC->summ[nummsgs-1].subj);
1792 #endif
1793                                 if (strlen(WC->summ[nummsgs-1].subj) > 75) {
1794                                         strcpy(&WC->summ[nummsgs-1].subj[72], "...");
1795                                 }
1796
1797                                 if (strlen(nodename) > 0) {
1798                                         if ( ((WC->room_flags & QR_NETWORK)
1799                                            || ((strcasecmp(nodename, serv_info.serv_nodename)
1800                                            && (strcasecmp(nodename, serv_info.serv_fqdn)))))
1801                                         ) {
1802                                                 strcat(WC->summ[nummsgs-1].from, " @ ");
1803                                                 strcat(WC->summ[nummsgs-1].from, nodename);
1804                                         }
1805                                 }
1806
1807                                 WC->summ[nummsgs-1].date = datestamp;
1808         
1809 #ifdef HAVE_ICONV
1810                                 /** Handle senders with RFC2047 encoding */
1811                                 utf8ify_rfc822_string(WC->summ[nummsgs-1].from);
1812 #endif
1813                                 if (strlen(WC->summ[nummsgs-1].from) > 25) {
1814                                         strcpy(&WC->summ[nummsgs-1].from[22], "...");
1815                                 }
1816                         }
1817                 }
1818         }
1819         return (nummsgs);
1820 }
1821
1822 /**
1823  * \brief qsort() compatible function to compare two longs in descending order.
1824  *
1825  * \param s1 first number to compare 
1826  * \param s2 second number to compare
1827  */
1828 int longcmp_r(const void *s1, const void *s2) {
1829         long l1;
1830         long l2;
1831
1832         l1 = *(long *)s1;
1833         l2 = *(long *)s2;
1834
1835         if (l1 > l2) return(-1);
1836         if (l1 < l2) return(+1);
1837         return(0);
1838 }
1839
1840  
1841 /**
1842  * \brief qsort() compatible function to compare two message summary structs by ascending subject.
1843  *
1844  * \param s1 first item to compare 
1845  * \param s2 second item to compare
1846  */
1847 int summcmp_subj(const void *s1, const void *s2) {
1848         struct message_summary *summ1;
1849         struct message_summary *summ2;
1850         
1851         summ1 = (struct message_summary *)s1;
1852         summ2 = (struct message_summary *)s2;
1853         return strcasecmp(summ1->subj, summ2->subj);
1854 }
1855
1856 /**
1857  * \brief qsort() compatible function to compare two message summary structs by descending subject.
1858  *
1859  * \param s1 first item to compare 
1860  * \param s2 second item to compare
1861  */
1862 int summcmp_rsubj(const void *s1, const void *s2) {
1863         struct message_summary *summ1;
1864         struct message_summary *summ2;
1865         
1866         summ1 = (struct message_summary *)s1;
1867         summ2 = (struct message_summary *)s2;
1868         return strcasecmp(summ2->subj, summ1->subj);
1869 }
1870
1871 /**
1872  * \brief qsort() compatible function to compare two message summary structs by ascending sender.
1873  *
1874  * \param s1 first item to compare 
1875  * \param s2 second item to compare
1876  */
1877 int summcmp_sender(const void *s1, const void *s2) {
1878         struct message_summary *summ1;
1879         struct message_summary *summ2;
1880         
1881         summ1 = (struct message_summary *)s1;
1882         summ2 = (struct message_summary *)s2;
1883         return strcasecmp(summ1->from, summ2->from);
1884 }
1885
1886 /**
1887  * \brief qsort() compatible function to compare two message summary structs by descending sender.
1888  *
1889  * \param s1 first item to compare 
1890  * \param s2 second item to compare
1891  */
1892 int summcmp_rsender(const void *s1, const void *s2) {
1893         struct message_summary *summ1;
1894         struct message_summary *summ2;
1895         
1896         summ1 = (struct message_summary *)s1;
1897         summ2 = (struct message_summary *)s2;
1898         return strcasecmp(summ2->from, summ1->from);
1899 }
1900
1901 /**
1902  * \brief qsort() compatible function to compare two message summary structs by ascending date.
1903  *
1904  * \param s1 first item to compare 
1905  * \param s2 second item to compare
1906  */
1907 int summcmp_date(const void *s1, const void *s2) {
1908         struct message_summary *summ1;
1909         struct message_summary *summ2;
1910         
1911         summ1 = (struct message_summary *)s1;
1912         summ2 = (struct message_summary *)s2;
1913
1914         if (summ1->date < summ2->date) return -1;
1915         else if (summ1->date > summ2->date) return +1;
1916         else return 0;
1917 }
1918
1919 /**
1920  * \brief qsort() compatible function to compare two message summary structs by descending date.
1921  *
1922  * \param s1 first item to compare 
1923  * \param s2 second item to compare
1924  */
1925 int summcmp_rdate(const void *s1, const void *s2) {
1926         struct message_summary *summ1;
1927         struct message_summary *summ2;
1928         
1929         summ1 = (struct message_summary *)s1;
1930         summ2 = (struct message_summary *)s2;
1931
1932         if (summ1->date < summ2->date) return +1;
1933         else if (summ1->date > summ2->date) return -1;
1934         else return 0;
1935 }
1936
1937
1938
1939 /**
1940  * \brief command loop for reading messages
1941  *
1942  * \param oper Set to "readnew" or "readold" or "readfwd" or "headers"
1943  */
1944 void readloop(char *oper)
1945 {
1946         char cmd[SIZ];
1947         char buf[SIZ];
1948         char old_msgs[SIZ];
1949         int a, b;
1950         int nummsgs;
1951         long startmsg;
1952         int maxmsgs;
1953         long *displayed_msgs = NULL;
1954         int num_displayed = 0;
1955         int is_summary = 0;
1956         int is_addressbook = 0;
1957         int is_singlecard = 0;
1958         int is_calendar = 0;
1959         int is_tasks = 0;
1960         int is_notes = 0;
1961         int is_bbview = 0;
1962         int lo, hi;
1963         int lowest_displayed = (-1);
1964         int highest_displayed = 0;
1965         struct addrbookent *addrbook = NULL;
1966         int num_ab = 0;
1967         char *sortby = NULL;
1968         char sortpref_name[128];
1969         char sortpref_value[128];
1970         char *subjsort_button;
1971         char *sendsort_button;
1972         char *datesort_button;
1973         int bbs_reverse = 0;
1974
1975         if (WC->wc_view == VIEW_WIKI) {
1976                 sprintf(buf, "wiki?room=%s?page=home", WC->wc_roomname);
1977                 http_redirect(buf);
1978                 return;
1979         }
1980
1981         startmsg = atol(bstr("startmsg"));
1982         maxmsgs = atoi(bstr("maxmsgs"));
1983         is_summary = atoi(bstr("summary"));
1984         if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
1985
1986         snprintf(sortpref_name, sizeof sortpref_name, "sort %s", WC->wc_roomname);
1987         get_preference(sortpref_name, sortpref_value, sizeof sortpref_value);
1988
1989         sortby = bstr("sortby");
1990         if ( (strlen(sortby) > 0) && (strcasecmp(sortby, sortpref_value)) ) {
1991                 set_preference(sortpref_name, sortby, 1);
1992         }
1993         if (strlen(sortby) == 0) sortby = sortpref_value;
1994
1995         /** mailbox sort */
1996         if (strlen(sortby) == 0) sortby = "rdate";
1997
1998         /** message board sort */
1999         if (!strcasecmp(sortby, "reverse")) {
2000                 bbs_reverse = 1;
2001         }
2002         else {
2003                 bbs_reverse = 0;
2004         }
2005
2006         output_headers(1, 1, 1, 0, 0, 0);
2007
2008         /**
2009          * When in summary mode, always show ALL messages instead of just
2010          * new or old.  Otherwise, show what the user asked for.
2011          */
2012         if (!strcmp(oper, "readnew")) {
2013                 strcpy(cmd, "MSGS NEW");
2014         }
2015         else if (!strcmp(oper, "readold")) {
2016                 strcpy(cmd, "MSGS OLD");
2017         }
2018         else {
2019                 strcpy(cmd, "MSGS ALL");
2020         }
2021
2022         if ((WC->wc_view == VIEW_MAILBOX) && (maxmsgs > 1)) {
2023                 is_summary = 1;
2024                 strcpy(cmd, "MSGS ALL");
2025         }
2026
2027         if ((WC->wc_view == VIEW_ADDRESSBOOK) && (maxmsgs > 1)) {
2028                 is_addressbook = 1;
2029                 strcpy(cmd, "MSGS ALL");
2030                 maxmsgs = 9999999;
2031         }
2032
2033         if (is_summary) {
2034                 strcpy(cmd, "MSGS ALL|||1");    /**< fetch header summary */
2035                 startmsg = 1;
2036                 maxmsgs = 9999999;
2037         }
2038
2039         /**
2040          * Are we doing a summary view?  If so, we need to know old messages
2041          * and new messages, so we can do that pretty boldface thing for the
2042          * new messages.
2043          */
2044         strcpy(old_msgs, "");
2045         if (is_summary) {
2046                 serv_puts("GTSN");
2047                 serv_getln(buf, sizeof buf);
2048                 if (buf[0] == '2') {
2049                         strcpy(old_msgs, &buf[4]);
2050                 }
2051         }
2052
2053         is_singlecard = atoi(bstr("is_singlecard"));
2054
2055         if ((WC->wc_view == VIEW_CALENDAR) ||
2056                 (WC->wc_view == VIEW_CALBRIEF)){                /**< calendar */
2057                 is_calendar = 1;
2058                 strcpy(cmd, "MSGS ALL");
2059                 maxmsgs = 32767;
2060         }
2061         if (WC->wc_view == VIEW_TASKS) {                /**< tasks */
2062                 is_tasks = 1;
2063                 strcpy(cmd, "MSGS ALL");
2064                 maxmsgs = 32767;
2065         }
2066         if (WC->wc_view == VIEW_NOTES) {                /**< notes */
2067                 is_notes = 1;
2068                 strcpy(cmd, "MSGS ALL");
2069                 maxmsgs = 32767;
2070         }
2071
2072         nummsgs = load_msg_ptrs(cmd, is_summary);
2073         if (nummsgs == 0) {
2074
2075                 if ((!is_tasks) && (!is_calendar) && (!is_notes) && (!is_addressbook)) {
2076                         wprintf("<em>");
2077                         if (!strcmp(oper, "readnew")) {
2078                                 wprintf(_("No new messages."));
2079                         } else if (!strcmp(oper, "readold")) {
2080                                 wprintf(_("No old messages."));
2081                         } else {
2082                                 wprintf(_("No messages here."));
2083                         }
2084                         wprintf("</em>\n");
2085                 }
2086
2087                 goto DONE;
2088         }
2089
2090         if (is_summary) {
2091                 for (a = 0; a < nummsgs; ++a) {
2092                         /** Are you a new message, or an old message? */
2093                         if (is_summary) {
2094                                 if (is_msg_in_mset(old_msgs, WC->msgarr[a])) {
2095                                         WC->summ[a].is_new = 0;
2096                                 }
2097                                 else {
2098                                         WC->summ[a].is_new = 1;
2099                                 }
2100                         }
2101                 }
2102         }
2103
2104         if (startmsg == 0L) {
2105                 if (bbs_reverse) {
2106                         startmsg = WC->msgarr[(nummsgs >= maxmsgs) ? (nummsgs - maxmsgs) : 0];
2107                 }
2108                 else {
2109                         startmsg = WC->msgarr[0];
2110                 }
2111         }
2112
2113         if (is_summary) {
2114                 if (!strcasecmp(sortby, "subject")) {
2115                         qsort(WC->summ, WC->num_summ,
2116                                 sizeof(struct message_summary), summcmp_subj);
2117                 }
2118                 else if (!strcasecmp(sortby, "rsubject")) {
2119                         qsort(WC->summ, WC->num_summ,
2120                                 sizeof(struct message_summary), summcmp_rsubj);
2121                 }
2122                 else if (!strcasecmp(sortby, "sender")) {
2123                         qsort(WC->summ, WC->num_summ,
2124                                 sizeof(struct message_summary), summcmp_sender);
2125                 }
2126                 else if (!strcasecmp(sortby, "rsender")) {
2127                         qsort(WC->summ, WC->num_summ,
2128                                 sizeof(struct message_summary), summcmp_rsender);
2129                 }
2130                 else if (!strcasecmp(sortby, "date")) {
2131                         qsort(WC->summ, WC->num_summ,
2132                                 sizeof(struct message_summary), summcmp_date);
2133                 }
2134                 else if (!strcasecmp(sortby, "rdate")) {
2135                         qsort(WC->summ, WC->num_summ,
2136                                 sizeof(struct message_summary), summcmp_rdate);
2137                 }
2138         }
2139
2140         if (!strcasecmp(sortby, "subject")) {
2141                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rsubject\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2142         }
2143         else if (!strcasecmp(sortby, "rsubject")) {
2144                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=subject\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2145         }
2146         else {
2147                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=subject\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2148         }
2149
2150         if (!strcasecmp(sortby, "sender")) {
2151                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rsender\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2152         }
2153         else if (!strcasecmp(sortby, "rsender")) {
2154                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=sender\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2155         }
2156         else {
2157                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=sender\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2158         }
2159
2160         if (!strcasecmp(sortby, "date")) {
2161                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rdate\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2162         }
2163         else if (!strcasecmp(sortby, "rdate")) {
2164                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=date\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2165         }
2166         else {
2167                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?summary=1?sortby=rdate\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2168         }
2169
2170         if (is_summary) {
2171                 wprintf("</div>\n");            /** end of 'content' div */
2172
2173                 wprintf("<script language=\"javascript\" type=\"text/javascript\">"
2174                         " document.onkeydown = CtdlMsgListKeyPress;     "
2175                         " if (document.layers) {                        "
2176                         "       document.captureEvents(Event.KEYPRESS); "
2177                         " }                                             "
2178                         "</script>\n"
2179                 );
2180
2181                 /** note that Date and Delete are now in the same column */
2182                 wprintf("<div id=\"message_list_hdr\">"
2183                         "<div class=\"fix_scrollbar_bug\">"
2184                         "<table cellspacing=0 style=\"width:100%%\">"
2185                         "<tr>"
2186                 );
2187                 wprintf("<td width=%d%%><b><i>%s</i></b> %s</td>"
2188                         "<td width=%d%%><b><i>%s</i></b> %s</td>"
2189                         "<td width=%d%%><b><i>%s</i></b> %s"
2190                         "&nbsp;"
2191                         "<input type=\"submit\" name=\"delete_button\" style=\"font-size:6pt\" "
2192                         " onClick=\"CtdlDeleteSelectedMessages(event)\" "
2193                         " value=\"%s\">"
2194                         "</td>"
2195                         "</tr>\n"
2196                         ,
2197                         SUBJ_COL_WIDTH_PCT,
2198                         _("Subject"),   subjsort_button,
2199                         SENDER_COL_WIDTH_PCT,
2200                         _("Sender"),    sendsort_button,
2201                         DATE_PLUS_BUTTONS_WIDTH_PCT,
2202                         _("Date"),      datesort_button,
2203                         _("Delete")
2204                 );
2205                 wprintf("</table></div></div>\n");
2206
2207                 wprintf("<div id=\"message_list\">"
2208
2209                         "<div class=\"fix_scrollbar_bug\">\n"
2210
2211                         "<table class=\"mailbox_summary\" id=\"summary_headers\" rules=rows "
2212                         "cellspacing=0 style=\"width:100%%;-moz-user-select:none;\">"
2213                 );
2214         }
2215
2216         if (is_notes) {
2217                 wprintf("<div align=center>%s</div>\n", _("Click on any note to edit it."));
2218                 wprintf("<div id=\"new_notes_here\"></div>\n");
2219         }
2220
2221         for (a = 0; a < nummsgs; ++a) {
2222                 if ((WC->msgarr[a] >= startmsg) && (num_displayed < maxmsgs)) {
2223
2224                         /** Display the message */
2225                         if (is_summary) {
2226                                 display_summarized(a);
2227                         }
2228                         else if (is_addressbook) {
2229                                 fetch_ab_name(WC->msgarr[a], buf);
2230                                 ++num_ab;
2231                                 addrbook = realloc(addrbook,
2232                                         (sizeof(struct addrbookent) * num_ab) );
2233                                 safestrncpy(addrbook[num_ab-1].ab_name, buf,
2234                                         sizeof(addrbook[num_ab-1].ab_name));
2235                                 addrbook[num_ab-1].ab_msgnum = WC->msgarr[a];
2236                         }
2237                         else if (is_calendar) {
2238                                 display_calendar(WC->msgarr[a]);
2239                         }
2240                         else if (is_tasks) {
2241                                 display_task(WC->msgarr[a]);
2242                         }
2243                         else if (is_notes) {
2244                                 display_note(WC->msgarr[a]);
2245                         }
2246                         else {
2247                                 if (displayed_msgs == NULL) {
2248                                         displayed_msgs = malloc(sizeof(long) *
2249                                                                 (maxmsgs<nummsgs ? maxmsgs : nummsgs));
2250                                 }
2251                                 displayed_msgs[num_displayed] = WC->msgarr[a];
2252                         }
2253
2254                         if (lowest_displayed < 0) lowest_displayed = a;
2255                         highest_displayed = a;
2256
2257                         ++num_displayed;
2258                 }
2259         }
2260
2261         /**
2262          * Set the "is_bbview" variable if it appears that we are looking at
2263          * a classic bulletin board view.
2264          */
2265         if ((!is_tasks) && (!is_calendar) && (!is_addressbook)
2266               && (!is_notes) && (!is_singlecard) && (!is_summary)) {
2267                 is_bbview = 1;
2268         }
2269
2270         /** Output loop */
2271         if (displayed_msgs != NULL) {
2272                 if (bbs_reverse) {
2273                         qsort(displayed_msgs, num_displayed, sizeof(long), longcmp_r);
2274                 }
2275
2276                 /** if we do a split bbview in the future, begin messages div here */
2277
2278                 for (a=0; a<num_displayed; ++a) {
2279                         read_message(displayed_msgs[a], 0, "");
2280                 }
2281
2282                 /** if we do a split bbview in the future, end messages div here */
2283
2284                 free(displayed_msgs);
2285                 displayed_msgs = NULL;
2286         }
2287
2288         if (is_summary) {
2289                 wprintf("</table>"
2290                         "</div>\n");                    /**< end of 'fix_scrollbar_bug' div */
2291                 wprintf("</div>");                      /**< end of 'message_list' div */
2292
2293                 /** Here's the grab-it-to-resize-the-message-list widget */
2294                 wprintf("<div id=\"resize_msglist\" "
2295                         "onMouseDown=\"CtdlResizeMsgListMouseDown(event)\">"
2296                         "<div class=\"fix_scrollbar_bug\">"
2297                         "<table width=100%% border=3 cellspacing=0 "
2298                         "bgcolor=\"#cccccc\" "
2299                         "cellpadding=0><TR><TD> </td></tr></table>"
2300                         "</div></div>\n"
2301                 );
2302
2303                 wprintf("<div id=\"preview_pane\">");   /**< The preview pane will initially be empty */
2304         }
2305
2306         /**
2307          * Bump these because although we're thinking in zero base, the user
2308          * is a drooling idiot and is thinking in one base.
2309          */
2310         ++lowest_displayed;
2311         ++highest_displayed;
2312
2313         /**
2314          * If we're not currently looking at ALL requested
2315          * messages, then display the selector bar
2316          */
2317         if (is_bbview) {
2318                 /** begin bbview scroller */
2319                 wprintf("<form name=\"msgomatic\">");
2320                 wprintf(_("Reading #"), lowest_displayed, highest_displayed);
2321
2322                 wprintf("<select name=\"whichones\" size=\"1\" "
2323                         "OnChange=\"location.href=msgomatic.whichones.options"
2324                         "[selectedIndex].value\">\n");
2325
2326                 if (bbs_reverse) {
2327                         for (b=nummsgs-1; b>=0; b = b - maxmsgs) {
2328                                 hi = b + 1;
2329                                 lo = b - maxmsgs + 2;
2330                                 if (lo < 1) lo = 1;
2331                                 wprintf("<option %s value="
2332                                         "\"%s"
2333                                         "?startmsg=%ld"
2334                                         "?maxmsgs=%d"
2335                                         "?summary=%d\">"
2336                                         "%d-%d</option> \n",
2337                                         ((WC->msgarr[lo-1] == startmsg) ? "selected" : ""),
2338                                         oper,
2339                                         WC->msgarr[lo-1],
2340                                         maxmsgs,
2341                                         is_summary,
2342                                         hi, lo);
2343                         }
2344                 }
2345                 else {
2346                         for (b=0; b<nummsgs; b = b + maxmsgs) {
2347                                 lo = b + 1;
2348                                 hi = b + maxmsgs + 1;
2349                                 if (hi > nummsgs) hi = nummsgs;
2350                                 wprintf("<option %s value="
2351                                         "\"%s"
2352                                         "?startmsg=%ld"
2353                                         "?maxmsgs=%d"
2354                                         "?summary=%d\">"
2355                                         "%d-%d</option> \n",
2356                                         ((WC->msgarr[b] == startmsg) ? "selected" : ""),
2357                                         oper,
2358                                         WC->msgarr[lo-1],
2359                                         maxmsgs,
2360                                         is_summary,
2361                                         lo, hi);
2362                         }
2363                 }
2364
2365                 wprintf("<option value=\"%s?startmsg=%ld"
2366                         "?maxmsgs=9999999?summary=%d\">"
2367                         "ALL"
2368                         "</option> ",
2369                         oper,
2370                         WC->msgarr[0], is_summary);
2371
2372                 wprintf("</select> ");
2373                 wprintf(_("of %d messages."), nummsgs);
2374
2375                 /** forward/reverse */
2376                 wprintf("&nbsp;<select name=\"direction\" size=\"1\" "
2377                         "OnChange=\"location.href=msgomatic.direction.options"
2378                         "[selectedIndex].value\">\n"
2379                 );
2380
2381                 wprintf("<option %s value=\"%s?sortby=forward\">oldest to newest</option>\n",
2382                         (bbs_reverse ? "" : "selected"),
2383                         oper
2384                 );
2385         
2386                 wprintf("<option %s value=\"%s?sortby=reverse\">newest to oldest</option>\n",
2387                         (bbs_reverse ? "selected" : ""),
2388                         oper
2389                 );
2390         
2391                 wprintf("</select></form>\n");
2392                 /** end bbview scroller */
2393         }
2394
2395 DONE:
2396         if (is_tasks) {
2397                 do_tasks_view();        /** Render the task list */
2398         }
2399
2400         if (is_calendar) {
2401                 do_calendar_view();     /** Render the calendar */
2402         }
2403
2404         if (is_addressbook) {
2405                 do_addrbook_view(addrbook, num_ab);     /** Render the address book */
2406         }
2407
2408         /** Note: wDumpContent() will output one additional </div> tag. */
2409         wDumpContent(1);
2410         if (addrbook != NULL) free(addrbook);
2411
2412         /** free the summary */
2413         if (WC->summ != NULL) {
2414                 free(WC->summ);
2415                 WC->num_summ = 0;
2416                 WC->summ = NULL;
2417         }
2418 }
2419
2420
2421 /**
2422  * \brief Back end for post_message()
2423  * ... this is where the actual message gets transmitted to the server.
2424  */
2425 void post_mime_to_server(void) {
2426         char boundary[SIZ];
2427         int is_multipart = 0;
2428         static int seq = 0;
2429         struct wc_attachment *att;
2430         char *encoded;
2431         size_t encoded_length;
2432
2433         /** RFC2045 requires this, and some clients look for it... */
2434         serv_puts("MIME-Version: 1.0");
2435
2436         /** If there are attachments, we have to do multipart/mixed */
2437         if (WC->first_attachment != NULL) {
2438                 is_multipart = 1;
2439         }
2440
2441         if (is_multipart) {
2442                 sprintf(boundary, "=_Citadel_Multipart_%s_%04x%04x",
2443                         serv_info.serv_fqdn,
2444                         getpid(),
2445                         ++seq
2446                 );
2447
2448                 /** Remember, serv_printf() appends an extra newline */
2449                 serv_printf("Content-type: multipart/mixed; "
2450                         "boundary=\"%s\"\n", boundary);
2451                 serv_printf("This is a multipart message in MIME format.\n");
2452                 serv_printf("--%s", boundary);
2453         }
2454
2455         serv_puts("Content-type: text/html; charset=utf-8");
2456         serv_puts("Content-Transfer-Encoding: quoted-printable");
2457         serv_puts("");
2458         serv_puts("<html><body>\r\n");
2459         text_to_server_qp(bstr("msgtext"));     /** Transmit message in quoted-printable encoding */
2460         serv_puts("</body></html>\r\n");
2461         
2462         if (is_multipart) {
2463
2464                 /** Add in the attachments */
2465                 for (att = WC->first_attachment; att!=NULL; att=att->next) {
2466
2467                         encoded_length = ((att->length * 150) / 100);
2468                         encoded = malloc(encoded_length);
2469                         if (encoded == NULL) break;
2470                         CtdlEncodeBase64(encoded, att->data, att->length);
2471
2472                         serv_printf("--%s", boundary);
2473                         serv_printf("Content-type: %s", att->content_type);
2474                         serv_printf("Content-disposition: attachment; "
2475                                 "filename=\"%s\"", att->filename);
2476                         serv_puts("Content-transfer-encoding: base64");
2477                         serv_puts("");
2478                         serv_write(encoded, strlen(encoded));
2479                         serv_puts("");
2480                         serv_puts("");
2481                         free(encoded);
2482                 }
2483                 serv_printf("--%s--", boundary);
2484         }
2485
2486         serv_puts("000");
2487 }
2488
2489
2490 /**
2491  * \brief Post message (or don't post message)
2492  *
2493  * Note regarding the "dont_post" variable:
2494  * A random value (actually, it's just a timestamp) is inserted as a hidden
2495  * field called "postseq" when the display_enter page is generated.  This
2496  * value is checked when posting, using the static variable dont_post.  If a
2497  * user attempts to post twice using the same dont_post value, the message is
2498  * discarded.  This prevents the accidental double-saving of the same message
2499  * if the user happens to click the browser "back" button.
2500  */
2501 void post_message(void)
2502 {
2503         char buf[SIZ];
2504         static long dont_post = (-1L);
2505         struct wc_attachment *att, *aptr;
2506         int is_anonymous = 0;
2507
2508         if (!strcasecmp(bstr("is_anonymous"), "yes")) {
2509                 is_anonymous = 1;
2510         }
2511
2512         if (WC->upload_length > 0) {
2513
2514                 /** There's an attachment.  Save it to this struct... */
2515                 att = malloc(sizeof(struct wc_attachment));
2516                 memset(att, 0, sizeof(struct wc_attachment));
2517                 att->length = WC->upload_length;
2518                 strcpy(att->content_type, WC->upload_content_type);
2519                 strcpy(att->filename, WC->upload_filename);
2520                 att->next = NULL;
2521
2522                 /** And add it to the list. */
2523                 if (WC->first_attachment == NULL) {
2524                         WC->first_attachment = att;
2525                 }
2526                 else {
2527                         aptr = WC->first_attachment;
2528                         while (aptr->next != NULL) aptr = aptr->next;
2529                         aptr->next = att;
2530                 }
2531
2532                 /**
2533                  * Mozilla sends a simple filename, which is what we want,
2534                  * but Satan's Browser sends an entire pathname.  Reduce
2535                  * the path to just a filename if we need to.
2536                  */
2537                 while (num_tokens(att->filename, '/') > 1) {
2538                         remove_token(att->filename, 0, '/');
2539                 }
2540                 while (num_tokens(att->filename, '\\') > 1) {
2541                         remove_token(att->filename, 0, '\\');
2542                 }
2543
2544                 /**
2545                  * Transfer control of this memory from the upload struct
2546                  * to the attachment struct.
2547                  */
2548                 att->data = WC->upload;
2549                 WC->upload_length = 0;
2550                 WC->upload = NULL;
2551                 display_enter();
2552                 return;
2553         }
2554
2555         if (strlen(bstr("cancel_button")) > 0) {
2556                 sprintf(WC->ImportantMessage, 
2557                         _("Cancelled.  Message was not posted."));
2558         } else if (strlen(bstr("attach_button")) > 0) {
2559                 display_enter();
2560                 return;
2561         } else if (atol(bstr("postseq")) == dont_post) {
2562                 sprintf(WC->ImportantMessage, 
2563                         _("Automatically cancelled because you have already "
2564                         "saved this message."));
2565         } else {
2566                 sprintf(buf, "ENT0 1|%s|%d|4|%s|||%s|%s|%s",
2567                         bstr("recp"),
2568                         is_anonymous,
2569                         bstr("subject"),
2570                         bstr("cc"),
2571                         bstr("bcc"),
2572                         bstr("wikipage")
2573                 );
2574                 serv_puts(buf);
2575                 serv_getln(buf, sizeof buf);
2576                 if (buf[0] == '4') {
2577                         post_mime_to_server();
2578                         if ( (strlen(bstr("recp")) > 0)
2579                            || (strlen(bstr("cc")) > 0)
2580                            || (strlen(bstr("bcc")) > 0)
2581                         ) {
2582                                 sprintf(WC->ImportantMessage, _("Message has been sent.\n"));
2583                         }
2584                         else {
2585                                 sprintf(WC->ImportantMessage, _("Message has been posted.\n"));
2586                         }
2587                         dont_post = atol(bstr("postseq"));
2588                 } else {
2589                         sprintf(WC->ImportantMessage, "%s", &buf[4]);
2590                         display_enter();
2591                         return;
2592                 }
2593         }
2594
2595         free_attachments(WC);
2596
2597         /**
2598          *  We may have been supplied with instructions regarding the location
2599          *  to which we must return after posting.  If found, go there.
2600          */
2601         if (strlen(bstr("return_to")) > 0) {
2602                 http_redirect(bstr("return_to"));
2603         }
2604         /**
2605          *  If we were editing a page in a wiki room, go to that page now.
2606          */
2607         else if (strlen(bstr("wikipage")) > 0) {
2608                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
2609                 http_redirect(buf);
2610         }
2611         /**
2612          *  Otherwise, just go to the "read messages" loop.
2613          */
2614         else {
2615                 readloop("readnew");
2616         }
2617 }
2618
2619
2620
2621
2622 /**
2623  * \brief display the message entry screen
2624  */
2625 void display_enter(void)
2626 {
2627         char buf[SIZ];
2628         char ebuf[SIZ];
2629         long now;
2630         struct wc_attachment *att;
2631         int recipient_required = 0;
2632         int recipient_bad = 0;
2633         int i;
2634         int is_anonymous = 0;
2635         long existing_page = (-1L);
2636
2637         if (strlen(bstr("force_room")) > 0) {
2638                 gotoroom(bstr("force_room"));
2639         }
2640
2641         if (!strcasecmp(bstr("is_anonymous"), "yes")) {
2642                 is_anonymous = 1;
2643         }
2644
2645         /**
2646          * Are we perhaps in an address book view?  If so, then an "enter
2647          * message" command really means "add new entry."
2648          */
2649         if (WC->wc_view == VIEW_ADDRESSBOOK) {
2650                 do_edit_vcard(-1, "", "");
2651                 return;
2652         }
2653
2654 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
2655         /**
2656          * Are we perhaps in a calendar view?  If so, then an "enter
2657          * message" command really means "add new calendar item."
2658          */
2659         if ((WC->wc_view == VIEW_CALENDAR) ||
2660                 (WC->wc_view == VIEW_CALBRIEF)){
2661                 display_edit_event();
2662                 return;
2663         }
2664
2665         /**
2666          * Are we perhaps in a tasks view?  If so, then an "enter
2667          * message" command really means "add new task."
2668          */
2669         if (WC->wc_view == VIEW_TASKS) {
2670                 display_edit_task();
2671                 return;
2672         }
2673 #endif
2674
2675         /**
2676          * Otherwise proceed normally.
2677          * Do a custom room banner with no navbar...
2678          */
2679         output_headers(1, 1, 2, 0, 0, 0);
2680         wprintf("<div id=\"banner\">\n");
2681         embed_room_banner(NULL, navbar_none);
2682         wprintf("</div>\n");
2683         wprintf("<div id=\"content\">\n"
2684                 "<div class=\"fix_scrollbar_bug\">"
2685                 "<table width=100%% border=0 bgcolor=\"#ffffff\"><tr><td>");
2686
2687         /** First test to see whether this is a room that requires recipients to be entered */
2688         serv_puts("ENT0 0");
2689         serv_getln(buf, sizeof buf);
2690         if (!strncmp(buf, "570", 3)) {          /** 570 means that we need a recipient here */
2691                 recipient_required = 1;
2692         }
2693         else if (buf[0] != '2') {               /** Any other error means that we cannot continue */
2694                 wprintf("<EM>%s</EM><br />\n", &buf[4]);
2695                 goto DONE;
2696         }
2697
2698         /** Now check our actual recipients if there are any */
2699         if (recipient_required) {
2700                 sprintf(buf, "ENT0 0|%s|%d|0||||%s|%s|%s", bstr("recp"), is_anonymous,
2701                         bstr("cc"), bstr("bcc"), bstr("wikipage"));
2702                 serv_puts(buf);
2703                 serv_getln(buf, sizeof buf);
2704
2705                 if (!strncmp(buf, "570", 3)) {  /** 570 means we have an invalid recipient listed */
2706                         if (strlen(bstr("recp")) + strlen(bstr("cc")) + strlen(bstr("bcc")) > 0) {
2707                                 recipient_bad = 1;
2708                         }
2709                 }
2710                 else if (buf[0] != '2') {       /** Any other error means that we cannot continue */
2711                         wprintf("<EM>%s</EM><br />\n", &buf[4]);
2712                         goto DONE;
2713                 }
2714         }
2715
2716         /** If we got this far, we can display the message entry screen. */
2717
2718         now = time(NULL);
2719         fmt_date(buf, now, 0);
2720         strcat(&buf[strlen(buf)], _(" <I>from</I> "));
2721         stresc(&buf[strlen(buf)], WC->wc_fullname, 1, 1);
2722
2723         /* Don't need this anymore, it's in the input box below
2724         if (strlen(bstr("recp")) > 0) {
2725                 strcat(&buf[strlen(buf)], _(" <I>to</I> "));
2726                 stresc(&buf[strlen(buf)], bstr("recp"), 1, 1);
2727         }
2728         */
2729
2730         strcat(&buf[strlen(buf)], _(" <I>in</I> "));
2731         stresc(&buf[strlen(buf)], WC->wc_roomname, 1, 1);
2732
2733         /** begin message entry screen */
2734         wprintf("<form "
2735                 "enctype=\"multipart/form-data\" "
2736                 "method=\"POST\" "
2737                 "accept-charset=\"UTF-8\" "
2738                 "action=\"post\" "
2739                 "name=\"enterform\""
2740                 ">\n");
2741         wprintf("<input type=\"hidden\" name=\"postseq\" value=\"%ld\">\n", now);
2742         if (WC->wc_view == VIEW_WIKI) {
2743                 wprintf("<input type=\"hidden\" name=\"wikipage\" value=\"%s\">\n", bstr("wikipage"));
2744         }
2745         wprintf("<input type=\"hidden\" name=\"return_to\" value=\"%s\">\n", bstr("return_to"));
2746
2747         wprintf("<img src=\"static/newmess3_24x.gif\" align=middle alt=\" \">");
2748         wprintf("%s\n", buf);   /** header bar */
2749         if (WC->room_flags & QR_ANONOPT) {
2750                 wprintf("&nbsp;"
2751                         "<input type=\"checkbox\" name=\"is_anonymous\" value=\"yes\" %s>",
2752                                 (is_anonymous ? "checked" : "")
2753                 );
2754                 wprintf("Anonymous");
2755         }
2756         wprintf("<br>\n");      /** header bar */
2757
2758         wprintf("<table border=\"0\" width=\"100%%\">\n");
2759         if (recipient_required) {
2760
2761                 wprintf("<tr><td>");
2762                 wprintf("<font size=-1>");
2763                 wprintf(_("To:"));
2764                 wprintf("</font>");
2765                 wprintf("</td><td>"
2766                         "<input autocomplete=\"off\" type=\"text\" name=\"recp\" id=\"recp_id\" value=\"");
2767                 escputs(bstr("recp"));
2768                 wprintf("\" size=50 maxlength=1000 />");
2769                 wprintf("<div class=\"auto_complete\" id=\"recp_name_choices\"></div>");
2770                 wprintf("</td><td></td></tr>\n");
2771
2772                 wprintf("<tr><td>");
2773                 wprintf("<font size=-1>");
2774                 wprintf(_("CC:"));
2775                 wprintf("</font>");
2776                 wprintf("</td><td>"
2777                         "<input autocomplete=\"off\" type=\"text\" name=\"cc\" id=\"cc_id\" value=\"");
2778                 escputs(bstr("cc"));
2779                 wprintf("\" size=50 maxlength=1000 />");
2780                 wprintf("<div class=\"auto_complete\" id=\"cc_name_choices\"></div>");
2781                 wprintf("</td><td></td></tr>\n");
2782
2783                 wprintf("<tr><td>");
2784                 wprintf("<font size=-1>");
2785                 wprintf(_("BCC:"));
2786                 wprintf("</font>");
2787                 wprintf("</td><td>"
2788                         "<input autocomplete=\"off\" type=\"text\" name=\"bcc\" id=\"bcc_id\" value=\"");
2789                 escputs(bstr("bcc"));
2790                 wprintf("\" size=50 maxlength=1000 />");
2791                 wprintf("<div class=\"auto_complete\" id=\"bcc_name_choices\"></div>");
2792                 wprintf("</td><td></td></tr>\n");
2793
2794                 /** Initialize the autocomplete ajax helpers (found in wclib.js) */
2795                 wprintf("<script type=\"text/javascript\">      \n"
2796                         " activate_entmsg_autocompleters();     \n"
2797                         "</script>                              \n"
2798                 );
2799         }
2800
2801         wprintf("<tr><td>");
2802         wprintf("<font size=-1>");
2803         wprintf(_("Subject (optional):"));
2804         wprintf("</font>");
2805         wprintf("</td><td>"
2806                 "<input type=\"text\" name=\"subject\" value=\"");
2807         escputs(bstr("subject"));
2808         wprintf("\" size=50 maxlength=70></td><td>\n");
2809
2810         wprintf("<input type=\"submit\" name=\"send_button\" value=\"");
2811         if (recipient_required) {
2812                 wprintf(_("Send message"));
2813         } else {
2814                 wprintf(_("Post message"));
2815         }
2816         wprintf("\">&nbsp;"
2817                 "<input type=\"submit\" name=\"cancel_button\" value=\"%s\">\n", _("Cancel"));
2818         wprintf("</td></tr></table>\n");
2819
2820         wprintf("<center>");
2821
2822         wprintf("<textarea name=\"msgtext\" cols=\"80\" rows=\"15\">");
2823
2824         /** If we're continuing from a previous edit, put our partially-composed message back... */
2825         msgescputs(bstr("msgtext"));
2826
2827         /* If we're forwarding a message, insert it here... */
2828         if (atol(bstr("fwdquote")) > 0L) {
2829                 wprintf("<br><div align=center><i>");
2830                 wprintf(_("--- forwarded message ---"));
2831                 wprintf("</i></div><br>");
2832                 pullquote_message(atol(bstr("fwdquote")), 1, 1);
2833         }
2834
2835         /** If we're replying quoted, insert the quote here... */
2836         else if (atol(bstr("replyquote")) > 0L) {
2837                 wprintf("<br>"
2838                         "<blockquote>");
2839                 pullquote_message(atol(bstr("replyquote")), 0, 1);
2840                 wprintf("</blockquote>\n\n");
2841         }
2842
2843         /** If we're editing a wiki page, insert the existing page here... */
2844         else if (WC->wc_view == VIEW_WIKI) {
2845                 safestrncpy(buf, bstr("wikipage"), sizeof buf);
2846                 str_wiki_index(buf);
2847                 existing_page = locate_message_by_uid(buf);
2848                 if (existing_page >= 0L) {
2849                         pullquote_message(existing_page, 1, 0);
2850                 }
2851         }
2852
2853         /** Insert our signature if appropriate... */
2854         if ( (WC->is_mailbox) && (strcmp(bstr("sig_inserted"), "yes")) ) {
2855                 get_preference("use_sig", buf, sizeof buf);
2856                 if (!strcasecmp(buf, "yes")) {
2857                         get_preference("signature", ebuf, sizeof ebuf);
2858                         euid_unescapize(buf, ebuf);
2859                         wprintf("<br>--<br>");
2860                         for (i=0; i<strlen(buf); ++i) {
2861                                 if (buf[i] == '\n') {
2862                                         wprintf("<br>");
2863                                 }
2864                                 else if (buf[i] == '<') {
2865                                         wprintf("&lt;");
2866                                 }
2867                                 else if (buf[i] == '>') {
2868                                         wprintf("&gt;");
2869                                 }
2870                                 else if (buf[i] == '&') {
2871                                         wprintf("&amp;");
2872                                 }
2873                                 else if (buf[i] == '\"') {
2874                                         wprintf("&quot;");
2875                                 }
2876                                 else if (buf[i] == '\'') {
2877                                         wprintf("&#39;");
2878                                 }
2879                                 else if (isprint(buf[i])) {
2880                                         wprintf("%c", buf[i]);
2881                                 }
2882                         }
2883                 }
2884         }
2885
2886         wprintf("</textarea>");
2887         wprintf("</center><br />\n");
2888
2889         /**
2890          * The following script embeds the TinyMCE richedit control, and automatically
2891          * transforms the textarea into a richedit textarea.
2892          */
2893         wprintf(
2894                 "<script language=\"javascript\" type=\"text/javascript\" src=\"tiny_mce/tiny_mce.js\"></script>\n"
2895                 "<script language=\"javascript\" type=\"text/javascript\">"
2896                 "tinyMCE.init({"
2897                 "       mode : \"textareas\", width : \"100%%\", browsers : \"msie,gecko\", "
2898                 "       theme : \"advanced\", plugins : \"iespell\", "
2899                 "       theme_advanced_buttons1 : \"bold, italic, underline, strikethrough, justifyleft, justifycenter, justifyright, justifyfull, bullist, numlist, cut, copy, paste, link, image, help, forecolor, iespell, code\", "
2900                 "       theme_advanced_buttons2 : \"\", "
2901                 "       theme_advanced_buttons3 : \"\" "
2902                 "});"
2903                 "</script>\n"
2904         );
2905
2906
2907         /** Enumerate any attachments which are already in place... */
2908         wprintf("<img src=\"static/diskette_24x.gif\" border=0 "
2909                 "align=middle height=16 width=16> ");
2910         wprintf(_("Attachments:"));
2911         wprintf(" ");
2912         wprintf("<select name=\"which_attachment\" size=1>");
2913         for (att = WC->first_attachment; att != NULL; att = att->next) {
2914                 wprintf("<option value=\"");
2915                 urlescputs(att->filename);
2916                 wprintf("\">");
2917                 escputs(att->filename);
2918                 /* wprintf(" (%s, %d bytes)",att->content_type,att->length); */
2919                 wprintf("</option>\n");
2920         }
2921         wprintf("</select>");
2922
2923         /** Now offer the ability to attach additional files... */
2924         wprintf("&nbsp;&nbsp;&nbsp;");
2925         wprintf(_("Attach file:"));
2926         wprintf(" <input NAME=\"attachfile\" "
2927                 "SIZE=16 TYPE=\"file\">\n&nbsp;&nbsp;"
2928                 "<input type=\"submit\" name=\"attach_button\" value=\"%s\">\n", _("Add"));
2929
2930         /** Seth asked for these to be at the top *and* bottom... */
2931         wprintf("<input type=\"submit\" name=\"send_button\" value=\"");
2932         if (recipient_required) {
2933                 wprintf(_("Send message"));
2934         } else {
2935                 wprintf(_("Post message"));
2936         }
2937         wprintf("\">&nbsp;"
2938                 "<input type=\"submit\" name=\"cancel_button\" value=\"%s\">\n", _("Cancel"));
2939
2940         /** Make sure we only insert our signature once */
2941         if (strcmp(bstr("sig_inserted"), "yes")) {
2942                 wprintf("<INPUT TYPE=\"hidden\" NAME=\"sig_inserted\" VALUE=\"yes\">\n");
2943         }
2944
2945         wprintf("</form>\n");
2946
2947         wprintf("</td></tr></table></div>\n");
2948 DONE:   wDumpContent(1);
2949 }
2950
2951
2952
2953 /**
2954  * \brief delete a message
2955  */
2956 void delete_msg(void)
2957 {
2958         long msgid;
2959         char buf[SIZ];
2960
2961         msgid = atol(bstr("msgid"));
2962
2963         output_headers(1, 1, 1, 0, 0, 0);
2964
2965         if (WC->wc_is_trash) {  /** Delete from Trash is a real delete */
2966                 serv_printf("DELE %ld", msgid); 
2967         }
2968         else {                  /** Otherwise move it to Trash */
2969                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
2970         }
2971
2972         serv_getln(buf, sizeof buf);
2973         wprintf("<EM>%s</EM><br />\n", &buf[4]);
2974
2975         wDumpContent(1);
2976 }
2977
2978
2979
2980
2981 /**
2982  * \brief Confirm move of a message
2983  */
2984 void confirm_move_msg(void)
2985 {
2986         long msgid;
2987         char buf[SIZ];
2988         char targ[SIZ];
2989
2990         msgid = atol(bstr("msgid"));
2991
2992
2993         output_headers(1, 1, 2, 0, 0, 0);
2994         wprintf("<div id=\"banner\">\n");
2995         wprintf("<TABLE WIDTH=100%% BORDER=0><TR><TD>");
2996         wprintf("<SPAN CLASS=\"titlebar\">");
2997         wprintf(_("Confirm move of message"));
2998         wprintf("</SPAN>\n");
2999         wprintf("</TD></TR></TABLE>\n");
3000         wprintf("</div>\n<div id=\"content\">\n");
3001
3002         wprintf("<CENTER>");
3003
3004         wprintf(_("Move this message to:"));
3005         wprintf("<br />\n");
3006
3007         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
3008         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
3009
3010         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
3011         serv_puts("LKRA");
3012         serv_getln(buf, sizeof buf);
3013         if (buf[0] == '1') {
3014                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3015                         extract_token(targ, buf, 0, '|', sizeof targ);
3016                         wprintf("<OPTION>");
3017                         escputs(targ);
3018                         wprintf("\n");
3019                 }
3020         }
3021         wprintf("</SELECT>\n");
3022         wprintf("<br />\n");
3023
3024         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
3025         wprintf("&nbsp;");
3026         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
3027         wprintf("</form></CENTER>\n");
3028
3029         wprintf("</CENTER>\n");
3030         wDumpContent(1);
3031 }
3032
3033
3034 /**
3035  * \brief move a message to another folder
3036  */
3037 void move_msg(void)
3038 {
3039         long msgid;
3040         char buf[SIZ];
3041
3042         msgid = atol(bstr("msgid"));
3043
3044         if (strlen(bstr("move_button")) > 0) {
3045                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
3046                 serv_puts(buf);
3047                 serv_getln(buf, sizeof buf);
3048                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
3049         } else {
3050                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
3051         }
3052
3053         readloop("readnew");
3054
3055 }
3056
3057
3058 /*@}*/