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