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