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