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