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