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