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