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