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