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