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