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