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