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