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