fadb68d707b6c5cdeb2ae15b9d31988297b75660
[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 int analyze_msg = 0;
16
17 #define SUBJ_COL_WIDTH_PCT              50      /**< Mailbox view column width */
18 #define SENDER_COL_WIDTH_PCT            30      /**< Mailbox view column width */
19 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /**< Mailbox view column width */
20
21
22
23 void display_enter(void);
24 int longcmp_r(const void *s1, const void *s2);
25 int summcmp_subj(const void *s1, const void *s2);
26 int summcmp_rsubj(const void *s1, const void *s2);
27 int summcmp_sender(const void *s1, const void *s2);
28 int summcmp_rsender(const void *s1, const void *s2);
29 int summcmp_date(const void *s1, const void *s2);
30 int summcmp_rdate(const void *s1, const void *s2);
31
32 /*----------------------------------------------------------------------------*/
33
34
35 typedef void (*MsgPartEvaluatorFunc)(message_summary *Sum, StrBuf *Buf);
36
37
38
39 /*----------------------------------------------------------------------------*/
40
41
42
43 /*
44  * I wanna SEE that message!
45  *
46  * msgnum               Message number to display
47  * printable_view       Nonzero to display a printable view
48  * section              Optional for encapsulated message/rfc822 submessage
49  */
50 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, int printable_view, const StrBuf *PartNum) {
51         StrBuf *Buf;
52         StrBuf *HdrToken;
53         StrBuf *FoundCharset;
54         HashPos  *it;
55         void *vMime;
56         message_summary *Msg = NULL;
57         headereval *Hdr;
58         void *vHdr;
59         char buf[SIZ];
60         int Done = 0;
61         int state=0;
62         long len;
63         const char *Key;
64
65         Buf = NewStrBuf();
66         lprintf(1, "----------%s---------MSG4 %ld|%s--------------\n", tmpl, msgnum, ChrPtr(PartNum));
67         serv_printf("MSG4 %ld|%s", msgnum, ChrPtr(PartNum));
68         StrBuf_ServGetln(Buf);
69         if (GetServerStatus(Buf, NULL) != 1) {
70                 StrBufAppendPrintf(Target, "<strong>");
71                 StrBufAppendPrintf(Target, _("ERROR:"));
72                 StrBufAppendPrintf(Target, "</strong> %s<br />\n", &buf[4]);
73                 FreeStrBuf(&Buf);
74                 return 0;
75         }
76
77         /** begin everythingamundo table */
78
79
80         HdrToken = NewStrBuf();
81         Msg = (message_summary *)malloc(sizeof(message_summary));
82         memset(Msg, 0, sizeof(message_summary));
83         Msg->msgnum = msgnum;
84         Msg->PartNum = PartNum;
85         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
86         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
87         FoundCharset = NewStrBuf();
88         while ((StrBuf_ServGetln(Buf)>=0) && !Done) {
89                 if ( (StrLength(Buf)==3) && 
90                     !strcmp(ChrPtr(Buf), "000")) 
91                 {
92                         Done = 1;
93                         if (state < 2) {
94                                 lprintf(1, _("unexpected end of message"));
95                                 
96                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
97                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
98                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("unexpected end of message"));
99                                 StrBufAppendPrintf(Msg->MsgBody->Data, " (1)</i><br /><br />\n");
100                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
101                         }
102                         break;
103                 }
104                 switch (state) {
105                 case 0:/* Citadel Message Headers */
106                         if (StrLength(Buf) == 0) {
107                                 state ++;
108                                 break;
109                         }
110                         StrBufExtract_token(HdrToken, Buf, 0, '=');
111                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
112                         
113 #ifdef TECH_PREVIEW
114                         if (analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
115 #endif
116                         /* look up one of the examine_* functions to parse the content */
117                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
118                             (vHdr != NULL)) {
119                                 Hdr = (headereval*)vHdr;
120                                 Hdr->evaluator(Msg, Buf, FoundCharset);
121                                 if (Hdr->Type == 1) {
122                                         state++;
123                                 }
124                         }
125                         else lprintf(1, "don't know how to handle message header[%s]\n", ChrPtr(HdrToken));
126                         break;
127                 case 1:/* Message Mime Header */
128                         if (StrLength(Buf) == 0) {
129                                 state++;
130                                 if (Msg->MsgBody->ContentType == NULL)
131                                         /* end of header or no header? */
132                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
133                                  /* usual end of mime header */
134                         }
135                         else
136                         {
137                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
138                                 if (StrLength(HdrToken) > 0) {
139                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
140 #ifdef TECH_PREVIEW
141                                         if (analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
142 #endif
143                                         /* the examine*'s know how to do with mime headers too... */
144                                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
145                                             (vHdr != NULL)) {
146                                                 Hdr = (headereval*)vHdr;
147                                                 Hdr->evaluator(Msg, Buf, FoundCharset);
148                                         }
149                                         break;
150                                 }
151                         }
152                 case 2: /* Message Body */
153                         
154                         if (Msg->MsgBody->size_known > 0) {
155                                 StrBuf_ServGetBLOB(Msg->MsgBody->Data, Msg->MsgBody->length);
156                                 state ++;
157                                         /// todo: check next line, if not 000, append following lines
158                         }
159                         else if (1){
160                                 if (StrLength(Msg->MsgBody->Data) > 0)
161                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
162                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
163                         }
164                         break;
165                 case 3:
166                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
167                         break;
168                 }
169         }
170
171         if (Msg->AllAttach == NULL)
172                 Msg->AllAttach = NewHash(1,NULL);
173         /* now we put the body mimepart we read above into the mimelist */
174         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
175         
176         /* strip the bare contenttype, so we ommit charset etc. */
177         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
178         StrBufTrim(Buf);
179         /* look up the renderer, that will convert this mimeitem into the htmlized form */
180         if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
181             (vHdr != NULL)) {
182                 RenderMimeFunc Render;
183                 Render = (RenderMimeFunc)vHdr;
184                 Render(Msg->MsgBody, NULL, FoundCharset);
185         }
186
187         if (StrLength(Msg->reply_references)> 0) {
188                 /* Trim down excessively long lists of thread references.  We eliminate the
189                  * second one in the list so that the thread root remains intact.
190                  */
191                 int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
192                 int rrlen = StrLength(Msg->reply_references);
193                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
194                         StrBufRemove_token(Msg->reply_references, 1, '|');
195                 }
196         }
197
198         /* Generate a reply-to address */
199         if (StrLength(Msg->Rfca) > 0) {
200                 if (Msg->reply_to == NULL)
201                         Msg->reply_to = NewStrBuf();
202                 if (StrLength(Msg->from) > 0) {
203                         StrBufPrintf(Msg->reply_to, "%s <%s>", ChrPtr(Msg->from), ChrPtr(Msg->Rfca));
204                 }
205                 else {
206                         FlushStrBuf(Msg->reply_to);
207                         StrBufAppendBuf(Msg->reply_to, Msg->Rfca, 0);
208                 }
209         }
210         else 
211         {
212                 if ((StrLength(Msg->OtherNode)>0) && 
213                     (strcasecmp(ChrPtr(Msg->OtherNode), serv_info.serv_nodename)) &&
214                     (strcasecmp(ChrPtr(Msg->OtherNode), serv_info.serv_humannode)) ) 
215                 {
216                         if (Msg->reply_to == NULL)
217                                 Msg->reply_to = NewStrBuf();
218                         StrBufPrintf(Msg->reply_to, 
219                                      "%s @ %s",
220                                      ChrPtr(Msg->from), 
221                                      ChrPtr(Msg->OtherNode));
222                 }
223                 else {
224                         if (Msg->reply_to == NULL)
225                                 Msg->reply_to = NewStrBuf();
226                         FlushStrBuf(Msg->reply_to);
227                         StrBufAppendBuf(Msg->reply_to, Msg->from, 0);
228                 }
229         }
230
231         /* now check if we need to translate some mimeparts, and remove the duplicate */
232         it = GetNewHashPos(Msg->AllAttach, 0);
233         while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
234                (vMime != NULL)) {
235                 wc_mime_attachment *Mime = (wc_mime_attachment*) vMime;
236                 evaluate_mime_part(Msg, Mime);
237         }
238         DeleteHashPos(&it);
239
240         DoTemplate(tmpl, tmpllen, Target, Msg, CTX_MAILSUM);
241
242         DestroyMessageSummary(Msg);
243         FreeStrBuf(&FoundCharset);
244         FreeStrBuf(&HdrToken);
245         FreeStrBuf(&Buf);
246         return 1;
247 }
248
249
250
251 /*
252  * Unadorned HTML output of an individual message, suitable
253  * for placing in a hidden iframe, for printing, or whatever
254  *
255  * msgnum_as_string == Message number, as a string instead of as a long int
256  */
257 void embed_message(void) {
258         long msgnum = 0L;
259         const StrBuf *Tmpl = sbstr("template");
260
261         msgnum = StrTol(WC->UrlFragment2);
262         if (StrLength(Tmpl) > 0) 
263                 read_message(WC->WBuf, SKEY(Tmpl), msgnum, 0, NULL);
264         else 
265                 read_message(WC->WBuf, HKEY("view_message"), msgnum, 0, NULL);
266 }
267
268
269 /*
270  * Printable view of a message
271  *
272  * msgnum_as_string == Message number, as a string instead of as a long int
273  */
274 void print_message(void) {
275         long msgnum = 0L;
276
277         msgnum = StrTol(WC->UrlFragment2);
278         output_headers(0, 0, 0, 0, 0, 0);
279
280         hprintf("Content-type: text/html\r\n"
281                 "Server: " PACKAGE_STRING "\r\n"
282                 "Connection: close\r\n");
283
284         begin_burst();
285
286         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, 1, NULL);
287
288         wDumpContent(0);
289 }
290
291 /* 
292  * Mobile browser view of message
293  *
294  * @param msg_num_as_string Message number as a string instead of as a long int 
295  */
296 void mobile_message_view(void) {
297   long msgnum = 0L;
298   msgnum = StrTol(WC->UrlFragment2);
299   output_headers(1, 0, 0, 0, 0, 1);
300   begin_burst();
301   do_template("msgcontrols", NULL);
302   read_message(WC->WBuf, HKEY("view_message"), msgnum,1, NULL);
303   wDumpContent(0);
304 }
305
306 /**
307  * \brief Display a message's headers
308  *
309  * \param msgnum_as_string Message number, as a string instead of as a long int
310  */
311 void display_headers(void) {
312         long msgnum = 0L;
313         char buf[1024];
314
315         msgnum = StrTol(WC->UrlFragment2);
316         output_headers(0, 0, 0, 0, 0, 0);
317
318         hprintf("Content-type: text/plain\r\n"
319                 "Server: %s\r\n"
320                 "Connection: close\r\n",
321                 PACKAGE_STRING);
322         begin_burst();
323
324         serv_printf("MSG2 %ld|3", msgnum);
325         serv_getln(buf, sizeof buf);
326         if (buf[0] == '1') {
327                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
328                         wprintf("%s\n", buf);
329                 }
330         }
331
332         wDumpContent(0);
333 }
334
335
336 message_summary *ReadOneMessageSummary(StrBuf *RawMessage, const char *DefaultSubject, long MsgNum) 
337 {
338         void                 *vEval;
339         MsgPartEvaluatorFunc  Eval;
340         message_summary      *Msg;
341         StrBuf *Buf;
342         const char *buf;
343         const char *ebuf;
344         int nBuf;
345         long len;
346         
347         Buf = NewStrBuf();
348
349         serv_printf("MSG0 %ld|1", MsgNum);      /* ask for headers only */
350         
351         StrBuf_ServGetln(Buf);
352         if (GetServerStatus(Buf, NULL) == 1) {
353                 FreeStrBuf(&Buf);
354                 return NULL;
355         }
356
357         Msg = (message_summary*)malloc(sizeof(message_summary));
358         memset(Msg, 0, sizeof(message_summary));
359         while (len = StrBuf_ServGetln(Buf),
360                ((len != 3)  ||
361                 strcmp(ChrPtr(Buf), "000")== 0)){
362                 buf = ChrPtr(Buf);
363                 ebuf = strchr(ChrPtr(Buf), '=');
364                 nBuf = ebuf - buf;
365                 if (GetHash(MsgEvaluators, buf, nBuf, &vEval) && vEval != NULL) {
366                         Eval = (MsgPartEvaluatorFunc) vEval;
367                         StrBufCutLeft(Buf, nBuf + 1);
368                         Eval(Msg, Buf);
369                 }
370                 else lprintf(1, "Don't know how to handle Message Headerline [%s]", ChrPtr(Buf));
371         }
372         return Msg;
373 }
374
375
376
377
378
379 /*
380  * load message pointers from the server for a "read messages" operation
381  *
382  * servcmd:             the citadel command to send to the citserver
383  * with_headers:        also include some of the headers with the message numbers (more expensive)
384  */
385 int load_msg_ptrs(char *servcmd, int with_headers)
386 {
387         StrBuf* FoundCharset = NULL;
388         wcsession *WCC = WC;
389         message_summary *Msg;
390         StrBuf *Buf, *Buf2;
391         int nummsgs = 0;
392         int maxload = 0;
393         long len;
394         int n;
395         int skipit;
396
397         if (WCC->summ != NULL) {
398                 if (WCC->summ != NULL)
399                         DeleteHash(&WCC->summ);
400         }
401         WCC->summ = NewHash(1, Flathash);
402         maxload = 10000;
403         
404         Buf = NewStrBuf();
405         serv_puts(servcmd);
406         StrBuf_ServGetln(Buf);
407         if (GetServerStatus(Buf, NULL) != 1) {
408                 FreeStrBuf(&Buf);
409                 return (nummsgs);
410         }
411 // TODO                         if (with_headers) { //// TODO: Have Attachments?
412         Buf2 = NewStrBuf();
413         while (len = StrBuf_ServGetln(Buf),
414                ((len != 3)  ||
415                 strcmp(ChrPtr(Buf), "000")!= 0))
416         {
417                 if (nummsgs < maxload) {
418                         skipit = 0;
419                         Msg = (message_summary*)malloc(sizeof(message_summary));
420                         memset(Msg, 0, sizeof(message_summary));
421
422                         Msg->msgnum = StrBufExtract_long(Buf, 0, '|');
423                         Msg->date = StrBufExtract_long(Buf, 1, '|');
424                         /* 
425                          * as citserver probably gives us messages in forward date sorting
426                          * nummsgs should be the same order as the message date.
427                          */
428                         if (Msg->date == 0) {
429                                 Msg->date = nummsgs;
430                                 if (StrLength(Buf) < 32) 
431                                         skipit = 1;
432                         }
433                         if (!skipit) {
434                                 Msg->from = NewStrBufPlain(NULL, StrLength(Buf));
435                                 StrBufExtract_token(Buf2, Buf, 2, '|');
436                                 if (StrLength(Buf2) != 0) {
437                                         /** Handle senders with RFC2047 encoding */
438                                         StrBuf_RFC822_to_Utf8(Msg->from, Buf2, WCC->DefaultCharset, FoundCharset);
439                                 }
440                         
441                                 /** Nodename */
442                                 StrBufExtract_token(Buf2, Buf, 3, '|');
443                                 if ((StrLength(Buf2) !=0 ) &&
444                                     ( ((WCC->room_flags & QR_NETWORK)
445                                        || ((strcasecmp(ChrPtr(Buf2), serv_info.serv_nodename)
446                                             && (strcasecmp(ChrPtr(Buf2), serv_info.serv_fqdn)))))))
447                                 {
448                                         StrBufAppendBufPlain(Msg->from, HKEY(" @ "), 0);
449                                         StrBufAppendBuf(Msg->from, Buf2, 0);
450                                 }
451
452                                 /** Not used:
453                                     StrBufExtract_token(Msg->inetaddr, Buf, 4, '|');
454                                 */
455
456                                 Msg->subj = NewStrBufPlain(NULL, StrLength(Buf));
457                                 StrBufExtract_token(Buf2,  Buf, 5, '|');
458                                 if (StrLength(Buf2) == 0)
459                                         StrBufAppendBufPlain(Msg->subj, _("(no subj)"), -1,0);
460                                 else {
461                                         StrBuf_RFC822_to_Utf8(Msg->subj, Buf2, WCC->DefaultCharset, FoundCharset);
462                                         if ((StrLength(Msg->subj) > 75) && 
463                                             (StrBuf_Utf8StrLen(Msg->subj) > 75)) {
464                                                 StrBuf_Utf8StrCut(Msg->subj, 72);
465                                                 StrBufAppendBufPlain(Msg->subj, HKEY("..."), 0);
466                                         }
467                                 }
468
469
470                                 if ((StrLength(Msg->from) > 25) && 
471                                     (StrBuf_Utf8StrLen(Msg->from) > 25)) {
472                                         StrBuf_Utf8StrCut(Msg->from, 23);
473                                         StrBufAppendBufPlain(Msg->from, HKEY("..."), 0);
474                                 }
475                         }
476                         n = Msg->msgnum;
477                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
478                 }
479                 nummsgs++;
480         }
481         FreeStrBuf(&Buf2);
482         FreeStrBuf(&Buf);
483         return (nummsgs);
484 }
485
486
487 inline message_summary* GetMessagePtrAt(int n, HashList *Summ)
488 {
489         const char *Key;
490         long HKLen;
491         void *vMsg;
492
493         if (Summ == NULL)
494                 return NULL;
495         GetHashAt(Summ, n, &HKLen, &Key, &vMsg);
496         return (message_summary*) vMsg;
497 }
498
499
500 long DrawMessageDropdown(StrBuf *Selector, long maxmsgs, long startmsg, int nMessages)
501 {
502         StrBuf *TmpBuf;
503         wcsession *WCC = WC;
504         void *vMsg;
505         int lo, hi;
506         long ret;
507         long hklen;
508         const char *key;
509         int done = 0;
510         int nItems;
511         HashPos *At;
512         long vector[16];
513
514         TmpBuf = NewStrBuf();
515         At = GetNewHashPos(WCC->summ, nMessages);
516         nItems = GetCount(WCC->summ);
517         ret = nMessages;
518         vector[0] = 7;
519         vector[2] = 1;
520         vector[1] = startmsg;
521         vector[3] = 0;
522
523         while (!done) {
524                 vector[3] = abs(nMessages);
525                 lo = GetHashPosCounter(At);
526                 if (nMessages > 0) {
527                         if (lo + nMessages >= nItems) {
528                                 hi = nItems - 1;
529                                 vector[3] = nItems - lo;
530                                 if (startmsg == lo) 
531                                         ret = vector[3];
532                         }
533                         else {
534                                 hi = lo + nMessages - 1;
535                         }
536                 } else {
537                         if (lo + nMessages < -1) {
538                                 hi = 0;
539                         }
540                         else {
541                                 if ((lo % abs(nMessages)) != 0) {
542                                         int offset = (lo % abs(nMessages) *
543                                                       (nMessages / abs(nMessages)));
544                                         hi = lo + offset;
545                                         vector[3] = abs(offset);
546                                         if (startmsg == lo)
547                                                  ret = offset;
548                                 }
549                                 else
550                                         hi = lo + nMessages;
551                         }
552                 }
553                 done = !GetNextHashPos(WCC->summ, At, &hklen, &key, &vMsg);
554                 
555                 /**
556                  * Bump these because although we're thinking in zero base, the user
557                  * is a drooling idiot and is thinking in one base.
558                  */
559                 vector[4] = lo + 1;
560                 vector[5] = hi + 1;
561                 vector[6] = lo;
562                 FlushStrBuf(TmpBuf);
563                 dbg_print_longvector(vector);
564                 DoTemplate(HKEY("select_messageindex"), TmpBuf, &vector, CTX_LONGVECTOR);
565                 StrBufAppendBuf(Selector, TmpBuf, 0);
566         }
567         vector[6] = 0;
568         FlushStrBuf(TmpBuf);
569         vector[1] = lbstr("maxmsgs") == 9999999;
570         vector[2] = 0;
571         dbg_print_longvector(vector);
572         DoTemplate(HKEY("select_messageindex_all"), TmpBuf, &vector, CTX_LONGVECTOR);
573         StrBufAppendBuf(Selector, TmpBuf, 0);
574         FreeStrBuf(&TmpBuf);
575         DeleteHashPos(&At);
576         return ret;
577 }
578
579 void load_seen_flags(void)
580 {
581         message_summary *Msg;
582         const char *HashKey;
583         long HKLen;
584         StrBuf *OldMsg = NewStrBuf();;
585         wcsession *WCC = WC;
586         HashPos *at;
587         void *vMsg;
588
589         serv_puts("GTSN");
590         StrBuf_ServGetln(OldMsg);
591         if (ChrPtr(OldMsg)[0] == '2') {
592                 StrBufCutLeft(OldMsg, 4);
593         }
594         else {
595                 FreeStrBuf(&OldMsg);
596                 return;
597         }
598         at = GetNewHashPos(WCC->summ, 0);
599         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
600                 /** Are you a new message, or an old message? */
601                 Msg = (message_summary*) vMsg;
602                 if (is_msg_in_mset(ChrPtr(OldMsg), Msg->msgnum)) {
603                         Msg->is_new = 0;
604                 }
605                 else {
606                         Msg->is_new = 1;
607                 }
608         }
609         FreeStrBuf(&OldMsg);
610         DeleteHashPos(&at);
611 }
612
613 extern readloop_struct rlid[];
614
615 /*
616  * command loop for reading messages
617  *
618  * Set oper to "readnew" or "readold" or "readfwd" or "headers"
619  */
620 void readloop(long oper)
621 {
622         StrBuf *MessageDropdown = NULL;
623         StrBuf *BBViewToolBar = NULL;
624         void *vMsg;
625         message_summary *Msg;
626         char cmd[256] = "";
627         char buf[SIZ];
628         int a = 0;
629         int with_headers = 0;
630         int nummsgs;
631         long startmsg = 0;
632         int maxmsgs = 0;
633         long *displayed_msgs = NULL;
634         int num_displayed = 0;
635         int is_singlecard = 0;
636         struct calview calv;
637         int i;
638         int lowest_displayed = (-1);
639         int highest_displayed = 0;
640         addrbookent *addrbook = NULL;
641         int num_ab = 0;
642         int bbs_reverse = 0;
643         wcsession *WCC = WC;
644         HashPos *at;
645         const char *HashKey;
646         long HKLen;
647         int care_for_empty_list = 0;
648         int load_seen = 0;
649         int sortit = 0;
650         int defaultsortorder = 0;
651
652         if (havebstr("is_summary") && (1 == (ibstr("is_summary"))))
653                 WCC->wc_view = VIEW_MAILBOX;
654
655         switch (WCC->wc_view) {
656         case VIEW_WIKI:
657                 sprintf(buf, "wiki?room=%s&page=home", WCC->wc_roomname);
658                 http_redirect(buf);
659                 return;
660         case VIEW_CALBRIEF:
661         case VIEW_CALENDAR:
662                 load_seen = 1;
663                 strcpy(cmd, "MSGS ALL|||1");
664                 maxmsgs = 32767;
665                 parse_calendar_view_request(&calv);
666                 break;
667         case VIEW_TASKS:
668                 strcpy(cmd, "MSGS ALL");
669                 maxmsgs = 32767;
670                 break;
671         case VIEW_NOTES:
672                 strcpy(cmd, "MSGS ALL");
673                 maxmsgs = 32767;
674                 wprintf("<div id=\"new_notes_here\"></div>\n");
675                 break;
676         case VIEW_ADDRESSBOOK:
677                 is_singlecard = ibstr("is_singlecard");
678                 if (is_singlecard != 1) {
679                         if (oper == do_search) {
680                                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
681                         }
682                         else {
683                                 strcpy(cmd, "MSGS ALL");
684                         }
685                         maxmsgs = 9999999;
686                         break;
687                 }
688                 break;
689         case VIEW_MAILBOX: 
690                 defaultsortorder = 2;
691                 sortit = 1;
692                 load_seen = 1;
693                 care_for_empty_list = 1;
694                 with_headers = 1;
695                 if (WCC->is_mobile) maxmsgs = 20;
696                 else maxmsgs = 9999999;
697                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
698                          (oper == do_search) ? "SEARCH" : "ALL",
699                          (oper == do_search) ? bstr("query") : ""
700                         );
701                 break;
702         case VIEW_BBS:
703         default:
704                 defaultsortorder = 1;
705                 startmsg = -1;
706                 sortit = 1;
707                 care_for_empty_list = 1;
708
709                 rlid[oper].cmd(cmd, sizeof(cmd));
710                 SetAccessCommand(oper);
711
712                 if (havebstr("maxmsgs"))
713                         maxmsgs = ibstr("maxmsgs");
714                 if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
715
716                 if (havebstr("startmsg")) {
717                         startmsg = lbstr("startmsg");
718                 }
719                 
720         }
721         output_headers(1, 1, 1, 0, 0, 0);
722
723         nummsgs = load_msg_ptrs(cmd, with_headers);
724         if (nummsgs == 0) {
725                 if (care_for_empty_list) {
726                         wprintf("<div align=\"center\"><br /><em>");
727                         switch (oper) {
728                         case readnew:
729                                 wprintf(_("No new messages."));
730                                 break;
731                         case readold:
732                                 wprintf(_("No old messages."));
733                                 break;
734                         default:
735                                 wprintf(_("No messages here."));
736                         }
737                         wprintf("</em><br /></div>\n");
738                 }
739
740                 goto DONE;
741         }
742
743         if (sortit) {
744                 CompareFunc SortIt;
745                 SortIt =  RetrieveSort(CTX_MAILSUM, NULL, 
746                                        HKEY("date"), defaultsortorder);
747                 if (SortIt != NULL)
748                         SortByPayload(WCC->summ, SortIt);
749                 if (WCC->wc_view == VIEW_BBS) {
750                         if (lbstr("SortOrder") == 2) {
751                                 bbs_reverse = 1;
752                                 num_displayed = -DEFAULT_MAXMSGS;
753                         }
754                         else {
755                                 bbs_reverse = 0;
756                                 num_displayed = DEFAULT_MAXMSGS;
757                         }
758                 }
759         }
760         if (startmsg < 0) startmsg = (bbs_reverse) ? nummsgs - 1 : 0;
761
762         if (load_seen) load_seen_flags();
763         
764         /**
765          * If we're to print s.th. above the message list...
766          */
767         switch (WCC->wc_view) {
768         case VIEW_MAILBOX: 
769                 do_template("summary_header", NULL);
770                 break;
771         case VIEW_BBS:
772                 BBViewToolBar = NewStrBuf();
773                 MessageDropdown = NewStrBuf();
774
775                 maxmsgs = DrawMessageDropdown(MessageDropdown, maxmsgs, startmsg, num_displayed);
776                 if (num_displayed < 0) {
777                         startmsg += maxmsgs;
778                         if (num_displayed != maxmsgs)                           
779                                 maxmsgs = abs(maxmsgs) + 1;
780                         else
781                                 maxmsgs = abs(maxmsgs);
782
783                 }
784                 DoTemplate(HKEY("msg_listselector_top"), BBViewToolBar, MessageDropdown, CTX_STRBUF);
785                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
786                 FlushStrBuf(BBViewToolBar);
787                 break;
788         }
789                         
790         /*
791          * iterate over each message. if we need to load an attachment, do it here. 
792          */
793         at = GetNewHashPos(WCC->summ, 0);
794         num_displayed = i = 0;
795         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
796                 Msg = (message_summary*) vMsg;          
797                 if ((Msg->msgnum >= startmsg) && (num_displayed <= maxmsgs)) {                  
798                         switch (WCC->wc_view) {
799                         case VIEW_WIKI:
800                                 break;
801                         case VIEW_CALBRIEF: /* load the mime attachments for special tasks... */
802                         case VIEW_CALENDAR:
803                                 load_calendar_item(Msg, Msg->is_new, &calv);
804                                 break;
805                         case VIEW_TASKS:
806                                 display_task(Msg, Msg->is_new);
807                                 break;
808                         case VIEW_NOTES:
809                                 display_note(Msg, Msg->is_new);
810                                 break;
811                         case VIEW_ADDRESSBOOK:
812                                 fetch_ab_name(Msg, buf);
813                                 ++num_ab;
814                                 addrbook = realloc(addrbook,
815                                                    (sizeof(addrbookent) * num_ab) );
816                                 safestrncpy(addrbook[num_ab-1].ab_name, buf,
817                                             sizeof(addrbook[num_ab-1].ab_name));
818                                 addrbook[num_ab-1].ab_msgnum = Msg->msgnum;
819                                 break;
820                         case VIEW_MAILBOX: /* here we just need the abstract, so render it now. */
821                                 DoTemplate(HKEY("section_mailsummary"), NULL, Msg, CTX_MAILSUM);
822                         
823                                 num_displayed++;
824                                 break;
825                         case VIEW_BBS: /* Tag the mails we want to show in bbview... */
826                         default:
827                                 if (displayed_msgs == NULL) {
828                                         displayed_msgs = malloc(sizeof(long) *
829                                                                 (maxmsgs<nummsgs ? maxmsgs + 1 : nummsgs + 1));
830                                 }
831                                 if ((i >= startmsg) && (i < startmsg + maxmsgs)) {
832                                         displayed_msgs[num_displayed] = Msg->msgnum;
833                                         if (lowest_displayed < 0) lowest_displayed = a;
834                                         highest_displayed = a;
835                         
836                                         num_displayed++;
837                                 }
838                         }
839                 }
840                 i++;
841         }
842         DeleteHashPos(&at);
843
844
845         /*
846          * Done iterating the message list. now tasks we want to do after.
847          */
848         switch (WCC->wc_view) {
849         case VIEW_MAILBOX: 
850                 do_template("summary_trailer", NULL);
851                 break;
852         case VIEW_BBS:
853                 if (displayed_msgs != NULL) {
854                         /** if we do a split bbview in the future, begin messages div here */
855                         
856                         for (a=0; a<num_displayed; ++a) {
857                                 read_message(WCC->WBuf, HKEY("view_message"), displayed_msgs[a], 0, NULL);
858                         }
859                         
860                         /** if we do a split bbview in the future, end messages div here */
861                         
862                         free(displayed_msgs);
863                         displayed_msgs = NULL;
864                 }
865                 DoTemplate(HKEY("msg_listselector_bottom"), BBViewToolBar, MessageDropdown, CTX_STRBUF);
866                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
867
868                 FreeStrBuf(&BBViewToolBar);
869                 FreeStrBuf(&MessageDropdown);
870         }
871
872         
873 DONE:
874         switch (WCC->wc_view) {
875         case VIEW_WIKI:
876                 break;
877         case VIEW_CALBRIEF:
878         case VIEW_CALENDAR:
879                 render_calendar_view(&calv);
880                 break;
881         case VIEW_TASKS:
882                 do_tasks_view();        /** Render the task list */
883                 break;
884         case VIEW_NOTES:
885                 break;
886         case VIEW_ADDRESSBOOK:
887                 do_addrbook_view(addrbook, num_ab);     /** Render the address book */
888                 break;
889         case VIEW_MAILBOX: 
890         case VIEW_BBS:
891         default:
892                 break;
893         }
894         /** Note: wDumpContent() will output one additional </div> tag. */
895         wprintf("</div>\n");            /** end of 'content' div */
896         wDumpContent(1);
897
898         /** free the summary */
899         if (WCC->summ != NULL) {
900                 DeleteHash(&WCC->summ);
901         }
902         if (addrbook != NULL) free(addrbook);
903         FreeStrBuf(&BBViewToolBar);
904 }
905
906
907 /*
908  * Back end for post_message()
909  * ... this is where the actual message gets transmitted to the server.
910  */
911 void post_mime_to_server(void) {
912         wcsession *WCC = WC;
913         char top_boundary[SIZ];
914         char alt_boundary[SIZ];
915         int is_multipart = 0;
916         static int seq = 0;
917         wc_mime_attachment *att;
918         char *encoded;
919         size_t encoded_length;
920         size_t encoded_strlen;
921         char *txtmail = NULL;
922
923         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
924                 serv_info.serv_fqdn,
925                 getpid(),
926                 ++seq
927         );
928         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
929                 serv_info.serv_fqdn,
930                 getpid(),
931                 ++seq
932         );
933
934         /* RFC2045 requires this, and some clients look for it... */
935         serv_puts("MIME-Version: 1.0");
936         serv_puts("X-Mailer: " PACKAGE_STRING);
937
938         /* If there are attachments, we have to do multipart/mixed */
939         if (GetCount(WCC->attachments) > 0) {
940                 is_multipart = 1;
941         }
942
943         if (is_multipart) {
944                 /* Remember, serv_printf() appends an extra newline */
945                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
946                 serv_printf("This is a multipart message in MIME format.\n");
947                 serv_printf("--%s", top_boundary);
948         }
949
950         /* Remember, serv_printf() appends an extra newline */
951         serv_printf("Content-type: multipart/alternative; "
952                 "boundary=\"%s\"\n", alt_boundary);
953         serv_printf("This is a multipart message in MIME format.\n");
954         serv_printf("--%s", alt_boundary);
955
956         serv_puts("Content-type: text/plain; charset=utf-8");
957         serv_puts("Content-Transfer-Encoding: quoted-printable");
958         serv_puts("");
959         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
960         text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
961         free(txtmail);
962
963         serv_printf("--%s", alt_boundary);
964
965         serv_puts("Content-type: text/html; charset=utf-8");
966         serv_puts("Content-Transfer-Encoding: quoted-printable");
967         serv_puts("");
968         serv_puts("<html><body>\r\n");
969         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
970         serv_puts("</body></html>\r\n");
971
972         serv_printf("--%s--", alt_boundary);
973         
974         if (is_multipart) {
975                 long len;
976                 const char *Key; 
977                 void *vAtt;
978                 HashPos  *it;
979
980                 /* Add in the attachments */
981                 it = GetNewHashPos(WCC->attachments, 0);
982                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
983                         att = (wc_mime_attachment *)vAtt;
984                         encoded_length = ((att->length * 150) / 100);
985                         encoded = malloc(encoded_length);
986                         if (encoded == NULL) break;
987                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
988
989                         serv_printf("--%s", top_boundary);
990                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
991                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
992                         serv_puts("Content-transfer-encoding: base64");
993                         serv_puts("");
994                         serv_write(encoded, encoded_strlen);
995                         serv_puts("");
996                         serv_puts("");
997                         free(encoded);
998                 }
999                 serv_printf("--%s--", top_boundary);
1000                 DeleteHashPos(&it);
1001         }
1002
1003         serv_puts("000");
1004 }
1005
1006
1007 /*
1008  * Post message (or don't post message)
1009  *
1010  * Note regarding the "dont_post" variable:
1011  * A random value (actually, it's just a timestamp) is inserted as a hidden
1012  * field called "postseq" when the display_enter page is generated.  This
1013  * value is checked when posting, using the static variable dont_post.  If a
1014  * user attempts to post twice using the same dont_post value, the message is
1015  * discarded.  This prevents the accidental double-saving of the same message
1016  * if the user happens to click the browser "back" button.
1017  */
1018 void post_message(void)
1019 {
1020         char buf[1024];
1021         StrBuf *encoded_subject = NULL;
1022         static long dont_post = (-1L);
1023         wc_mime_attachment  *att;
1024         int is_anonymous = 0;
1025         const StrBuf *display_name = NULL;
1026         wcsession *WCC = WC;
1027         
1028         if (havebstr("force_room")) {
1029                 gotoroom(bstr("force_room"));
1030         }
1031
1032         if (havebstr("display_name")) {
1033                 display_name = sbstr("display_name");
1034                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1035                         display_name = NULL;
1036                         is_anonymous = 1;
1037                 }
1038         }
1039
1040         if (WCC->upload_length > 0) {
1041                 const char *pch;
1042                 int n;
1043                 char N[64];
1044
1045                 lprintf(9, "%s:%d: we are uploading %d bytes\n", __FILE__, __LINE__, WCC->upload_length);
1046                 /** There's an attachment.  Save it to this struct... */
1047                 att = malloc(sizeof(wc_mime_attachment));
1048                 memset(att, 0, sizeof(wc_mime_attachment ));
1049                 att->length = WCC->upload_length;
1050                 att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1051                 att->FileName = NewStrBufPlain(WCC->upload_filename, -1);
1052                 
1053                 
1054                 if (WCC->attachments == NULL)
1055                         WCC->attachments = NewHash(1, NULL);
1056                 /* And add it to the list. */
1057                 n = snprintf(N, sizeof N, "%d", GetCount(WCC->attachments) + 1);
1058                 Put(WCC->attachments, N, n, att, DestroyMime);
1059
1060                 /**
1061                  * Mozilla sends a simple filename, which is what we want,
1062                  * but Satan's Browser sends an entire pathname.  Reduce
1063                  * the path to just a filename if we need to.
1064                  */
1065                 pch = strrchr(ChrPtr(att->FileName), '/');
1066                 if (pch != NULL) {
1067                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName));
1068                 }
1069                 pch = strrchr(ChrPtr(att->FileName), '\\');
1070                 if (pch != NULL) {
1071                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName));
1072                 }
1073
1074                 /**
1075                  * Transfer control of this memory from the upload struct
1076                  * to the attachment struct.
1077                  */
1078                 att->Data = NewStrBufPlain(WCC->upload, WCC->upload_length);
1079                 free(WCC->upload);
1080                 WCC->upload_length = 0;
1081                 WCC->upload = NULL;
1082                 display_enter();
1083                 return;
1084         }
1085
1086         if (havebstr("cancel_button")) {
1087                 sprintf(WCC->ImportantMessage, 
1088                         _("Cancelled.  Message was not posted."));
1089         } else if (havebstr("attach_button")) {
1090                 display_enter();
1091                 return;
1092         } else if (lbstr("postseq") == dont_post) {
1093                 sprintf(WCC->ImportantMessage, 
1094                         _("Automatically cancelled because you have already "
1095                         "saved this message."));
1096         } else {
1097                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1098                 const StrBuf *Recp = NULL; 
1099                 const StrBuf *Cc = NULL;
1100                 const StrBuf *Bcc = NULL;
1101                 const StrBuf *Wikipage = NULL;
1102                 const StrBuf *my_email_addr = NULL;
1103                 StrBuf *CmdBuf = NULL;;
1104                 StrBuf *references = NULL;
1105
1106                 if (havebstr("references"))
1107                 {
1108                         const StrBuf *ref = sbstr("references");
1109                         references = NewStrBufPlain(ChrPtr(ref), StrLength(ref));
1110                         lprintf(9, "Converting: %s\n", ChrPtr(references));
1111                         StrBufReplaceChars(references, '|', '!');
1112                         lprintf(9, "Converted: %s\n", ChrPtr(references));
1113                 }
1114                 if (havebstr("subject")) {
1115                         const StrBuf *Subj;
1116                         /*
1117                          * make enough room for the encoded string; 
1118                          * plus the QP header 
1119                          */
1120                         Subj = sbstr("subject");
1121                         
1122                         StrBufRFC2047encode(&encoded_subject, Subj);
1123                 }
1124                 Recp = sbstr("recp");
1125                 Cc = sbstr("cc");
1126                 Bcc = sbstr("bcc");
1127                 Wikipage = sbstr("wikipage");
1128                 my_email_addr = sbstr("my_email_addr");
1129                 
1130                 CmdBuf = NewStrBufPlain(NULL, 
1131                                         sizeof (CMD) + 
1132                                         StrLength(Recp) + 
1133                                         StrLength(encoded_subject) +
1134                                         StrLength(Cc) +
1135                                         StrLength(Bcc) + 
1136                                         StrLength(Wikipage) +
1137                                         StrLength(my_email_addr) + 
1138                                         StrLength(references));
1139
1140                 StrBufPrintf(CmdBuf, 
1141                              CMD,
1142                              ChrPtr(Recp),
1143                              is_anonymous,
1144                              ChrPtr(encoded_subject),
1145                              ChrPtr(display_name),
1146                              ChrPtr(Cc),
1147                              ChrPtr(Bcc),
1148                              ChrPtr(Wikipage),
1149                              ChrPtr(my_email_addr),
1150                              ChrPtr(references));
1151                 FreeStrBuf(&references);
1152
1153                 lprintf(9, "%s\n", ChrPtr(CmdBuf));
1154                 serv_puts(ChrPtr(CmdBuf));
1155                 serv_getln(buf, sizeof buf);
1156                 FreeStrBuf(&CmdBuf);
1157                 FreeStrBuf(&encoded_subject);
1158                 if (buf[0] == '4') {
1159                         post_mime_to_server();
1160                         if (  (havebstr("recp"))
1161                            || (havebstr("cc"  ))
1162                            || (havebstr("bcc" ))
1163                         ) {
1164                                 sprintf(WCC->ImportantMessage, _("Message has been sent.\n"));
1165                         }
1166                         else {
1167                                 sprintf(WC->ImportantMessage, _("Message has been posted.\n"));
1168                         }
1169                         dont_post = lbstr("postseq");
1170                 } else {
1171                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, buf);
1172                         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1173                         display_enter();
1174                         return;
1175                 }
1176         }
1177
1178         DeleteHash(&WCC->attachments);
1179
1180         /**
1181          *  We may have been supplied with instructions regarding the location
1182          *  to which we must return after posting.  If found, go there.
1183          */
1184         if (havebstr("return_to")) {
1185                 http_redirect(bstr("return_to"));
1186         }
1187         /**
1188          *  If we were editing a page in a wiki room, go to that page now.
1189          */
1190         else if (havebstr("wikipage")) {
1191                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
1192                 http_redirect(buf);
1193         }
1194         /**
1195          *  Otherwise, just go to the "read messages" loop.
1196          */
1197         else {
1198                 readloop(readnew);
1199         }
1200 }
1201
1202
1203
1204
1205 /**
1206  * \brief display the message entry screen
1207  */
1208 void display_enter(void)
1209 {
1210         char buf[SIZ];
1211         long now;
1212         const StrBuf *display_name = NULL;
1213         int recipient_required = 0;
1214         int subject_required = 0;
1215         int recipient_bad = 0;
1216         int is_anonymous = 0;
1217         wcsession *WCC = WC;
1218
1219         now = time(NULL);
1220
1221         if (havebstr("force_room")) {
1222                 gotoroom(bstr("force_room"));
1223         }
1224
1225         display_name = sbstr("display_name");
1226         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1227                 display_name = NULL;
1228                 is_anonymous = 1;
1229         }
1230
1231         /** First test to see whether this is a room that requires recipients to be entered */
1232         serv_puts("ENT0 0");
1233         serv_getln(buf, sizeof buf);
1234
1235         if (!strncmp(buf, "570", 3)) {          /** 570 means that we need a recipient here */
1236                 recipient_required = 1;
1237         }
1238         else if (buf[0] != '2') {               /** Any other error means that we cannot continue */
1239                 sprintf(WCC->ImportantMessage, "%s", &buf[4]);
1240                 readloop(readnew);
1241                 return;
1242         }
1243
1244         /* Is the server strongly recommending that the user enter a message subject? */
1245         if ((buf[3] != '\0') && (buf[4] != '\0')) {
1246                 subject_required = extract_int(&buf[4], 1);
1247         }
1248
1249         /**
1250          * Are we perhaps in an address book view?  If so, then an "enter
1251          * message" command really means "add new entry."
1252          */
1253         if (WCC->wc_default_view == VIEW_ADDRESSBOOK) {
1254                 do_edit_vcard(-1, "", "", WCC->wc_roomname);
1255                 return;
1256         }
1257
1258         /*
1259          * Are we perhaps in a calendar room?  If so, then an "enter
1260          * message" command really means "add new calendar item."
1261          */
1262         if (WCC->wc_default_view == VIEW_CALENDAR) {
1263                 display_edit_event();
1264                 return;
1265         }
1266
1267         /*
1268          * Are we perhaps in a tasks view?  If so, then an "enter
1269          * message" command really means "add new task."
1270          */
1271         if (WCC->wc_default_view == VIEW_TASKS) {
1272                 display_edit_task();
1273                 return;
1274         }
1275
1276         /*
1277          * Otherwise proceed normally.
1278          * Do a custom room banner with no navbar...
1279          */
1280
1281         if (recipient_required) {
1282                 const StrBuf *Recp = NULL; 
1283                 const StrBuf *Cc = NULL;
1284                 const StrBuf *Bcc = NULL;
1285                 const StrBuf *Wikipage = NULL;
1286                 StrBuf *CmdBuf = NULL;;
1287                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1288                 
1289                 Recp = sbstr("recp");
1290                 Cc = sbstr("cc");
1291                 Bcc = sbstr("bcc");
1292                 Wikipage = sbstr("wikipage");
1293                 
1294                 CmdBuf = NewStrBufPlain(NULL, 
1295                                         sizeof (CMD) + 
1296                                         StrLength(Recp) + 
1297                                         StrLength(display_name) +
1298                                         StrLength(Cc) +
1299                                         StrLength(Bcc) + 
1300                                         StrLength(Wikipage));
1301
1302                 StrBufPrintf(CmdBuf, 
1303                              CMD,
1304                              ChrPtr(Recp), 
1305                              is_anonymous,
1306                              ChrPtr(display_name),
1307                              ChrPtr(Cc), 
1308                              ChrPtr(Bcc), 
1309                              ChrPtr(Wikipage));
1310                 serv_puts(ChrPtr(CmdBuf));
1311                 serv_getln(buf, sizeof buf);
1312                 FreeStrBuf(&CmdBuf);
1313
1314                 if (!strncmp(buf, "570", 3)) {  /** 570 means we have an invalid recipient listed */
1315                         if (havebstr("recp") && 
1316                             havebstr("cc"  ) && 
1317                             havebstr("bcc" )) {
1318                                 recipient_bad = 1;
1319                         }
1320                 }
1321                 else if (buf[0] != '2') {       /** Any other error means that we cannot continue */
1322                         wprintf("<em>%s</em><br />\n", &buf[4]);/// -> important message
1323                         return;
1324                 }
1325         }
1326         svputlong("RCPTREQUIRED", recipient_required);
1327         svputlong("SUBJREQUIRED", recipient_required || subject_required);
1328
1329         begin_burst();
1330         output_headers(1, 0, 0, 0, 1, 0);
1331         DoTemplate(HKEY("edit_message"), NULL, NULL, CTX_NONE);
1332         end_burst();
1333
1334         return;
1335 }
1336
1337 /**
1338  * \brief delete a message
1339  */
1340 void delete_msg(void)
1341 {
1342         long msgid;
1343         char buf[SIZ];
1344
1345         msgid = lbstr("msgid");
1346
1347         if (WC->wc_is_trash) {  /** Delete from Trash is a real delete */
1348                 serv_printf("DELE %ld", msgid); 
1349         }
1350         else {                  /** Otherwise move it to Trash */
1351                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1352         }
1353
1354         serv_getln(buf, sizeof buf);
1355         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1356
1357         readloop(readnew);
1358 }
1359
1360
1361 /**
1362  * \brief move a message to another folder
1363  */
1364 void move_msg(void)
1365 {
1366         long msgid;
1367         char buf[SIZ];
1368
1369         msgid = lbstr("msgid");
1370
1371         if (havebstr("move_button")) {
1372                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
1373                 serv_puts(buf);
1374                 serv_getln(buf, sizeof buf);
1375                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
1376         } else {
1377                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
1378         }
1379
1380         readloop(readnew);
1381 }
1382
1383
1384
1385
1386
1387 /*
1388  * Confirm move of a message
1389  */
1390 void confirm_move_msg(void)
1391 {
1392         long msgid;
1393         char buf[SIZ];
1394         char targ[SIZ];
1395
1396         msgid = lbstr("msgid");
1397
1398
1399         output_headers(1, 1, 2, 0, 0, 0);
1400         wprintf("<div id=\"banner\">\n");
1401         wprintf("<h1>");
1402         wprintf(_("Confirm move of message"));
1403         wprintf("</h1>");
1404         wprintf("</div>\n");
1405
1406         wprintf("<div id=\"content\" class=\"service\">\n");
1407
1408         wprintf("<CENTER>");
1409
1410         wprintf(_("Move this message to:"));
1411         wprintf("<br />\n");
1412
1413         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
1414         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
1415         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
1416
1417         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
1418         serv_puts("LKRA");
1419         serv_getln(buf, sizeof buf);
1420         if (buf[0] == '1') {
1421                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1422                         extract_token(targ, buf, 0, '|', sizeof targ);
1423                         wprintf("<OPTION>");
1424                         escputs(targ);
1425                         wprintf("\n");
1426                 }
1427         }
1428         wprintf("</SELECT>\n");
1429         wprintf("<br />\n");
1430
1431         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
1432         wprintf("&nbsp;");
1433         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
1434         wprintf("</form></CENTER>\n");
1435
1436         wprintf("</CENTER>\n");
1437         wDumpContent(1);
1438 }
1439
1440
1441 /*
1442  * Generic function to output an arbitrary MIME attachment from
1443  * message being composed
1444  *
1445  * partnum              The MIME part to be output
1446  * filename             Fake filename to give
1447  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1448  */
1449 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1450 {
1451         void *vPart;
1452         StrBuf *content_type;
1453         wc_mime_attachment *part;
1454         
1455         if (GetHash(WC->attachments, SKEY(partnum), &vPart) &&
1456             (vPart != NULL)) {
1457                 part = (wc_mime_attachment*) vPart;
1458                 if (force_download) {
1459                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1460                 }
1461                 else {
1462                         content_type = NewStrBufDup(part->ContentType);
1463                 }
1464                 output_headers(0, 0, 0, 0, 0, 0);
1465                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1466                 http_transmit_thing(ChrPtr(content_type), 0);
1467         } else {
1468                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1469                 output_headers(0, 0, 0, 0, 0, 0);
1470                 hprintf("Content-Type: text/plain\r\n");
1471                 wprintf(_("An error occurred while retrieving this part: %s/%s\n"), 
1472                         ChrPtr(partnum), ChrPtr(filename));
1473                 end_burst();
1474         }
1475         FreeStrBuf(&content_type);
1476 }
1477
1478
1479 /*
1480  * Generic function to output an arbitrary MIME part from an arbitrary
1481  * message number on the server.
1482  *
1483  * msgnum               Number of the item on the citadel server
1484  * partnum              The MIME part to be output
1485  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1486  */
1487 void mimepart(const char *msgnum, const char *partnum, int force_download)
1488 {
1489         char buf[256];
1490         off_t bytes;
1491         char content_type[256];
1492         
1493         serv_printf("OPNA %s|%s", msgnum, partnum);
1494         serv_getln(buf, sizeof buf);
1495         if (buf[0] == '2') {
1496                 bytes = extract_long(&buf[4], 0);
1497                 if (force_download) {
1498                         strcpy(content_type, "application/octet-stream");
1499                 }
1500                 else {
1501                         extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1502                 }
1503                 output_headers(0, 0, 0, 0, 0, 0);
1504
1505                 read_server_binary(WC->WBuf, bytes);
1506                 serv_puts("CLOS");
1507                 serv_getln(buf, sizeof buf);
1508                 http_transmit_thing(content_type, 0);
1509         } else {
1510                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
1511                 output_headers(0, 0, 0, 0, 0, 0);
1512                 hprintf("Content-Type: text/plain\r\n");
1513                 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
1514                 end_burst();
1515         }
1516 }
1517
1518
1519 /*
1520  * Read any MIME part of a message, from the server, into memory.
1521  */
1522 char *load_mimepart(long msgnum, char *partnum)
1523 {
1524         char buf[SIZ];
1525         off_t bytes;
1526         char content_type[SIZ];
1527         char *content;
1528         
1529         serv_printf("DLAT %ld|%s", msgnum, partnum);
1530         serv_getln(buf, sizeof buf);
1531         if (buf[0] == '6') {
1532                 bytes = extract_long(&buf[4], 0);
1533                 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1534
1535                 content = malloc(bytes + 2);
1536                 serv_read(content, bytes);
1537
1538                 content[bytes] = 0;     /* null terminate for good measure */
1539                 return(content);
1540         }
1541         else {
1542                 return(NULL);
1543         }
1544 }
1545
1546 /*
1547  * Read any MIME part of a message, from the server, into memory.
1548  */
1549 void MimeLoadData(wc_mime_attachment *Mime)
1550 {
1551         char buf[SIZ];
1552         off_t bytes;
1553 //// TODO: is there a chance the contenttype is different  to the one we know?  
1554         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1555         serv_getln(buf, sizeof buf);
1556         if (buf[0] == '6') {
1557                 bytes = extract_long(&buf[4], 0);
1558
1559                 if (Mime->Data == NULL)
1560                         Mime->Data = NewStrBufPlain(NULL, bytes);
1561                 StrBuf_ServGetBLOB(Mime->Data, bytes);
1562
1563         }
1564         else {
1565                 FlushStrBuf(Mime->Data);
1566                 /// TODO XImportant message
1567         }
1568 }
1569
1570
1571
1572
1573 void view_mimepart(void) {
1574         mimepart(ChrPtr(WC->UrlFragment2),
1575                  ChrPtr(WC->UrlFragment3),
1576                  0);
1577 }
1578
1579 void download_mimepart(void) {
1580         mimepart(ChrPtr(WC->UrlFragment2),
1581                  ChrPtr(WC->UrlFragment3),
1582                  1);
1583 }
1584
1585 void view_postpart(void) {
1586         postpart(WC->UrlFragment2,
1587                  WC->UrlFragment3,
1588                  0);
1589 }
1590
1591 void download_postpart(void) {
1592         postpart(WC->UrlFragment2,
1593                  WC->UrlFragment3,
1594                  1);
1595 }
1596
1597 void h_readnew(void) { readloop(readnew);}
1598 void h_readold(void) { readloop(readold);}
1599 void h_readfwd(void) { readloop(readfwd);}
1600 void h_headers(void) { readloop(headers);}
1601 void h_do_search(void) { readloop(do_search);}
1602
1603 void 
1604 InitModule_MSG
1605 (void)
1606 {
1607         WebcitAddUrlHandler(HKEY("readnew"), h_readnew, NEED_URL);
1608         WebcitAddUrlHandler(HKEY("readold"), h_readold, NEED_URL);
1609         WebcitAddUrlHandler(HKEY("readfwd"), h_readfwd, NEED_URL);
1610         WebcitAddUrlHandler(HKEY("headers"), h_headers, NEED_URL);
1611         WebcitAddUrlHandler(HKEY("do_search"), h_do_search, 0);
1612         WebcitAddUrlHandler(HKEY("display_enter"), display_enter, 0);
1613         WebcitAddUrlHandler(HKEY("post"), post_message, 0);
1614         WebcitAddUrlHandler(HKEY("move_msg"), move_msg, 0);
1615         WebcitAddUrlHandler(HKEY("delete_msg"), delete_msg, 0);
1616         WebcitAddUrlHandler(HKEY("confirm_move_msg"), confirm_move_msg, 0);
1617         WebcitAddUrlHandler(HKEY("msg"), embed_message, NEED_URL|AJAX);
1618         WebcitAddUrlHandler(HKEY("printmsg"), print_message, NEED_URL);
1619         WebcitAddUrlHandler(HKEY("mobilemsg"), mobile_message_view, NEED_URL);
1620         WebcitAddUrlHandler(HKEY("msgheaders"), display_headers, NEED_URL);
1621
1622         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1623         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1624         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
1625         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
1626
1627         return ;
1628 }