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