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