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