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