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