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