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