]> code.citadel.org Git - citadel.git/blob - webcit/messages.c
* lengthen the subject buffer so it can take utf8 glyphs
[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[1024];
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[1024];
2017         int nummsgs;
2018         int sbjlen;
2019         int maxload = 0;
2020
2021         int num_summ_alloc = 0;
2022
2023         if (WC->summ != NULL) {
2024                 free(WC->summ);
2025                 WC->num_summ = 0;
2026                 WC->summ = NULL;
2027         }
2028         num_summ_alloc = 100;
2029         WC->num_summ = 0;
2030         WC->summ = malloc(num_summ_alloc * sizeof(struct message_summary));
2031
2032         nummsgs = 0;
2033         maxload = sizeof(WC->msgarr) / sizeof(long) ;
2034         serv_puts(servcmd);
2035         serv_getln(buf, sizeof buf);
2036         if (buf[0] != '1') {
2037                 return (nummsgs);
2038         }
2039         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
2040                 if (nummsgs < maxload) {
2041                         WC->msgarr[nummsgs] = extract_long(buf, 0);
2042                         datestamp = extract_long(buf, 1);
2043                         extract_token(fullname, buf, 2, '|', sizeof fullname);
2044                         extract_token(nodename, buf, 3, '|', sizeof nodename);
2045                         extract_token(inetaddr, buf, 4, '|', sizeof inetaddr);
2046                         extract_token(subject, buf, 5, '|', sizeof subject);
2047                         ++nummsgs;
2048
2049                         if (with_headers) {
2050                                 if (nummsgs > num_summ_alloc) {
2051                                         num_summ_alloc *= 2;
2052                                         WC->summ = realloc(WC->summ,
2053                                                 num_summ_alloc * sizeof(struct message_summary));
2054                                 }
2055                                 ++WC->num_summ;
2056
2057                                 memset(&WC->summ[nummsgs-1], 0, sizeof(struct message_summary));
2058                                 WC->summ[nummsgs-1].msgnum = WC->msgarr[nummsgs-1];
2059                                 safestrncpy(WC->summ[nummsgs-1].subj,
2060                                         _("(no subject)"), sizeof WC->summ[nummsgs-1].subj);
2061                                 if (!IsEmptyStr(fullname)) {
2062                                 /** Handle senders with RFC2047 encoding */
2063                                         utf8ify_rfc822_string(fullname);
2064                                         safestrncpy(WC->summ[nummsgs-1].from,
2065                                                 fullname, sizeof WC->summ[nummsgs-1].from);
2066                                 }
2067                                 if (!IsEmptyStr(subject)) {
2068                                 /** Handle subjects with RFC2047 encoding */
2069                                         utf8ify_rfc822_string(subject);
2070                                         safestrncpy(WC->summ[nummsgs-1].subj, subject,
2071                                                     sizeof WC->summ[nummsgs-1].subj);
2072                                 }
2073                                 sbjlen = Ctdl_Utf8StrLen(WC->summ[nummsgs-1].subj);
2074                                 if (sbjlen > 75) {
2075                                         char *ptr;
2076                                         ptr = Ctdl_Utf8StrCut(WC->summ[nummsgs-1].subj, 72);
2077
2078                                         strcpy(ptr, "...");
2079                                 }
2080
2081                                 if (!IsEmptyStr(nodename)) {
2082                                         if ( ((WC->room_flags & QR_NETWORK)
2083                                            || ((strcasecmp(nodename, serv_info.serv_nodename)
2084                                            && (strcasecmp(nodename, serv_info.serv_fqdn)))))
2085                                         ) {
2086                                                 strcat(WC->summ[nummsgs-1].from, " @ ");
2087                                                 strcat(WC->summ[nummsgs-1].from, nodename);
2088                                         }
2089                                 }
2090
2091                                 WC->summ[nummsgs-1].date = datestamp;
2092         
2093                                 /** Handle senders with RFC2047 encoding */
2094                                 utf8ify_rfc822_string(WC->summ[nummsgs-1].from);
2095                                 if (strlen(WC->summ[nummsgs-1].from) > 25) {
2096                                         strcpy(&WC->summ[nummsgs-1].from[22], "...");
2097                                 }
2098                         }
2099                 }
2100         }
2101         return (nummsgs);
2102 }
2103
2104 /**
2105  * \brief qsort() compatible function to compare two longs in descending order.
2106  *
2107  * \param s1 first number to compare 
2108  * \param s2 second number to compare
2109  */
2110 int longcmp_r(const void *s1, const void *s2) {
2111         long l1;
2112         long l2;
2113
2114         l1 = *(long *)s1;
2115         l2 = *(long *)s2;
2116
2117         if (l1 > l2) return(-1);
2118         if (l1 < l2) return(+1);
2119         return(0);
2120 }
2121
2122  
2123 /**
2124  * \brief qsort() compatible function to compare two message summary structs by ascending subject.
2125  *
2126  * \param s1 first item to compare 
2127  * \param s2 second item to compare
2128  */
2129 int summcmp_subj(const void *s1, const void *s2) {
2130         struct message_summary *summ1;
2131         struct message_summary *summ2;
2132         
2133         summ1 = (struct message_summary *)s1;
2134         summ2 = (struct message_summary *)s2;
2135         return strcasecmp(summ1->subj, summ2->subj);
2136 }
2137
2138 /**
2139  * \brief qsort() compatible function to compare two message summary structs by descending subject.
2140  *
2141  * \param s1 first item to compare 
2142  * \param s2 second item to compare
2143  */
2144 int summcmp_rsubj(const void *s1, const void *s2) {
2145         struct message_summary *summ1;
2146         struct message_summary *summ2;
2147         
2148         summ1 = (struct message_summary *)s1;
2149         summ2 = (struct message_summary *)s2;
2150         return strcasecmp(summ2->subj, summ1->subj);
2151 }
2152
2153 /**
2154  * \brief qsort() compatible function to compare two message summary structs by ascending sender.
2155  *
2156  * \param s1 first item to compare 
2157  * \param s2 second item to compare
2158  */
2159 int summcmp_sender(const void *s1, const void *s2) {
2160         struct message_summary *summ1;
2161         struct message_summary *summ2;
2162         
2163         summ1 = (struct message_summary *)s1;
2164         summ2 = (struct message_summary *)s2;
2165         return strcasecmp(summ1->from, summ2->from);
2166 }
2167
2168 /**
2169  * \brief qsort() compatible function to compare two message summary structs by descending sender.
2170  *
2171  * \param s1 first item to compare 
2172  * \param s2 second item to compare
2173  */
2174 int summcmp_rsender(const void *s1, const void *s2) {
2175         struct message_summary *summ1;
2176         struct message_summary *summ2;
2177         
2178         summ1 = (struct message_summary *)s1;
2179         summ2 = (struct message_summary *)s2;
2180         return strcasecmp(summ2->from, summ1->from);
2181 }
2182
2183 /**
2184  * \brief qsort() compatible function to compare two message summary structs by ascending date.
2185  *
2186  * \param s1 first item to compare 
2187  * \param s2 second item to compare
2188  */
2189 int summcmp_date(const void *s1, const void *s2) {
2190         struct message_summary *summ1;
2191         struct message_summary *summ2;
2192         
2193         summ1 = (struct message_summary *)s1;
2194         summ2 = (struct message_summary *)s2;
2195
2196         if (summ1->date < summ2->date) return -1;
2197         else if (summ1->date > summ2->date) return +1;
2198         else return 0;
2199 }
2200
2201 /**
2202  * \brief qsort() compatible function to compare two message summary structs by descending date.
2203  *
2204  * \param s1 first item to compare 
2205  * \param s2 second item to compare
2206  */
2207 int summcmp_rdate(const void *s1, const void *s2) {
2208         struct message_summary *summ1;
2209         struct message_summary *summ2;
2210         
2211         summ1 = (struct message_summary *)s1;
2212         summ2 = (struct message_summary *)s2;
2213
2214         if (summ1->date < summ2->date) return +1;
2215         else if (summ1->date > summ2->date) return -1;
2216         else return 0;
2217 }
2218
2219
2220
2221 /**
2222  * \brief command loop for reading messages
2223  *
2224  * \param oper Set to "readnew" or "readold" or "readfwd" or "headers"
2225  */
2226 void readloop(char *oper)
2227 {
2228         char cmd[256] = "";
2229         char buf[SIZ];
2230         char old_msgs[SIZ];
2231         int a, b;
2232         int nummsgs;
2233         long startmsg;
2234         int maxmsgs;
2235         long *displayed_msgs = NULL;
2236         int num_displayed = 0;
2237         int is_summary = 0;
2238         int is_addressbook = 0;
2239         int is_singlecard = 0;
2240         int is_calendar = 0;
2241         int is_tasks = 0;
2242         int is_notes = 0;
2243         int is_bbview = 0;
2244         int lo, hi;
2245         int lowest_displayed = (-1);
2246         int highest_displayed = 0;
2247         struct addrbookent *addrbook = NULL;
2248         int num_ab = 0;
2249         char *sortby = NULL;
2250         char sortpref_name[128];
2251         char sortpref_value[128];
2252         char *subjsort_button;
2253         char *sendsort_button;
2254         char *datesort_button;
2255         int bbs_reverse = 0;
2256         struct wcsession *WCC = WC;     /* This is done to make it run faster; WC is a function */
2257
2258         if (WCC->wc_view == VIEW_WIKI) {
2259                 sprintf(buf, "wiki?room=%s?page=home", WCC->wc_roomname);
2260                 http_redirect(buf);
2261                 return;
2262         }
2263
2264         startmsg = atol(bstr("startmsg"));
2265         maxmsgs = atoi(bstr("maxmsgs"));
2266         is_summary = atoi(bstr("is_summary"));
2267         if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
2268
2269         snprintf(sortpref_name, sizeof sortpref_name, "sort %s", WCC->wc_roomname);
2270         get_preference(sortpref_name, sortpref_value, sizeof sortpref_value);
2271
2272         sortby = bstr("sortby");
2273         if ( (!IsEmptyStr(sortby)) && (strcasecmp(sortby, sortpref_value)) ) {
2274                 set_preference(sortpref_name, sortby, 1);
2275         }
2276         if (IsEmptyStr(sortby)) sortby = sortpref_value;
2277
2278         /** mailbox sort */
2279         if (IsEmptyStr(sortby)) sortby = "rdate";
2280
2281         /** message board sort */
2282         if (!strcasecmp(sortby, "reverse")) {
2283                 bbs_reverse = 1;
2284         }
2285         else {
2286                 bbs_reverse = 0;
2287         }
2288
2289         output_headers(1, 1, 1, 0, 0, 0);
2290
2291         /**
2292          * When in summary mode, always show ALL messages instead of just
2293          * new or old.  Otherwise, show what the user asked for.
2294          */
2295         if (!strcmp(oper, "readnew")) {
2296                 strcpy(cmd, "MSGS NEW");
2297         }
2298         else if (!strcmp(oper, "readold")) {
2299                 strcpy(cmd, "MSGS OLD");
2300         }
2301         else if (!strcmp(oper, "do_search")) {
2302                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
2303         }
2304         else {
2305                 strcpy(cmd, "MSGS ALL");
2306         }
2307
2308         if ((WCC->wc_view == VIEW_MAILBOX) && (maxmsgs > 1)) {
2309                 is_summary = 1;
2310                 if (!strcmp(oper, "do_search")) {
2311                         snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
2312                 }
2313                 else {
2314                         strcpy(cmd, "MSGS ALL");
2315                 }
2316         }
2317
2318         if ((WCC->wc_view == VIEW_ADDRESSBOOK) && (maxmsgs > 1)) {
2319                 is_addressbook = 1;
2320                 if (!strcmp(oper, "do_search")) {
2321                         snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
2322                 }
2323                 else {
2324                         strcpy(cmd, "MSGS ALL");
2325                 }
2326                 maxmsgs = 9999999;
2327         }
2328
2329         if (is_summary) {                       /**< fetch header summary */
2330                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
2331                         (!strcmp(oper, "do_search") ? "SEARCH" : "ALL"),
2332                         (!strcmp(oper, "do_search") ? bstr("query") : "")
2333                 );
2334                 startmsg = 1;
2335                 maxmsgs = 9999999;
2336         }
2337
2338         /**
2339          * Are we doing a summary view?  If so, we need to know old messages
2340          * and new messages, so we can do that pretty boldface thing for the
2341          * new messages.
2342          */
2343         strcpy(old_msgs, "");
2344         if ((is_summary) || (WCC->wc_default_view == VIEW_CALENDAR)){
2345                 serv_puts("GTSN");
2346                 serv_getln(buf, sizeof buf);
2347                 if (buf[0] == '2') {
2348                         strcpy(old_msgs, &buf[4]);
2349                 }
2350         }
2351
2352         is_singlecard = atoi(bstr("is_singlecard"));
2353
2354         if (WCC->wc_default_view == VIEW_CALENDAR) {            /**< calendar */
2355                 is_calendar = 1;
2356                 strcpy(cmd, "MSGS ALL|||1");
2357                 maxmsgs = 32767;
2358         }
2359         if (WCC->wc_default_view == VIEW_TASKS) {               /**< tasks */
2360                 is_tasks = 1;
2361                 strcpy(cmd, "MSGS ALL");
2362                 maxmsgs = 32767;
2363         }
2364         if (WCC->wc_default_view == VIEW_NOTES) {               /**< notes */
2365                 is_notes = 1;
2366                 strcpy(cmd, "MSGS ALL");
2367                 maxmsgs = 32767;
2368         }
2369
2370         if (is_notes) {
2371                 wprintf("<div align=center>%s</div>\n", _("Click on any note to edit it."));
2372                 wprintf("<div id=\"new_notes_here\"></div>\n");
2373         }
2374
2375         nummsgs = load_msg_ptrs(cmd, is_summary);
2376         if (nummsgs == 0) {
2377
2378                 if ((!is_tasks) && (!is_calendar) && (!is_notes) && (!is_addressbook)) {
2379                         wprintf("<div align=\"center\"><br /><em>");
2380                         if (!strcmp(oper, "readnew")) {
2381                                 wprintf(_("No new messages."));
2382                         } else if (!strcmp(oper, "readold")) {
2383                                 wprintf(_("No old messages."));
2384                         } else {
2385                                 wprintf(_("No messages here."));
2386                         }
2387                         wprintf("</em><br /></div>\n");
2388                 }
2389
2390                 goto DONE;
2391         }
2392
2393         if ((is_summary) || (WCC->wc_default_view == VIEW_CALENDAR)){
2394                 for (a = 0; a < nummsgs; ++a) {
2395                         /** Are you a new message, or an old message? */
2396                         if (is_summary) {
2397                                 if (is_msg_in_mset(old_msgs, WCC->msgarr[a])) {
2398                                         WCC->summ[a].is_new = 0;
2399                                 }
2400                                 else {
2401                                         WCC->summ[a].is_new = 1;
2402                                 }
2403                         }
2404                 }
2405         }
2406
2407         if (startmsg == 0L) {
2408                 if (bbs_reverse) {
2409                         startmsg = WCC->msgarr[(nummsgs >= maxmsgs) ? (nummsgs - maxmsgs) : 0];
2410                 }
2411                 else {
2412                         startmsg = WCC->msgarr[0];
2413                 }
2414         }
2415
2416         if (is_summary) {
2417                 if (!strcasecmp(sortby, "subject")) {
2418                         qsort(WCC->summ, WCC->num_summ,
2419                                 sizeof(struct message_summary), summcmp_subj);
2420                 }
2421                 else if (!strcasecmp(sortby, "rsubject")) {
2422                         qsort(WCC->summ, WCC->num_summ,
2423                                 sizeof(struct message_summary), summcmp_rsubj);
2424                 }
2425                 else if (!strcasecmp(sortby, "sender")) {
2426                         qsort(WCC->summ, WCC->num_summ,
2427                                 sizeof(struct message_summary), summcmp_sender);
2428                 }
2429                 else if (!strcasecmp(sortby, "rsender")) {
2430                         qsort(WCC->summ, WCC->num_summ,
2431                                 sizeof(struct message_summary), summcmp_rsender);
2432                 }
2433                 else if (!strcasecmp(sortby, "date")) {
2434                         qsort(WCC->summ, WCC->num_summ,
2435                                 sizeof(struct message_summary), summcmp_date);
2436                 }
2437                 else if (!strcasecmp(sortby, "rdate")) {
2438                         qsort(WCC->summ, WCC->num_summ,
2439                                 sizeof(struct message_summary), summcmp_rdate);
2440                 }
2441         }
2442
2443         if (!strcasecmp(sortby, "subject")) {
2444                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rsubject\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2445         }
2446         else if (!strcasecmp(sortby, "rsubject")) {
2447                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=subject\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2448         }
2449         else {
2450                 subjsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=subject\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2451         }
2452
2453         if (!strcasecmp(sortby, "sender")) {
2454                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rsender\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2455         }
2456         else if (!strcasecmp(sortby, "rsender")) {
2457                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=sender\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2458         }
2459         else {
2460                 sendsort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=sender\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2461         }
2462
2463         if (!strcasecmp(sortby, "date")) {
2464                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rdate\"><img border=\"0\" src=\"static/down_pointer.gif\" /></a>" ;
2465         }
2466         else if (!strcasecmp(sortby, "rdate")) {
2467                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=date\"><img border=\"0\" src=\"static/up_pointer.gif\" /></a>" ;
2468         }
2469         else {
2470                 datesort_button = "<a href=\"readfwd?startmsg=1?maxmsgs=9999999?is_summary=1?sortby=rdate\"><img border=\"0\" src=\"static/sort_none.gif\" /></a>" ;
2471         }
2472
2473         if (is_summary) {
2474
2475                 wprintf("<script language=\"javascript\" type=\"text/javascript\">"
2476                         " document.onkeydown = CtdlMsgListKeyPress;     "
2477                         " if (document.layers) {                        "
2478                         "       document.captureEvents(Event.KEYPRESS); "
2479                         " }                                             "
2480                         "</script>\n"
2481                 );
2482
2483                 /** note that Date and Delete are now in the same column */
2484                 wprintf("<div id=\"message_list_hdr\">"
2485                         "<div class=\"fix_scrollbar_bug\">"
2486                         "<table cellspacing=0 style=\"width:100%%\">"
2487                         "<tr>"
2488                 );
2489                 wprintf("<th width=%d%%>%s %s</th>"
2490                         "<th width=%d%%>%s %s</th>"
2491                         "<th width=%d%%>%s %s"
2492                         "&nbsp;"
2493                         "<input type=\"submit\" name=\"delete_button\" id=\"delbutton\" "
2494                         " onClick=\"CtdlDeleteSelectedMessages(event)\" "
2495                         " value=\"%s\">"
2496                         "</th>"
2497                         "</tr>\n"
2498                         ,
2499                         SUBJ_COL_WIDTH_PCT,
2500                         _("Subject"),   subjsort_button,
2501                         SENDER_COL_WIDTH_PCT,
2502                         _("Sender"),    sendsort_button,
2503                         DATE_PLUS_BUTTONS_WIDTH_PCT,
2504                         _("Date"),      datesort_button,
2505                         _("Delete")
2506                 );
2507                 wprintf("</table></div></div>\n");
2508
2509                 wprintf("<div id=\"message_list\">"
2510
2511                         "<div class=\"fix_scrollbar_bug\">\n"
2512
2513                         "<table class=\"mailbox_summary\" id=\"summary_headers\" "
2514                         "cellspacing=0 style=\"width:100%%;-moz-user-select:none;\">"
2515                 );
2516         }
2517
2518
2519         /**
2520          * Set the "is_bbview" variable if it appears that we are looking at
2521          * a classic bulletin board view.
2522          */
2523         if ((!is_tasks) && (!is_calendar) && (!is_addressbook)
2524               && (!is_notes) && (!is_singlecard) && (!is_summary)) {
2525                 is_bbview = 1;
2526         }
2527
2528         /**
2529          * If we're not currently looking at ALL requested
2530          * messages, then display the selector bar
2531          */
2532         if (is_bbview) {
2533                 /** begin bbview scroller */
2534                 wprintf("<form name=\"msgomatictop\" class=\"selector_top\" > \n <p>");
2535                 wprintf(_("Reading #"), lowest_displayed, highest_displayed);
2536
2537                 wprintf("<select name=\"whichones\" size=\"1\" "
2538                         "OnChange=\"location.href=msgomatictop.whichones.options"
2539                         "[selectedIndex].value\">\n");
2540
2541                 if (bbs_reverse) {
2542                         for (b=nummsgs-1; b>=0; b = b - maxmsgs) {
2543                                 hi = b + 1;
2544                                 lo = b - maxmsgs + 2;
2545                                 if (lo < 1) lo = 1;
2546                                 wprintf("<option %s value="
2547                                         "\"%s"
2548                                         "?startmsg=%ld"
2549                                         "?maxmsgs=%d"
2550                                         "?is_summary=%d\">"
2551                                         "%d-%d</option> \n",
2552                                         ((WCC->msgarr[lo-1] == startmsg) ? "selected" : ""),
2553                                         oper,
2554                                         WCC->msgarr[lo-1],
2555                                         maxmsgs,
2556                                         is_summary,
2557                                         hi, lo);
2558                         }
2559                 }
2560                 else {
2561                         for (b=0; b<nummsgs; b = b + maxmsgs) {
2562                                 lo = b + 1;
2563                                 hi = b + maxmsgs + 1;
2564                                 if (hi > nummsgs) hi = nummsgs;
2565                                 wprintf("<option %s value="
2566                                         "\"%s"
2567                                         "?startmsg=%ld"
2568                                         "?maxmsgs=%d"
2569                                         "?is_summary=%d\">"
2570                                         "%d-%d</option> \n",
2571                                         ((WCC->msgarr[b] == startmsg) ? "selected" : ""),
2572                                         oper,
2573                                         WCC->msgarr[lo-1],
2574                                         maxmsgs,
2575                                         is_summary,
2576                                         lo, hi);
2577                         }
2578                 }
2579
2580                 wprintf("<option value=\"%s?startmsg=%ld"
2581                         "?maxmsgs=9999999?is_summary=%d\">",
2582                         oper,
2583                         WCC->msgarr[0], is_summary);
2584                 wprintf(_("All"));
2585                 wprintf("</option>");
2586                 wprintf("</select> ");
2587                 wprintf(_("of %d messages."), nummsgs);
2588
2589                 /** forward/reverse */
2590                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2591                         "OnChange=\"location.href='%s?sortby=forward'\"",  
2592                         (bbs_reverse ? "" : "checked"),
2593                         oper
2594                 );
2595                 wprintf(">");
2596                 wprintf(_("oldest to newest"));
2597                 wprintf("&nbsp;&nbsp;&nbsp;&nbsp;");
2598
2599                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2600                         "OnChange=\"location.href='%s?sortby=reverse'\"", 
2601                         (bbs_reverse ? "checked" : ""),
2602                         oper
2603                 );
2604                 wprintf(">");
2605                 wprintf(_("newest to oldest"));
2606                 wprintf("\n");
2607         
2608                 wprintf("</p></form>\n");
2609                 /** end bbview scroller */
2610         }
2611
2612         if (is_notes)
2613         {
2614                 wprintf ("<script src=\"/static/dragdrop.js\" type=\"text/javascript\"></script>\n");
2615         }
2616
2617
2618
2619         for (a = 0; a < nummsgs; ++a) {
2620                 if ((WCC->msgarr[a] >= startmsg) && (num_displayed < maxmsgs)) {
2621
2622                         /** Display the message */
2623                         if (is_summary) {
2624                                 display_summarized(a);
2625                         }
2626                         else if (is_addressbook) {
2627                                 fetch_ab_name(WCC->msgarr[a], buf);
2628                                 ++num_ab;
2629                                 addrbook = realloc(addrbook,
2630                                         (sizeof(struct addrbookent) * num_ab) );
2631                                 safestrncpy(addrbook[num_ab-1].ab_name, buf,
2632                                         sizeof(addrbook[num_ab-1].ab_name));
2633                                 addrbook[num_ab-1].ab_msgnum = WCC->msgarr[a];
2634                         }
2635                         else if (is_calendar) {
2636                                 display_calendar(WCC->msgarr[a], WCC->summ[a].is_new);
2637                         }
2638                         else if (is_tasks) {
2639                                 display_task(WCC->msgarr[a], WCC->summ[a].is_new);
2640                         }
2641                         else if (is_notes) {
2642                                 display_note(WCC->msgarr[a], WCC->summ[a].is_new);
2643                         }
2644                         else {
2645                                 if (displayed_msgs == NULL) {
2646                                         displayed_msgs = malloc(sizeof(long) *
2647                                                                 (maxmsgs<nummsgs ? maxmsgs : nummsgs));
2648                                 }
2649                                 displayed_msgs[num_displayed] = WCC->msgarr[a];
2650                         }
2651
2652                         if (lowest_displayed < 0) lowest_displayed = a;
2653                         highest_displayed = a;
2654
2655                         ++num_displayed;
2656                 }
2657         }
2658
2659         /** Output loop */
2660         if (displayed_msgs != NULL) {
2661                 if (bbs_reverse) {
2662                         qsort(displayed_msgs, num_displayed, sizeof(long), longcmp_r);
2663                 }
2664
2665                 /** if we do a split bbview in the future, begin messages div here */
2666
2667                 for (a=0; a<num_displayed; ++a) {
2668                         read_message(displayed_msgs[a], 0, "");
2669                 }
2670
2671                 /** if we do a split bbview in the future, end messages div here */
2672
2673                 free(displayed_msgs);
2674                 displayed_msgs = NULL;
2675         }
2676
2677         if (is_summary) {
2678                 wprintf("</table>"
2679                         "</div>\n");                    /**< end of 'fix_scrollbar_bug' div */
2680                 wprintf("</div>");                      /**< end of 'message_list' div */
2681
2682                 /** Here's the grab-it-to-resize-the-message-list widget */
2683                 wprintf("<div id=\"resize_msglist\" "
2684                         "onMouseDown=\"CtdlResizeMsgListMouseDown(event)\">"
2685                         "<div class=\"fix_scrollbar_bug\"> <hr>"
2686                         "</div></div>\n"
2687                 );
2688
2689                 wprintf("<div id=\"preview_pane\">");   /**< The preview pane will initially be empty */
2690         }
2691
2692         /**
2693          * Bump these because although we're thinking in zero base, the user
2694          * is a drooling idiot and is thinking in one base.
2695          */
2696         ++lowest_displayed;
2697         ++highest_displayed;
2698
2699         /**
2700          * If we're not currently looking at ALL requested
2701          * messages, then display the selector bar
2702          */
2703         if (is_bbview) {
2704                 /** begin bbview scroller */
2705                 wprintf("<form name=\"msgomatic\" class=\"selector_bottom\" > \n <p>");
2706                 wprintf(_("Reading #"), lowest_displayed, highest_displayed);
2707
2708                 wprintf("<select name=\"whichones\" size=\"1\" "
2709                         "OnChange=\"location.href=msgomatic.whichones.options"
2710                         "[selectedIndex].value\">\n");
2711
2712                 if (bbs_reverse) {
2713                         for (b=nummsgs-1; b>=0; b = b - maxmsgs) {
2714                                 hi = b + 1;
2715                                 lo = b - maxmsgs + 2;
2716                                 if (lo < 1) lo = 1;
2717                                 wprintf("<option %s value="
2718                                         "\"%s"
2719                                         "?startmsg=%ld"
2720                                         "?maxmsgs=%d"
2721                                         "?is_summary=%d\">"
2722                                         "%d-%d</option> \n",
2723                                         ((WCC->msgarr[lo-1] == startmsg) ? "selected" : ""),
2724                                         oper,
2725                                         WCC->msgarr[lo-1],
2726                                         maxmsgs,
2727                                         is_summary,
2728                                         hi, lo);
2729                         }
2730                 }
2731                 else {
2732                         for (b=0; b<nummsgs; b = b + maxmsgs) {
2733                                 lo = b + 1;
2734                                 hi = b + maxmsgs + 1;
2735                                 if (hi > nummsgs) hi = nummsgs;
2736                                 wprintf("<option %s value="
2737                                         "\"%s"
2738                                         "?startmsg=%ld"
2739                                         "?maxmsgs=%d"
2740                                         "?is_summary=%d\">"
2741                                         "%d-%d</option> \n",
2742                                         ((WCC->msgarr[b] == startmsg) ? "selected" : ""),
2743                                         oper,
2744                                         WCC->msgarr[lo-1],
2745                                         maxmsgs,
2746                                         is_summary,
2747                                         lo, hi);
2748                         }
2749                 }
2750
2751                 wprintf("<option value=\"%s?startmsg=%ld"
2752                         "?maxmsgs=9999999?is_summary=%d\">",
2753                         oper,
2754                         WCC->msgarr[0], is_summary);
2755                 wprintf(_("All"));
2756                 wprintf("</option>");
2757                 wprintf("</select> ");
2758                 wprintf(_("of %d messages."), nummsgs);
2759
2760                 /** forward/reverse */
2761                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2762                         "OnChange=\"location.href='%s?sortby=forward'\"",  
2763                         (bbs_reverse ? "" : "checked"),
2764                         oper
2765                 );
2766                 wprintf(">");
2767                 wprintf(_("oldest to newest"));
2768                 wprintf("&nbsp;&nbsp;&nbsp;&nbsp;");
2769                 wprintf("<input type=\"radio\" %s name=\"direction\" value=\"\""
2770                         "OnChange=\"location.href='%s?sortby=reverse'\"", 
2771                         (bbs_reverse ? "checked" : ""),
2772                         oper
2773                 );
2774                 wprintf(">");
2775                 wprintf(_("newest to oldest"));
2776                 wprintf("\n");
2777
2778                 wprintf("</p></form>\n");
2779                 /** end bbview scroller */
2780         }
2781         
2782         if (is_notes)
2783         {
2784 //              wprintf ("</div>\n");
2785                 wprintf ("<div id=\"wastebin\" align=middle>Drop notes here to remove them.</div>\n");
2786                 wprintf ("<script type=\"text/javascript\">\n");
2787 //              wprintf ("//<![CDATA[\n");
2788                 wprintf ("Droppables.add(\"wastebin\",\n");
2789                 wprintf ("\t{\n");
2790                 wprintf ("\t\taccept:'notes',\n");
2791                 wprintf ("\t\tonDrop:function(element)\n");
2792                 wprintf ("\t\t{\n");
2793                 wprintf ("\t\t\tElement.hide(element);\n");
2794                 wprintf ("\t\t\tnew Ajax.Updater('notes', 'delnote',\n");
2795                 wprintf ("\t\t\t{\n");
2796                 wprintf ("\t\t\t\tasynchronous:true,\n");
2797                 wprintf ("\t\t\t\tevalScripts:true,\n");
2798                 wprintf ("\t\t\t\tonComplete:function(request)\n");
2799                 wprintf ("\t\t\t\t{\n");
2800                 wprintf ("\t\t\t\t\tElement.hide('indicator')\n");
2801                 wprintf ("\t\t\t\t},\n");
2802                 wprintf ("\t\t\t\tonLoading:function(request)\n");
2803                 wprintf ("\t\t\t\t{\n");
2804                 wprintf ("\t\t\t\t\tElement.show('indicator')\n");
2805                 wprintf ("\t\t\t\t},\n");
2806                 wprintf ("\t\t\t\tparameters:'id=' + encodeURIComponent(element.id)\n");
2807                 wprintf ("\t\t\t})\n");
2808                 wprintf ("\t\t}\n");
2809                 wprintf ("\t})\n");
2810 //              wprintf ("//]]>\n");
2811                 wprintf ("</script>\n");
2812         }
2813
2814
2815
2816 DONE:
2817         if (is_tasks) {
2818                 do_tasks_view();        /** Render the task list */
2819         }
2820
2821         if (is_calendar) {
2822                 do_calendar_view();     /** Render the calendar */
2823         }
2824
2825         if (is_addressbook) {
2826                 do_addrbook_view(addrbook, num_ab);     /** Render the address book */
2827         }
2828
2829         /** Note: wDumpContent() will output one additional </div> tag. */
2830         wprintf("</div>\n");            /** end of 'content' div */
2831         wDumpContent(1);
2832
2833         /** free the summary */
2834         if (WCC->summ != NULL) {
2835                 free(WCC->summ);
2836                 WCC->num_summ = 0;
2837                 WCC->summ = NULL;
2838         }
2839         if (addrbook != NULL) free(addrbook);
2840 }
2841
2842
2843 /**
2844  * \brief Back end for post_message()
2845  * ... this is where the actual message gets transmitted to the server.
2846  */
2847 void post_mime_to_server(void) {
2848         char top_boundary[SIZ];
2849         char alt_boundary[SIZ];
2850         int is_multipart = 0;
2851         static int seq = 0;
2852         struct wc_attachment *att;
2853         char *encoded;
2854         size_t encoded_length;
2855         size_t encoded_strlen;
2856         char *txtmail = NULL;
2857
2858         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
2859                 serv_info.serv_fqdn,
2860                 getpid(),
2861                 ++seq
2862         );
2863         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
2864                 serv_info.serv_fqdn,
2865                 getpid(),
2866                 ++seq
2867         );
2868
2869         /** RFC2045 requires this, and some clients look for it... */
2870         serv_puts("MIME-Version: 1.0");
2871         serv_puts("X-Mailer: " PACKAGE_STRING);
2872
2873         /** If there are attachments, we have to do multipart/mixed */
2874         if (WC->first_attachment != NULL) {
2875                 is_multipart = 1;
2876         }
2877
2878         if (is_multipart) {
2879                 /** Remember, serv_printf() appends an extra newline */
2880                 serv_printf("Content-type: multipart/mixed; "
2881                         "boundary=\"%s\"\n", top_boundary);
2882                 serv_printf("This is a multipart message in MIME format.\n");
2883                 serv_printf("--%s", top_boundary);
2884         }
2885
2886
2887
2888         /* Remember, serv_printf() appends an extra newline */
2889         serv_printf("Content-type: multipart/alternative; "
2890                 "boundary=\"%s\"\n", alt_boundary);
2891         serv_printf("This is a multipart message in MIME format.\n");
2892         serv_printf("--%s", alt_boundary);
2893
2894         serv_puts("Content-type: text/plain; charset=utf-8");
2895         serv_puts("Content-Transfer-Encoding: quoted-printable");
2896         serv_puts("");
2897         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
2898         text_to_server_qp(txtmail);     /** Transmit message in quoted-printable encoding */
2899         free(txtmail);
2900
2901         serv_printf("--%s", alt_boundary);
2902
2903         serv_puts("Content-type: text/html; charset=utf-8");
2904         serv_puts("Content-Transfer-Encoding: quoted-printable");
2905         serv_puts("");
2906         serv_puts("<html><body>\r\n");
2907         text_to_server_qp(bstr("msgtext"));     /** Transmit message in quoted-printable encoding */
2908         serv_puts("</body></html>\r\n");
2909
2910
2911         serv_printf("--%s--", alt_boundary);
2912
2913
2914
2915
2916         
2917         if (is_multipart) {
2918
2919                 /** Add in the attachments */
2920                 for (att = WC->first_attachment; att!=NULL; att=att->next) {
2921
2922                         encoded_length = ((att->length * 150) / 100);
2923                         encoded = malloc(encoded_length);
2924                         if (encoded == NULL) break;
2925                         encoded_strlen = CtdlEncodeBase64(encoded, att->data, att->length, 1);
2926
2927                         serv_printf("--%s", top_boundary);
2928                         serv_printf("Content-type: %s", att->content_type);
2929                         serv_printf("Content-disposition: attachment; "
2930                                 "filename=\"%s\"", att->filename);
2931                         serv_puts("Content-transfer-encoding: base64");
2932                         serv_puts("");
2933                         serv_write(encoded, encoded_strlen);
2934                         serv_puts("");
2935                         serv_puts("");
2936                         free(encoded);
2937                 }
2938                 serv_printf("--%s--", top_boundary);
2939         }
2940
2941         serv_puts("000");
2942 }
2943
2944
2945 /**
2946  * \brief Post message (or don't post message)
2947  *
2948  * Note regarding the "dont_post" variable:
2949  * A random value (actually, it's just a timestamp) is inserted as a hidden
2950  * field called "postseq" when the display_enter page is generated.  This
2951  * value is checked when posting, using the static variable dont_post.  If a
2952  * user attempts to post twice using the same dont_post value, the message is
2953  * discarded.  This prevents the accidental double-saving of the same message
2954  * if the user happens to click the browser "back" button.
2955  */
2956 void post_message(void)
2957 {
2958         char buf[1024];
2959         char encoded_subject[1024];
2960         static long dont_post = (-1L);
2961         struct wc_attachment *att, *aptr;
2962         int is_anonymous = 0;
2963         char *display_name;
2964
2965         if (!IsEmptyStr(bstr("force_room"))) {
2966                 gotoroom(bstr("force_room"));
2967         }
2968
2969         display_name = bstr("display_name");
2970         if (!strcmp(display_name, "__ANONYMOUS__")) {
2971                 display_name = "";
2972                 is_anonymous = 1;
2973         }
2974
2975         if (WC->upload_length > 0) {
2976
2977                 lprintf(9, "%s:%d: we are uploading %d bytes\n", __FILE__, __LINE__, WC->upload_length);
2978                 /** There's an attachment.  Save it to this struct... */
2979                 att = malloc(sizeof(struct wc_attachment));
2980                 memset(att, 0, sizeof(struct wc_attachment));
2981                 att->length = WC->upload_length;
2982                 strcpy(att->content_type, WC->upload_content_type);
2983                 strcpy(att->filename, WC->upload_filename);
2984                 att->next = NULL;
2985
2986                 /** And add it to the list. */
2987                 if (WC->first_attachment == NULL) {
2988                         WC->first_attachment = att;
2989                 }
2990                 else {
2991                         aptr = WC->first_attachment;
2992                         while (aptr->next != NULL) aptr = aptr->next;
2993                         aptr->next = att;
2994                 }
2995
2996                 /**
2997                  * Mozilla sends a simple filename, which is what we want,
2998                  * but Satan's Browser sends an entire pathname.  Reduce
2999                  * the path to just a filename if we need to.
3000                  */
3001                 while (num_tokens(att->filename, '/') > 1) {
3002                         remove_token(att->filename, 0, '/');
3003                 }
3004                 while (num_tokens(att->filename, '\\') > 1) {
3005                         remove_token(att->filename, 0, '\\');
3006                 }
3007
3008                 /**
3009                  * Transfer control of this memory from the upload struct
3010                  * to the attachment struct.
3011                  */
3012                 att->data = WC->upload;
3013                 WC->upload_length = 0;
3014                 WC->upload = NULL;
3015                 display_enter();
3016                 return;
3017         }
3018
3019         if (!IsEmptyStr(bstr("cancel_button"))) {
3020                 sprintf(WC->ImportantMessage, 
3021                         _("Cancelled.  Message was not posted."));
3022         } else if (!IsEmptyStr(bstr("attach_button"))) {
3023                 display_enter();
3024                 return;
3025         } else if (atol(bstr("postseq")) == dont_post) {
3026                 sprintf(WC->ImportantMessage, 
3027                         _("Automatically cancelled because you have already "
3028                         "saved this message."));
3029         } else {
3030                 webcit_rfc2047encode(encoded_subject, sizeof encoded_subject, bstr("subject"));
3031                 sprintf(buf, "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s",
3032                         bstr("recp"),
3033                         is_anonymous,
3034                         encoded_subject,
3035                         display_name,
3036                         bstr("cc"),
3037                         bstr("bcc"),
3038                         bstr("wikipage"),
3039                         bstr("my_email_addr")
3040                 );
3041                 serv_puts(buf);
3042                 serv_getln(buf, sizeof buf);
3043                 if (buf[0] == '4') {
3044                         post_mime_to_server();
3045                         if (  (!IsEmptyStr(bstr("recp")))
3046                            || (!IsEmptyStr(bstr("cc"  )))
3047                            || (!IsEmptyStr(bstr("bcc" )))
3048                         ) {
3049                                 sprintf(WC->ImportantMessage, _("Message has been sent.\n"));
3050                         }
3051                         else {
3052                                 sprintf(WC->ImportantMessage, _("Message has been posted.\n"));
3053                         }
3054                         dont_post = atol(bstr("postseq"));
3055                 } else {
3056                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, buf);
3057                         sprintf(WC->ImportantMessage, "%s", &buf[4]);
3058                         display_enter();
3059                         return;
3060                 }
3061         }
3062
3063         free_attachments(WC);
3064
3065         /**
3066          *  We may have been supplied with instructions regarding the location
3067          *  to which we must return after posting.  If found, go there.
3068          */
3069         if (!IsEmptyStr(bstr("return_to"))) {
3070                 http_redirect(bstr("return_to"));
3071         }
3072         /**
3073          *  If we were editing a page in a wiki room, go to that page now.
3074          */
3075         else if (!IsEmptyStr(bstr("wikipage"))) {
3076                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
3077                 http_redirect(buf);
3078         }
3079         /**
3080          *  Otherwise, just go to the "read messages" loop.
3081          */
3082         else {
3083                 readloop("readnew");
3084         }
3085 }
3086
3087
3088
3089
3090 /**
3091  * \brief display the message entry screen
3092  */
3093 void display_enter(void)
3094 {
3095         char buf[SIZ];
3096         char ebuf[SIZ];
3097         long now;
3098         char *display_name;
3099         struct wc_attachment *att;
3100         int recipient_required = 0;
3101         int subject_required = 0;
3102         int recipient_bad = 0;
3103         int i;
3104         int is_anonymous = 0;
3105         long existing_page = (-1L);
3106
3107         now = time(NULL);
3108
3109         if (!IsEmptyStr(bstr("force_room"))) {
3110                 gotoroom(bstr("force_room"));
3111         }
3112
3113         display_name = bstr("display_name");
3114         if (!strcmp(display_name, "__ANONYMOUS__")) {
3115                 display_name = "";
3116                 is_anonymous = 1;
3117         }
3118
3119         /** First test to see whether this is a room that requires recipients to be entered */
3120         serv_puts("ENT0 0");
3121         serv_getln(buf, sizeof buf);
3122
3123         if (!strncmp(buf, "570", 3)) {          /** 570 means that we need a recipient here */
3124                 recipient_required = 1;
3125         }
3126         else if (buf[0] != '2') {               /** Any other error means that we cannot continue */
3127                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
3128                 readloop("readnew");
3129                 return;
3130         }
3131
3132         /* Is the server strongly recommending that the user enter a message subject? */
3133         if ((buf[3] != '\0') && (buf[4] != '\0')) {
3134                 subject_required = extract_int(&buf[4], 1);
3135         }
3136
3137         /**
3138          * Are we perhaps in an address book view?  If so, then an "enter
3139          * message" command really means "add new entry."
3140          */
3141         if (WC->wc_default_view == VIEW_ADDRESSBOOK) {
3142                 do_edit_vcard(-1, "", "", WC->wc_roomname);
3143                 return;
3144         }
3145
3146         /*
3147          * Are we perhaps in a calendar room?  If so, then an "enter
3148          * message" command really means "add new calendar item."
3149          */
3150         if (WC->wc_default_view == VIEW_CALENDAR) {
3151                 display_edit_event();
3152                 return;
3153         }
3154
3155         /*
3156          * Are we perhaps in a tasks view?  If so, then an "enter
3157          * message" command really means "add new task."
3158          */
3159         if (WC->wc_default_view == VIEW_TASKS) {
3160                 display_edit_task();
3161                 return;
3162         }
3163
3164         /*
3165          * Otherwise proceed normally.
3166          * Do a custom room banner with no navbar...
3167          */
3168         output_headers(1, 1, 2, 0, 0, 0);
3169         wprintf("<div id=\"banner\">\n");
3170         embed_room_banner(NULL, navbar_none);
3171         wprintf("</div>\n");
3172         wprintf("<div id=\"content\">\n"
3173                 "<div class=\"fix_scrollbar_bug message \">");
3174
3175         /** Now check our actual recipients if there are any */
3176         if (recipient_required) {
3177                 sprintf(buf, "ENT0 0|%s|%d|0||%s||%s|%s|%s",
3178                         bstr("recp"),
3179                         is_anonymous,
3180                         display_name,
3181                         bstr("cc"), bstr("bcc"), bstr("wikipage"));
3182                 serv_puts(buf);
3183                 serv_getln(buf, sizeof buf);
3184
3185                 if (!strncmp(buf, "570", 3)) {  /** 570 means we have an invalid recipient listed */
3186                         if (!IsEmptyStr(bstr("recp")) && 
3187                             !IsEmptyStr(bstr("cc"  )) && 
3188                             !IsEmptyStr(bstr("bcc" ))) {
3189                                 recipient_bad = 1;
3190                         }
3191                 }
3192                 else if (buf[0] != '2') {       /** Any other error means that we cannot continue */
3193                         wprintf("<em>%s</em><br />\n", &buf[4]);
3194                         goto DONE;
3195                 }
3196         }
3197
3198         /** If we got this far, we can display the message entry screen. */
3199
3200         /** begin message entry screen */
3201         wprintf("<form "
3202                 "enctype=\"multipart/form-data\" "
3203                 "method=\"POST\" "
3204                 "accept-charset=\"UTF-8\" "
3205                 "action=\"post\" "
3206                 "name=\"enterform\""
3207                 ">\n");
3208         wprintf("<input type=\"hidden\" name=\"postseq\" value=\"%ld\">\n", now);
3209         if (WC->wc_view == VIEW_WIKI) {
3210                 wprintf("<input type=\"hidden\" name=\"wikipage\" value=\"%s\">\n", bstr("wikipage"));
3211         }
3212         wprintf("<input type=\"hidden\" name=\"return_to\" value=\"%s\">\n", bstr("return_to"));
3213         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%ld\">\n", WC->nonce);
3214         wprintf("<input type=\"hidden\" name=\"force_room\" value=\"");
3215         escputs(WC->wc_roomname);
3216         wprintf("\">\n");
3217
3218         /** submit or cancel buttons */
3219         wprintf("<p class=\"send_edit_msg\">");
3220         wprintf("<input type=\"submit\" name=\"send_button\" value=\"");
3221         if (recipient_required) {
3222                 wprintf(_("Send message"));
3223         } else {
3224                 wprintf(_("Post message"));
3225         }
3226         wprintf("\">&nbsp;"
3227                 "<input type=\"submit\" name=\"cancel_button\" value=\"%s\">\n", _("Cancel"));
3228         wprintf("</p>");
3229
3230         /** header bar */
3231
3232         wprintf("<img src=\"static/newmess3_24x.gif\" class=\"imgedit\">");
3233         wprintf("  ");  /** header bar */
3234         webcit_fmt_date(buf, now, 0);
3235         wprintf("%s", buf);
3236         wprintf("\n");  /** header bar */
3237
3238         wprintf("<table width=\"100%%\" class=\"edit_msg_table\">");
3239         wprintf("<tr>");
3240         wprintf("<th><label for=\"from_id\" > ");
3241         wprintf(_(" <I>from</I> "));
3242         wprintf("</label></th>");
3243
3244         wprintf("<td colspan=\"2\">");
3245
3246         /* Allow the user to select any of his valid screen names */
3247
3248         wprintf("<select name=\"display_name\" size=1 id=\"from_id\">\n");
3249
3250         serv_puts("GVSN");
3251         serv_getln(buf, sizeof buf);
3252         if (buf[0] == '1') {
3253                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3254                         wprintf("<option %s value=\"",
3255                                 ((!strcasecmp(bstr("display_name"), buf)) ? "selected" : "")
3256                         );
3257                         escputs(buf);
3258                         wprintf("\">");
3259                         escputs(buf);
3260                         wprintf("</option>\n");
3261                 }
3262         }
3263
3264         if (WC->room_flags & QR_ANONOPT) {
3265                 wprintf("<option %s value=\"__ANONYMOUS__\">%s</option>\n",
3266                         ((!strcasecmp(bstr("__ANONYMOUS__"), WC->wc_fullname)) ? "selected" : ""),
3267                         _("Anonymous")
3268                 );
3269         }
3270
3271         wprintf("</select>\n");
3272
3273         /* If this is an email (not a post), allow the user to select any of his
3274          * valid email addresses.
3275          */
3276         if (recipient_required) {
3277                 serv_puts("GVEA");
3278                 serv_getln(buf, sizeof buf);
3279                 if (buf[0] == '1') {
3280                         wprintf("<select name=\"my_email_addr\" size=1>\n");
3281                         while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3282                                 wprintf("<option value=\"");
3283                                 escputs(buf);
3284                                 wprintf("\">&lt;");
3285                                 escputs(buf);
3286                                 wprintf("&gt;</option>\n");
3287                         }
3288                         wprintf("</select>\n");
3289                 }
3290         }
3291
3292         wprintf(_(" <I>in</I> "));
3293         escputs(WC->wc_roomname);
3294
3295         wprintf("</td></tr>");
3296
3297         if (recipient_required) {
3298                 char *ccraw;
3299                 char *copy;
3300                 size_t len;
3301                 wprintf("<tr><th><label for=\"recp_id\"> ");
3302                 wprintf(_("To:"));
3303                 wprintf("</label></th>"
3304                         "<td><input autocomplete=\"off\" type=\"text\" name=\"recp\" id=\"recp_id\" value=\"");
3305                 ccraw = bstr("recp");
3306                 len = strlen(ccraw);
3307                 copy = (char*) malloc(len * 2 + 1);
3308                 memcpy(copy, ccraw, len + 1); 
3309                 utf8ify_rfc822_string(copy);
3310                 escputs(copy);
3311                 free(copy);
3312                 wprintf("\" size=45 maxlength=1000 />");
3313                 wprintf("<div class=\"auto_complete\" id=\"recp_name_choices\"></div>");
3314                 wprintf("</td><td rowspan=\"3\" align=\"left\" valign=\"top\">");
3315
3316                 /** Pop open an address book -- begin **/
3317                 wprintf(
3318                         "<a href=\"javascript:PopOpenAddressBook('recp_id|%s|cc_id|%s|bcc_id|%s');\" "
3319                         "title=\"%s\">"
3320                         "<img align=middle border=0 width=24 height=24 src=\"static/viewcontacts_24x.gif\">"
3321                         "&nbsp;%s</a>",
3322                         _("To:"), _("CC:"), _("BCC:"),
3323                         _("Contacts"), _("Contacts")
3324                 );
3325                 /** Pop open an address book -- end **/
3326
3327                 wprintf("</td></tr>");
3328
3329                 wprintf("<tr><th><label for=\"cc_id\"> ");
3330                 wprintf(_("CC:"));
3331                 wprintf("</label></th>"
3332                         "<td><input autocomplete=\"off\" type=\"text\" name=\"cc\" id=\"cc_id\" value=\"");
3333                 ccraw = bstr("cc");
3334                 len = strlen(ccraw);
3335                 copy = (char*) malloc(len * 2 + 1);
3336                 memcpy(copy, ccraw, len + 1); 
3337                 utf8ify_rfc822_string(copy);
3338                 escputs(copy);
3339                 free(copy);
3340                 wprintf("\" size=45 maxlength=1000 />");
3341                 wprintf("<div class=\"auto_complete\" id=\"cc_name_choices\"></div>");
3342                 wprintf("</td></tr>");
3343
3344                 wprintf("<tr><th><label for=\"bcc_id\"> ");
3345                 wprintf(_("BCC:"));
3346                 wprintf("</label></th>"
3347                         "<td><input autocomplete=\"off\" type=\"text\" name=\"bcc\" id=\"bcc_id\" value=\"");
3348                 ccraw = bstr("bcc");
3349                 len = strlen(ccraw);
3350                 copy = (char*) malloc(len * 2 + 1);
3351                 memcpy(copy, ccraw, len + 1); 
3352                 utf8ify_rfc822_string(copy);
3353                 escputs(copy);
3354                 free(copy);
3355                 wprintf("\" size=45 maxlength=1000 />");
3356                 wprintf("<div class=\"auto_complete\" id=\"bcc_name_choices\"></div>");
3357                 wprintf("</td></tr>");
3358
3359                 /** Initialize the autocomplete ajax helpers (found in wclib.js) */
3360                 wprintf("<script type=\"text/javascript\">      \n"
3361                         " activate_entmsg_autocompleters();     \n"
3362                         "</script>                              \n"
3363                 );
3364
3365         }
3366
3367         wprintf("<tr><th><label for=\"subject_id\" > ");
3368         if (recipient_required || subject_required) {
3369                 wprintf(_("Subject:"));
3370         }
3371         else {
3372                 wprintf(_("Subject (optional):"));
3373         }
3374         wprintf("</label></th>"
3375                 "<td colspan=\"2\">"
3376                 "<input type=\"text\" name=\"subject\" id=\"subject_id\" value=\"");
3377         escputs(bstr("subject"));
3378         wprintf("\" size=45 maxlength=70>\n");
3379         wprintf("</td></tr>");
3380
3381         wprintf("<tr><td colspan=\"3\">\n");
3382
3383         wprintf("<textarea name=\"msgtext\" cols=\"80\" rows=\"15\">");
3384
3385         /** If we're continuing from a previous edit, put our partially-composed message back... */
3386         msgescputs(bstr("msgtext"));
3387
3388         /* If we're forwarding a message, insert it here... */
3389         if (atol(bstr("fwdquote")) > 0L) {
3390                 wprintf("<br><div align=center><i>");
3391                 wprintf(_("--- forwarded message ---"));
3392                 wprintf("</i></div><br>");
3393                 pullquote_message(atol(bstr("fwdquote")), 1, 1);
3394         }
3395
3396         /** If we're replying quoted, insert the quote here... */
3397         else if (atol(bstr("replyquote")) > 0L) {
3398                 wprintf("<br>"
3399                         "<blockquote>");
3400                 pullquote_message(atol(bstr("replyquote")), 0, 1);
3401                 wprintf("</blockquote><br>");
3402         }
3403
3404         /** If we're editing a wiki page, insert the existing page here... */
3405         else if (WC->wc_view == VIEW_WIKI) {
3406                 safestrncpy(buf, bstr("wikipage"), sizeof buf);
3407                 str_wiki_index(buf);
3408                 existing_page = locate_message_by_uid(buf);
3409                 if (existing_page >= 0L) {
3410                         pullquote_message(existing_page, 1, 0);
3411                 }
3412         }
3413
3414         /** Insert our signature if appropriate... */
3415         if ( (WC->is_mailbox) && (strcmp(bstr("sig_inserted"), "yes")) ) {
3416                 get_preference("use_sig", buf, sizeof buf);
3417                 if (!strcasecmp(buf, "yes")) {
3418                         int len;
3419                         get_preference("signature", ebuf, sizeof ebuf);
3420                         euid_unescapize(buf, ebuf);
3421                         wprintf("<br>--<br>");
3422                         len = strlen(buf);
3423                         for (i=0; i<len; ++i) {
3424                                 if (buf[i] == '\n') {
3425                                         wprintf("<br>");
3426                                 }
3427                                 else if (buf[i] == '<') {
3428                                         wprintf("&lt;");
3429                                 }
3430                                 else if (buf[i] == '>') {
3431                                         wprintf("&gt;");
3432                                 }
3433                                 else if (buf[i] == '&') {
3434                                         wprintf("&amp;");
3435                                 }
3436                                 else if (buf[i] == '\"') {
3437                                         wprintf("&quot;");
3438                                 }
3439                                 else if (buf[i] == '\'') {
3440                                         wprintf("&#39;");
3441                                 }
3442                                 else if (isprint(buf[i])) {
3443                                         wprintf("%c", buf[i]);
3444                                 }
3445                         }
3446                 }
3447         }
3448
3449         wprintf("</textarea>\n");
3450
3451         /** Make sure we only insert our signature once */
3452         /** We don't care if it was there or not before, it needs to be there now. */
3453         wprintf("<input type=\"hidden\" name=\"sig_inserted\" value=\"yes\">\n");
3454         
3455         /**
3456          * The following template embeds the TinyMCE richedit control, and automatically
3457          * transforms the textarea into a richedit textarea.
3458          */
3459         do_template("richedit");
3460
3461         /** Enumerate any attachments which are already in place... */
3462         wprintf("<div class=\"attachment buttons\"><img src=\"static/diskette_24x.gif\" class=\"imgedit\" > ");
3463         wprintf(_("Attachments:"));
3464         wprintf(" ");
3465         wprintf("<select name=\"which_attachment\" size=1>");
3466         for (att = WC->first_attachment; att != NULL; att = att->next) {
3467                 wprintf("<option value=\"");
3468                 urlescputs(att->filename);
3469                 wprintf("\">");
3470                 escputs(att->filename);
3471                 /* wprintf(" (%s, %d bytes)",att->content_type,att->length); */
3472                 wprintf("</option>\n");
3473         }
3474         wprintf("</select>");
3475
3476         /** Now offer the ability to attach additional files... */
3477         wprintf("&nbsp;&nbsp;&nbsp;");
3478         wprintf(_("Attach file:"));
3479         wprintf(" <input name=\"attachfile\" class=\"attachfile\" "
3480                 "size=16 type=\"file\">\n&nbsp;&nbsp;"
3481                 "<input type=\"submit\" name=\"attach_button\" value=\"%s\">\n", _("Add"));
3482         wprintf("</div>");      /* End of "attachment buttons" div */
3483
3484
3485         wprintf("</td></tr></table>");
3486         
3487         wprintf("</form>\n");
3488         wprintf("</div>\n");    /* end of "fix_scrollbar_bug" div */
3489
3490         /* NOTE: address_book_popup() will close the "content" div.  Don't close it here. */
3491 DONE:   address_book_popup();
3492         wDumpContent(1);
3493 }
3494
3495
3496 /**
3497  * \brief delete a message
3498  */
3499 void delete_msg(void)
3500 {
3501         long msgid;
3502         char buf[SIZ];
3503
3504         msgid = atol(bstr("msgid"));
3505
3506         if (WC->wc_is_trash) {  /** Delete from Trash is a real delete */
3507                 serv_printf("DELE %ld", msgid); 
3508         }
3509         else {                  /** Otherwise move it to Trash */
3510                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
3511         }
3512
3513         serv_getln(buf, sizeof buf);
3514         sprintf(WC->ImportantMessage, "%s", &buf[4]);
3515
3516         readloop("readnew");
3517 }
3518
3519
3520 /**
3521  * \brief move a message to another folder
3522  */
3523 void move_msg(void)
3524 {
3525         long msgid;
3526         char buf[SIZ];
3527
3528         msgid = atol(bstr("msgid"));
3529
3530         if (!IsEmptyStr(bstr("move_button"))) {
3531                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
3532                 serv_puts(buf);
3533                 serv_getln(buf, sizeof buf);
3534                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
3535         } else {
3536                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
3537         }
3538
3539         readloop("readnew");
3540 }
3541
3542
3543
3544
3545
3546 /**
3547  * \brief Confirm move of a message
3548  */
3549 void confirm_move_msg(void)
3550 {
3551         long msgid;
3552         char buf[SIZ];
3553         char targ[SIZ];
3554
3555         msgid = atol(bstr("msgid"));
3556
3557
3558         output_headers(1, 1, 2, 0, 0, 0);
3559         wprintf("<div id=\"banner\">\n");
3560         wprintf("<h1>");
3561         wprintf(_("Confirm move of message"));
3562         wprintf("</h1>");
3563         wprintf("</div>\n");
3564
3565         wprintf("<div id=\"content\" class=\"service\">\n");
3566
3567         wprintf("<CENTER>");
3568
3569         wprintf(_("Move this message to:"));
3570         wprintf("<br />\n");
3571
3572         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
3573         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%ld\">\n", WC->nonce);
3574         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
3575
3576         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
3577         serv_puts("LKRA");
3578         serv_getln(buf, sizeof buf);
3579         if (buf[0] == '1') {
3580                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
3581                         extract_token(targ, buf, 0, '|', sizeof targ);
3582                         wprintf("<OPTION>");
3583                         escputs(targ);
3584                         wprintf("\n");
3585                 }
3586         }
3587         wprintf("</SELECT>\n");
3588         wprintf("<br />\n");
3589
3590         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
3591         wprintf("&nbsp;");
3592         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
3593         wprintf("</form></CENTER>\n");
3594
3595         wprintf("</CENTER>\n");
3596         wDumpContent(1);
3597 }
3598
3599
3600 /*@}*/