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