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