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