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