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