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