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