* Modified load_msg_pointers(), gave it the ability to return the lowest and highest...
[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 dbg_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 void jsonMessageListHdr(void);
22
23 void display_enter(void);
24
25 typedef void (*MsgPartEvaluatorFunc)(message_summary *Sum, StrBuf *Buf);
26
27 typedef struct _MsgPartEvaluatorStruct {
28         MsgPartEvaluatorFunc f;
29 } MsgPartEvaluatorStruct;
30
31 int load_message(message_summary *Msg, 
32                  StrBuf *FoundCharset,
33                  StrBuf **Error)
34 {
35         wcsession *WCC = WC;
36         StrBuf *Buf;
37         StrBuf *HdrToken;
38         headereval *Hdr;
39         void *vHdr;
40         char buf[SIZ];
41         int Done = 0;
42         int state=0;
43         
44         Buf = NewStrBuf();
45         lprintf(9, "MSG4 %ld|%s\n", Msg->msgnum, ChrPtr(Msg->PartNum));
46         if (Msg->PartNum != NULL) {
47                 serv_printf("MSG4 %ld|%s", Msg->msgnum, ChrPtr(Msg->PartNum));
48         }
49         else {
50                 serv_printf("MSG4 %ld", Msg->msgnum);
51         }
52
53         StrBuf_ServGetln(Buf);
54         if (GetServerStatus(Buf, NULL) != 1) {
55                 *Error = NewStrBuf();
56                 StrBufAppendPrintf(*Error, "<strong>");
57                 StrBufAppendPrintf(*Error, _("ERROR:"));
58                 StrBufAppendPrintf(*Error, "</strong> %s<br />\n", &buf[4]);
59                 FreeStrBuf(&Buf);
60                 return 0;
61         }
62
63         /* begin everythingamundo table */
64         HdrToken = NewStrBuf();
65         while ((StrBuf_ServGetln(Buf)>=0) && !Done) {
66                 if ( (StrLength(Buf)==3) && 
67                     !strcmp(ChrPtr(Buf), "000")) 
68                 {
69                         Done = 1;
70                         if (state < 2) {
71                                 lprintf(1, _("unexpected end of message"));
72                                 if (Msg->MsgBody->Data == NULL)
73                                         Msg->MsgBody->Data = NewStrBuf();
74                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
75                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
76                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("unexpected end of message"));
77                                 StrBufAppendPrintf(Msg->MsgBody->Data, " (1)</i><br /><br />\n");
78                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
79                         }
80                         break;
81                 }
82                 switch (state) {
83                 case 0:/* Citadel Message Headers */
84                         if (StrLength(Buf) == 0) {
85                                 state ++;
86                                 break;
87                         }
88                         StrBufExtract_token(HdrToken, Buf, 0, '=');
89                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
90                         
91 #ifdef TECH_PREVIEW
92                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
93 #endif
94                         /* look up one of the examine_* functions to parse the content */
95                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
96                             (vHdr != NULL)) {
97                                 Hdr = (headereval*)vHdr;
98                                 Hdr->evaluator(Msg, Buf, FoundCharset);
99                                 if (Hdr->Type == 1) {
100                                         state++;
101                                 }
102                         }/* TODO: 
103                         else LogError(Target, 
104                                       __FUNCTION__,  
105                                       "don't know how to handle message header[%s]\n", 
106                                       ChrPtr(HdrToken));
107                          */
108                         break;
109                 case 1:/* Message Mime Header */
110                         if (StrLength(Buf) == 0) {
111                                 state++;
112                                 if (Msg->MsgBody->ContentType == NULL)
113                                         /* end of header or no header? */
114                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
115                                  /* usual end of mime header */
116                         }
117                         else
118                         {
119                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
120                                 if (StrLength(HdrToken) > 0) {
121                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
122 #ifdef TECH_PREVIEW
123                                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
124 #endif
125                                         /* the examine*'s know how to do with mime headers too... */
126                                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
127                                             (vHdr != NULL)) {
128                                                 Hdr = (headereval*)vHdr;
129                                                 Hdr->evaluator(Msg, Buf, FoundCharset);
130                                         }
131                                         break;
132                                 }
133                         }
134                 case 2: /* Message Body */
135                         
136                         if (Msg->MsgBody->size_known > 0) {
137                                 StrBuf_ServGetBLOBBuffered(Msg->MsgBody->Data, Msg->MsgBody->length);
138                                 state ++;
139                                 /*/ todo: check next line, if not 000, append following lines */
140                         }
141                         else if (1){
142                                 if (StrLength(Msg->MsgBody->Data) > 0)
143                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
144                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
145                         }
146                         break;
147                 case 3:
148                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
149                         break;
150                 }
151         }
152
153         if (Msg->AllAttach == NULL)
154                 Msg->AllAttach = NewHash(1,NULL);
155         /* now we put the body mimepart we read above into the mimelist */
156         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
157         
158         /* Generate a reply-to address */
159         if (StrLength(Msg->Rfca) > 0) {
160                 if (Msg->reply_to == NULL)
161                         Msg->reply_to = NewStrBuf();
162                 if (StrLength(Msg->from) > 0) {
163                         StrBufPrintf(Msg->reply_to, "%s <%s>", ChrPtr(Msg->from), ChrPtr(Msg->Rfca));
164                 }
165                 else {
166                         FlushStrBuf(Msg->reply_to);
167                         StrBufAppendBuf(Msg->reply_to, Msg->Rfca, 0);
168                 }
169         }
170         else 
171         {
172                 if ((StrLength(Msg->OtherNode)>0) && 
173                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_nodename))) &&
174                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_humannode)) ))
175                 {
176                         if (Msg->reply_to == NULL)
177                                 Msg->reply_to = NewStrBuf();
178                         StrBufPrintf(Msg->reply_to, 
179                                      "%s @ %s",
180                                      ChrPtr(Msg->from), 
181                                      ChrPtr(Msg->OtherNode));
182                 }
183                 else {
184                         if (Msg->reply_to == NULL)
185                                 Msg->reply_to = NewStrBuf();
186                         FlushStrBuf(Msg->reply_to);
187                         StrBufAppendBuf(Msg->reply_to, Msg->from, 0);
188                 }
189         }
190         FreeStrBuf(&Buf);
191         FreeStrBuf(&HdrToken);
192         return 1;
193 }
194
195
196
197 /*
198  * I wanna SEE that message!
199  *
200  * msgnum               Message number to display
201  * printable_view       Nonzero to display a printable view
202  * section              Optional for encapsulated message/rfc822 submessage
203  */
204 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, const StrBuf *PartNum, const StrBuf **OutMime) 
205 {
206         StrBuf *Buf;
207         StrBuf *FoundCharset;
208         HashPos  *it;
209         void *vMime;
210         message_summary *Msg = NULL;
211         void *vHdr;
212         long len;
213         const char *Key;
214         WCTemplputParams SubTP;
215         StrBuf *Error = NULL;
216
217         Buf = NewStrBuf();
218         FoundCharset = NewStrBuf();
219         Msg = (message_summary *)malloc(sizeof(message_summary));
220         memset(Msg, 0, sizeof(message_summary));
221         Msg->msgnum = msgnum;
222         Msg->PartNum = PartNum;
223         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
224         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
225         Msg->MsgBody->msgnum = msgnum;
226
227         if (!load_message(Msg, FoundCharset, &Error)) {
228                 StrBufAppendBuf(Target, Error, 0);
229                 FreeStrBuf(&Error);
230         }
231
232         /* strip the bare contenttype, so we ommit charset etc. */
233         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
234         StrBufTrim(Buf);
235         StrBufLowerCase(Buf);
236         /* look up the renderer, that will convert this mimeitem into the htmlized form */
237         if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
238             (vHdr != NULL)) {
239                 RenderMimeFuncStruct *Render;
240                 Render = (RenderMimeFuncStruct*)vHdr;
241                 Render->f(Msg->MsgBody, NULL, FoundCharset);
242         }
243
244         if (StrLength(Msg->reply_references)> 0) {
245                 /* Trim down excessively long lists of thread references.  We eliminate the
246                  * second one in the list so that the thread root remains intact.
247                  */
248                 int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
249                 int rrlen = StrLength(Msg->reply_references);
250                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
251                         StrBufRemove_token(Msg->reply_references, 1, '|');
252                 }
253         }
254
255         /* now check if we need to translate some mimeparts, and remove the duplicate */
256         it = GetNewHashPos(Msg->AllAttach, 0);
257         while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
258                (vMime != NULL)) {
259                 wc_mime_attachment *Mime = (wc_mime_attachment*) vMime;
260                 evaluate_mime_part(Msg, Mime);
261         }
262         DeleteHashPos(&it);
263         memset(&SubTP, 0, sizeof(WCTemplputParams));
264         SubTP.Filter.ContextType = CTX_MAILSUM;
265         SubTP.Context = Msg;
266         *OutMime = DoTemplate(tmpl, tmpllen, Target, &SubTP);
267
268         DestroyMessageSummary(Msg);
269         FreeStrBuf(&FoundCharset);
270         FreeStrBuf(&Buf);
271         return 1;
272 }
273
274
275 void
276 HttpStatus(long CitadelStatus)
277 {
278         long httpstatus = 502;
279         
280         switch (MAJORCODE(CitadelStatus))
281         {
282         case LISTING_FOLLOWS:
283         case CIT_OK:
284                 httpstatus = 201;
285                 break;
286         case ERROR:
287                 switch (MINORCODE(CitadelStatus))
288                 {
289                 case INTERNAL_ERROR:
290                         httpstatus = 403;
291                         break;
292                         
293                 case TOO_BIG:
294                 case ILLEGAL_VALUE:
295                 case HIGHER_ACCESS_REQUIRED:
296                 case MAX_SESSIONS_EXCEEDED:
297                 case RESOURCE_BUSY:
298                 case RESOURCE_NOT_OPEN:
299                 case NOT_HERE:
300                 case INVALID_FLOOR_OPERATION:
301                 case FILE_NOT_FOUND:
302                 case ROOM_NOT_FOUND:
303                         httpstatus = 409;
304                         break;
305
306                 case MESSAGE_NOT_FOUND:
307                 case ALREADY_EXISTS:
308                         httpstatus = 403;
309                         break;
310
311                 case NO_SUCH_SYSTEM:
312                         httpstatus = 502;
313                         break;
314
315                 default:
316                 case CMD_NOT_SUPPORTED:
317                 case PASSWORD_REQUIRED:
318                 case ALREADY_LOGGED_IN:
319                 case USERNAME_REQUIRED:
320                 case NOT_LOGGED_IN:
321                 case SERVER_SHUTTING_DOWN:
322                 case NO_SUCH_USER:
323                 case ASYNC_GEXP:
324                         httpstatus = 502;
325                         break;
326                 }
327                 break;
328
329         default:
330         case BINARY_FOLLOWS:
331         case SEND_BINARY:
332         case START_CHAT_MODE:
333         case ASYNC_MSG:
334         case MORE_DATA:
335         case SEND_LISTING:
336                 httpstatus = 502; /* aeh... whut? */
337                 break;
338         }
339
340
341 }
342
343 /*
344  * Unadorned HTML output of an individual message, suitable
345  * for placing in a hidden iframe, for printing, or whatever
346  */
347 void handle_one_message(void) 
348 {
349         long CitStatus;
350         int CopyMessage = 0;
351         const StrBuf *Destination;
352         void *vLine;
353         const StrBuf *Mime;
354         long msgnum = 0L;
355         wcsession *WCC = WC;
356         const StrBuf *Tmpl;
357         StrBuf *CmdBuf = NULL;
358         const char *pMsg;
359
360
361         pMsg = strchr(ChrPtr(WCC->Hdr->HR.ReqLine), '/');
362         if (pMsg == NULL) {
363                 HttpStatus(CitStatus);
364                 return;
365         }
366
367         msgnum = atol(pMsg + 1);
368         StrBufCutAt(WCC->Hdr->HR.ReqLine, 0, pMsg);
369         gotoroom(WCC->Hdr->HR.ReqLine);
370         switch (WCC->Hdr->HR.eReqType)
371         {
372         case eGET:
373         case ePOST:
374                 Tmpl = sbstr("template");
375                 if (StrLength(Tmpl) > 0) 
376                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime);
377                 else 
378                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
379                 http_transmit_thing(ChrPtr(Mime), 0);
380                 break;
381         case eDELETE:
382                 CmdBuf = NewStrBuf ();
383                 if (WCC->wc_is_trash) { /* Delete from Trash is a real delete */
384                         serv_printf("DELE %ld", msgnum);        
385                 }
386                 else {                  /* Otherwise move it to Trash */
387                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
388                 }
389                 StrBuf_ServGetln(CmdBuf);
390                 FlushStrBuf(WCC->ImportantMsg);
391                 StrBufAppendBuf(WCC->ImportantMsg, CmdBuf, 4);
392                 GetServerStatus(CmdBuf, &CitStatus);
393                 HttpStatus(CitStatus);
394                 break;
395         case eCOPY:
396                 CopyMessage = 1;
397         case eMOVE:
398                 if (GetHash(WCC->Hdr->HTTPHeaders, HKEY("DESTINATION"), &vLine) &&
399                     (vLine!=NULL)) {
400                         Destination = (StrBuf*) vLine;
401                         serv_printf("MOVE %ld|%s|%d", msgnum, ChrPtr(Destination), CopyMessage);
402                         StrBuf_ServGetln(CmdBuf);
403                         FlushStrBuf(WCC->ImportantMsg);
404                         StrBufAppendBuf(WCC->ImportantMsg, CmdBuf, 4);
405                         GetServerStatus(CmdBuf, &CitStatus);
406                         HttpStatus(CitStatus);
407                 }
408                 else
409                         HttpStatus(500);
410                 break;
411         default:
412                 break;
413
414         }
415 }
416
417
418 /*
419  * Unadorned HTML output of an individual message, suitable
420  * for placing in a hidden iframe, for printing, or whatever
421  */
422 void embed_message(void) {
423         const StrBuf *Mime;
424         long msgnum = 0L;
425         wcsession *WCC = WC;
426         const StrBuf *Tmpl;
427         StrBuf *CmdBuf = NULL;
428
429         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
430         switch (WCC->Hdr->HR.eReqType)
431         {
432         case eGET:
433         case ePOST:
434                 Tmpl = sbstr("template");
435                 if (StrLength(Tmpl) > 0) 
436                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime);
437                 else 
438                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
439                 http_transmit_thing(ChrPtr(Mime), 0);
440                 break;
441         case eDELETE:
442                 CmdBuf = NewStrBuf ();
443                 if (WCC->wc_is_trash) { /* Delete from Trash is a real delete */
444                         serv_printf("DELE %ld", msgnum);        
445                 }
446                 else {                  /* Otherwise move it to Trash */
447                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
448                 }
449                 StrBuf_ServGetln(CmdBuf);
450                 FlushStrBuf(WCC->ImportantMsg);
451                 StrBufAppendBuf(WCC->ImportantMsg, CmdBuf, 4);
452                 break;
453         default:
454                 break;
455
456         }
457 }
458
459
460 /*
461  * Printable view of a message
462  */
463 void print_message(void) {
464         long msgnum = 0L;
465         const StrBuf *Mime;
466
467         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
468         output_headers(0, 0, 0, 0, 0, 0);
469
470         hprintf("Content-type: text/html\r\n"
471                 "Server: " PACKAGE_STRING "\r\n"
472                 "Connection: close\r\n");
473
474         begin_burst();
475
476         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, NULL, &Mime);
477
478         wDumpContent(0);
479 }
480
481 /* 
482  * Mobile browser view of message
483  */
484 void mobile_message_view(void) 
485 {
486         long msgnum = 0L;
487         const StrBuf *Mime;
488   
489         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
490         output_headers(1, 0, 0, 0, 0, 1);
491         begin_burst();
492         do_template("msgcontrols", NULL);
493         read_message(WC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
494         wDumpContent(0);
495 }
496
497 /*
498  * Display a message's headers
499  */
500 void display_headers(void) {
501         long msgnum = 0L;
502         char buf[1024];
503
504         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
505         output_headers(0, 0, 0, 0, 0, 0);
506
507         hprintf("Content-type: text/plain\r\n"
508                 "Server: %s\r\n"
509                 "Connection: close\r\n",
510                 PACKAGE_STRING);
511         begin_burst();
512
513         serv_printf("MSG2 %ld|3", msgnum);
514         serv_getln(buf, sizeof buf);
515         if (buf[0] == '1') {
516                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
517                         wprintf("%s\n", buf);
518                 }
519         }
520
521         wDumpContent(0);
522 }
523
524
525 message_summary *ReadOneMessageSummary(StrBuf *RawMessage, const char *DefaultSubject, long MsgNum) 
526 {
527         void                 *vEval;
528         MsgPartEvaluatorStruct  *Eval;
529         message_summary      *Msg;
530         StrBuf *Buf;
531         const char *buf;
532         const char *ebuf;
533         int nBuf;
534         long len;
535         
536         Buf = NewStrBuf();
537
538         serv_printf("MSG0 %ld|1", MsgNum);      /* ask for headers only */
539         
540         StrBuf_ServGetln(Buf);
541         if (GetServerStatus(Buf, NULL) == 1) {
542                 FreeStrBuf(&Buf);
543                 return NULL;
544         }
545
546         Msg = (message_summary*)malloc(sizeof(message_summary));
547         memset(Msg, 0, sizeof(message_summary));
548         while (len = StrBuf_ServGetln(Buf),
549                ((len != 3)  ||
550                 strcmp(ChrPtr(Buf), "000")== 0)){
551                 buf = ChrPtr(Buf);
552                 ebuf = strchr(ChrPtr(Buf), '=');
553                 nBuf = ebuf - buf;
554                 if (GetHash(MsgEvaluators, buf, nBuf, &vEval) && vEval != NULL) {
555                         Eval = (MsgPartEvaluatorStruct*) vEval;
556                         StrBufCutLeft(Buf, nBuf + 1);
557                         Eval->f(Msg, Buf);
558                 }
559                 else lprintf(1, "Don't know how to handle Message Headerline [%s]", ChrPtr(Buf));
560         }
561         return Msg;
562 }
563
564
565
566
567
568 /*
569  * load message pointers from the server for a "read messages" operation
570  *
571  * servcmd:             the citadel command to send to the citserver
572  * with_headers:        also include some of the headers with the message numbers (more expensive)
573  */
574 int load_msg_ptrs(const char *servcmd, int with_headers, long *lowest_found, long *highest_found)
575 {
576         StrBuf* FoundCharset = NULL;
577         wcsession *WCC = WC;
578         message_summary *Msg;
579         StrBuf *Buf, *Buf2;
580         int nummsgs = 0;
581         int maxload = 0;
582         long len;
583         int n;
584         int skipit;
585         const char *Ptr = NULL;
586
587         if (lowest_found) *lowest_found = LONG_MAX;
588         if (highest_found) *highest_found = LONG_MIN;
589
590         if (WCC->summ != NULL) {
591                 DeleteHash(&WCC->summ);
592         }
593         WCC->summ = NewHash(1, Flathash);
594         maxload = 10000;
595         
596         Buf = NewStrBuf();
597         serv_puts(servcmd);
598         StrBuf_ServGetln(Buf);
599         if (GetServerStatus(Buf, NULL) != 1) {
600                 FreeStrBuf(&Buf);
601                 return (nummsgs);
602         }
603         Buf2 = NewStrBuf();
604         while (len = StrBuf_ServGetln(Buf), ((len != 3) || strcmp(ChrPtr(Buf), "000")!= 0))
605         {
606                 if (nummsgs < maxload) {
607                         skipit = 0;
608                         Ptr = NULL;
609                         Msg = (message_summary*)malloc(sizeof(message_summary));
610                         memset(Msg, 0, sizeof(message_summary));
611
612                         Msg->msgnum = StrBufExtractNext_long(Buf, &Ptr, '|');
613                         Msg->date = StrBufExtractNext_long(Buf, &Ptr, '|');
614
615                         if (nummsgs == 0) {
616                                 if ((lowest_found) && (Msg->msgnum < *lowest_found)) {
617                                         *lowest_found = Msg->msgnum;
618                                 }
619                                 if ((highest_found) && (Msg->msgnum > *highest_found)) {
620                                         *highest_found = Msg->msgnum;
621                                 }
622                         }
623
624                         if ((Msg->msgnum == 0) && (StrLength(Buf) < 32)) {
625                                 free(Msg);
626                                 continue;
627                         }
628
629                         /* 
630                          * as citserver probably gives us messages in forward date sorting
631                          * nummsgs should be the same order as the message date.
632                          */
633                         if (Msg->date == 0) {
634                                 Msg->date = nummsgs;
635                                 if (StrLength(Buf) < 32) 
636                                         skipit = 1;
637                         }
638                         if (!skipit) {
639                                 Msg->from = NewStrBufPlain(NULL, StrLength(Buf));
640                                 StrBufExtract_NextToken(Buf2, Buf, &Ptr, '|');
641                                 if (StrLength(Buf2) != 0) {
642                                         /* Handle senders with RFC2047 encoding */
643                                         StrBuf_RFC822_to_Utf8(Msg->from, Buf2, WCC->DefaultCharset, FoundCharset);
644                                 }
645                         
646                                 /* node name */
647                                 StrBufExtract_NextToken(Buf2, Buf, &Ptr, '|');
648                                 if ((StrLength(Buf2) !=0 ) &&
649                                     ( ((WCC->room_flags & QR_NETWORK)
650                                        || ((strcasecmp(ChrPtr(Buf2), ChrPtr(WCC->serv_info->serv_nodename))
651                                             && (strcasecmp(ChrPtr(Buf2), ChrPtr(WCC->serv_info->serv_fqdn))))))))
652                                 {
653                                         StrBufAppendBufPlain(Msg->from, HKEY(" @ "), 0);
654                                         StrBufAppendBuf(Msg->from, Buf2, 0);
655                                 }
656
657                                 /* Internet address (not used)
658                                  *      StrBufExtract_token(Msg->inetaddr, Buf, 4, '|');
659                                  */
660                                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 1);
661                                 Msg->subj = NewStrBufPlain(NULL, StrLength(Buf));
662                                 StrBufExtract_NextToken(Buf2,  Buf, &Ptr, '|');
663                                 if (StrLength(Buf2) == 0)
664                                         StrBufAppendBufPlain(Msg->subj, _("(no subject)"), -1,0);
665                                 else {
666                                         StrBuf_RFC822_to_Utf8(Msg->subj, Buf2, WCC->DefaultCharset, FoundCharset);
667                                         if ((StrLength(Msg->subj) > 75) && 
668                                             (StrBuf_Utf8StrLen(Msg->subj) > 75)) {
669                                                 StrBuf_Utf8StrCut(Msg->subj, 72);
670                                                 StrBufAppendBufPlain(Msg->subj, HKEY("..."), 0);
671                                         }
672                                 }
673
674                                 if ((StrLength(Msg->from) > 25) && 
675                                     (StrBuf_Utf8StrLen(Msg->from) > 25)) {
676                                         StrBuf_Utf8StrCut(Msg->from, 23);
677                                         StrBufAppendBufPlain(Msg->from, HKEY("..."), 0);
678                                 }
679                         }
680                         n = Msg->msgnum;
681                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
682                 }
683                 nummsgs++;
684         }
685         FreeStrBuf(&Buf2);
686         FreeStrBuf(&Buf);
687         return (nummsgs);
688 }
689
690
691 inline message_summary* GetMessagePtrAt(int n, HashList *Summ)
692 {
693         const char *Key;
694         long HKLen;
695         void *vMsg;
696
697         if (Summ == NULL)
698                 return NULL;
699         GetHashAt(Summ, n, &HKLen, &Key, &vMsg);
700         return (message_summary*) vMsg;
701 }
702
703
704 long DrawMessageDropdown(StrBuf *Selector, long maxmsgs, long startmsg, int nMessages)
705 {
706         StrBuf *TmpBuf;
707         wcsession *WCC = WC;
708         void *vMsg;
709         int lo, hi;
710         long ret;
711         long hklen;
712         const char *key;
713         int done = 0;
714         int nItems;
715         HashPos *At;
716         long vector[16];
717         WCTemplputParams SubTP;
718
719         memset(&SubTP, 0, sizeof(WCTemplputParams));
720         SubTP.Filter.ContextType = CTX_LONGVECTOR;
721         SubTP.Context = &vector;
722         TmpBuf = NewStrBufPlain(NULL, SIZ);
723         At = GetNewHashPos(WCC->summ, nMessages);
724         nItems = GetCount(WCC->summ);
725         ret = nMessages;
726         vector[0] = 7;
727         vector[2] = 1;
728         vector[1] = startmsg;
729         vector[3] = 0;
730
731         while (!done) {
732                 vector[3] = abs(nMessages);
733                 lo = GetHashPosCounter(At);
734                 if (nMessages > 0) {
735                         if (lo + nMessages >= nItems) {
736                                 hi = nItems - 1;
737                                 vector[3] = nItems - lo;
738                                 if (startmsg == lo) 
739                                         ret = vector[3];
740                         }
741                         else {
742                                 hi = lo + nMessages - 1;
743                         }
744                 } else {
745                         if (lo + nMessages < -1) {
746                                 hi = 0;
747                         }
748                         else {
749                                 if ((lo % abs(nMessages)) != 0) {
750                                         int offset = (lo % abs(nMessages) *
751                                                       (nMessages / abs(nMessages)));
752                                         hi = lo + offset;
753                                         vector[3] = abs(offset);
754                                         if (startmsg == lo)
755                                                  ret = offset;
756                                 }
757                                 else
758                                         hi = lo + nMessages;
759                         }
760                 }
761                 done = !GetNextHashPos(WCC->summ, At, &hklen, &key, &vMsg);
762                 
763                 /*
764                  * Bump these because although we're thinking in zero base, the user
765                  * is a drooling idiot and is thinking in one base.
766                  */
767                 vector[4] = lo + 1;
768                 vector[5] = hi + 1;
769                 vector[6] = lo;
770                 FlushStrBuf(TmpBuf);
771                 dbg_print_longvector(vector);
772                 DoTemplate(HKEY("select_messageindex"), TmpBuf, &SubTP);
773                 StrBufAppendBuf(Selector, TmpBuf, 0);
774         }
775         vector[6] = 0;
776         FlushStrBuf(TmpBuf);
777         if (maxmsgs == 9999999) {
778                 vector[1] = 1;
779                 ret = maxmsgs;
780         }
781         else
782                 vector[1] = 0;          
783         vector[2] = 0;
784         dbg_print_longvector(vector);
785         DoTemplate(HKEY("select_messageindex_all"), TmpBuf, &SubTP);
786         StrBufAppendBuf(Selector, TmpBuf, 0);
787         FreeStrBuf(&TmpBuf);
788         DeleteHashPos(&At);
789         return ret;
790 }
791
792 void load_seen_flags(void)
793 {
794         message_summary *Msg;
795         const char *HashKey;
796         long HKLen;
797         HashPos *at;
798         void *vMsg;
799         StrBuf *OldMsg;
800         wcsession *WCC = WC;
801
802         OldMsg = NewStrBuf();
803         serv_puts("GTSN");
804         StrBuf_ServGetln(OldMsg);
805         if (GetServerStatus(OldMsg, NULL) == 2) {
806                 StrBufCutLeft(OldMsg, 4);
807         }
808         else {
809                 FreeStrBuf(&OldMsg);
810                 return;
811         }
812         at = GetNewHashPos(WCC->summ, 0);
813         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
814                 /* Are you a new message, or an old message? */
815                 Msg = (message_summary*) vMsg;
816                 if (is_msg_in_mset(ChrPtr(OldMsg), Msg->msgnum)) {
817                         Msg->is_new = 0;
818                 }
819                 else {
820                         Msg->is_new = 1;
821                 }
822         }
823         FreeStrBuf(&OldMsg);
824         DeleteHashPos(&at);
825 }
826
827 extern readloop_struct rlid[];
828
829 /*
830  * command loop for reading messages
831  *
832  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt"
833  */
834 void readloop(long oper)
835 {
836         StrBuf *MessageDropdown = NULL;
837         StrBuf *BBViewToolBar = NULL;
838         void *vMsg;
839         message_summary *Msg;
840         char cmd[256] = "";
841         char buf[SIZ];
842         int a = 0;
843         int with_headers = 0;
844         int nummsgs;
845         long startmsg = 0;
846         int maxmsgs = 0;
847         long *displayed_msgs = NULL;
848         int num_displayed = 0;
849         int is_singlecard = 0;
850         struct calview calv;
851         int i;
852         int lowest_displayed = (-1);
853         int highest_displayed = 0;
854         addrbookent *addrbook = NULL;
855         int num_ab = 0;
856         int bbs_reverse = 0;
857         wcsession *WCC = WC;
858         HashPos *at;
859         const char *HashKey;
860         long HKLen;
861         int care_for_empty_list = 0;
862         int load_seen = 0;
863         int sortit = 0;
864         int defaultsortorder = 0;
865         WCTemplputParams SubTP;
866         char *ab_name;
867         const StrBuf *Mime;
868         long lowest_found = (-1);
869         long highest_found = (-1);
870
871         if (havebstr("is_summary") && (1 == (ibstr("is_summary"))))
872                 WCC->wc_view = VIEW_MAILBOX;
873
874         if (!WCC->is_ajax) {
875                 output_headers(1, 1, 1, 0, 0, 0);
876         } else if (WCC->wc_view == VIEW_MAILBOX) {
877                 jsonMessageListHdr();
878         }
879
880         switch (WCC->wc_view) {
881         case VIEW_WIKI:
882                 sprintf(buf, "wiki?room=%s&page=home", ChrPtr(WCC->wc_roomname));
883                 http_redirect(buf);
884                 return;
885         case VIEW_CALBRIEF:
886         case VIEW_CALENDAR:
887                 load_seen = 1;
888                 strcpy(cmd, "MSGS ALL");
889                 maxmsgs = 32767;
890                 parse_calendar_view_request(&calv);
891                 break;
892         case VIEW_TASKS:
893                 strcpy(cmd, "MSGS ALL");
894                 maxmsgs = 32767;
895                 break;
896         case VIEW_NOTES:
897                 strcpy(cmd, "MSGS ALL");
898                 maxmsgs = 32767;
899                 wprintf("<div id=\"new_notes_here\"></div>\n");
900                 break;
901         case VIEW_ADDRESSBOOK:
902                 is_singlecard = ibstr("is_singlecard");
903                 if (is_singlecard != 1) {
904                         if (oper == do_search) {
905                                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
906                         }
907                         else {
908                                 strcpy(cmd, "MSGS ALL");
909                         }
910                         maxmsgs = 9999999;
911                         break;
912                 }
913                 break;
914         case VIEW_MAILBOX: 
915           if (!WCC->is_ajax) {
916             new_summary_view();
917             return;
918           } else {
919                 defaultsortorder = 2;
920                 sortit = 1;
921                 load_seen = 1;
922                 care_for_empty_list = 0;
923                 with_headers = 1;
924                 /* Generally using maxmsgs|startmsg is not required
925                    in mailbox view, but we have a 'safemode' for clients
926                    (*cough* Exploder) that simply can't handle too many */
927                 if (havebstr("maxmsgs")) maxmsgs = ibstr("maxmsgs");
928                 else maxmsgs = 9999999;
929                 if (havebstr("startmsg")) startmsg = lbstr("startmsg");
930                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
931                          (oper == do_search) ? "SEARCH" : "ALL",
932                          (oper == do_search) ? bstr("query") : ""
933                         );
934           }
935                 break;
936         case VIEW_BBS:
937         default:
938                 defaultsortorder = 1;
939                 startmsg = -1;
940                 sortit = 1;
941                 care_for_empty_list = 1;
942
943                 rlid[oper].cmd(cmd, sizeof(cmd));
944
945                 if (havebstr("maxmsgs"))
946                         maxmsgs = ibstr("maxmsgs");
947                 if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
948
949                 if (havebstr("startmsg")) {
950                         startmsg = lbstr("startmsg");
951                 }
952                 
953         }
954
955         nummsgs = load_msg_ptrs(cmd, with_headers, &lowest_found, &highest_found);
956         if (nummsgs == 0) {
957                 if (care_for_empty_list) {
958                         wprintf("<div class=\"nomsgs\"><br><em>");
959                         switch (oper) {
960                         case readnew:
961                                 wprintf(_("No new messages."));
962                                 break;
963                         case readold:
964                                 wprintf(_("No old messages."));
965                                 break;
966                         default:
967                                 wprintf(_("No messages here."));
968                         }
969                         wprintf("</em><br></div>\n");
970                         goto DONE;
971                 }
972
973         }
974
975         if (sortit) {
976                 CompareFunc SortIt;
977                 memset(&SubTP, 0, sizeof(WCTemplputParams));
978                 SubTP.Filter.ContextType = CTX_NONE;
979                 SubTP.Context = NULL;
980                 SortIt =  RetrieveSort(&SubTP, NULL, 0,
981                                        HKEY("date"), defaultsortorder);
982                 if (SortIt != NULL)
983                         SortByPayload(WCC->summ, SortIt);
984                 if (WCC->wc_view == VIEW_BBS) {
985                         if (lbstr("SortOrder") == 2) {
986                                 bbs_reverse = 1;
987                                 num_displayed = -DEFAULT_MAXMSGS;
988                         }
989                         else {
990                                 bbs_reverse = 0;
991                                 num_displayed = DEFAULT_MAXMSGS;
992                         }
993                 }
994         }
995         if (startmsg < 0) startmsg = (bbs_reverse) ? nummsgs - 1 : 0;
996
997         if (load_seen) load_seen_flags();
998         
999         /*
1000          * Print any inforation above the message list...
1001          */
1002         switch (WCC->wc_view) {
1003         case VIEW_BBS:
1004                 BBViewToolBar = NewStrBufPlain(NULL, SIZ);
1005                 MessageDropdown = NewStrBufPlain(NULL, SIZ);
1006
1007                 maxmsgs = DrawMessageDropdown(MessageDropdown, maxmsgs, startmsg, num_displayed);
1008                 if (num_displayed < 0) {
1009                         startmsg += maxmsgs;
1010                         if (num_displayed != maxmsgs)                           
1011                                 maxmsgs = abs(maxmsgs) + 1;
1012                         else
1013                                 maxmsgs = abs(maxmsgs);
1014
1015                 }
1016                 memset(&SubTP, 0, sizeof(WCTemplputParams));
1017                 SubTP.Filter.ContextType = CTX_STRBUF;
1018                 SubTP.Context = MessageDropdown;
1019                 DoTemplate(HKEY("msg_listselector_top"), BBViewToolBar, &SubTP);
1020                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
1021                 FlushStrBuf(BBViewToolBar);
1022                 break;
1023         }
1024         WCC->startmsg =  startmsg;
1025         WCC->maxmsgs = maxmsgs;
1026         WCC->num_displayed = 0;
1027
1028         /* Put some helpful data in vars for mailsummary_json */
1029         svputlong("READLOOP:TOTALMSGS", nummsgs);
1030         svputlong("READLOOP:STARTMSG", startmsg);
1031         svputlong("WCVIEW", WCC->wc_view);
1032
1033         /*
1034          * iterate over each message. if we need to load an attachment, do it here. 
1035          */
1036         if (WCC->wc_view == VIEW_MAILBOX) goto NO_MSG_LOOP;
1037         at = GetNewHashPos(WCC->summ, 0);
1038         num_displayed = i = 0;
1039         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
1040                 Msg = (message_summary*) vMsg;          
1041                 if ((Msg->msgnum >= startmsg) && (num_displayed <= maxmsgs)) {                  
1042                         switch (WCC->wc_view) {
1043                         case VIEW_WIKI:
1044                                 break;
1045                         case VIEW_CALBRIEF: /* load the mime attachments for special tasks... */
1046                         case VIEW_CALENDAR:
1047                                 load_calendar_item(Msg, Msg->is_new, &calv);
1048                                 break;
1049                         case VIEW_TASKS:
1050                                 display_task(Msg, Msg->is_new);
1051                                 break;
1052                         case VIEW_NOTES:
1053                                 display_note(Msg, Msg->is_new);
1054                                 break;
1055                         case VIEW_ADDRESSBOOK:
1056                                 ab_name = NULL;
1057                                 fetch_ab_name(Msg, &ab_name);
1058                                 if (ab_name == NULL) 
1059                                         break;
1060                                 ++num_ab;
1061                                 addrbook = realloc(addrbook,
1062                                                    (sizeof(addrbookent) * num_ab) );
1063                                 safestrncpy(addrbook[num_ab-1].ab_name, ab_name,
1064                                             sizeof(addrbook[num_ab-1].ab_name));
1065                                 addrbook[num_ab-1].ab_msgnum = Msg->msgnum;
1066                                 free(ab_name);
1067                                 break;
1068                         case VIEW_BBS: /* Tag the mails we want to show in bbview... */
1069                         default:
1070                                 if (displayed_msgs == NULL) {
1071                                         displayed_msgs = malloc(sizeof(long) *
1072                                                                 (maxmsgs<nummsgs ? maxmsgs + 1 : nummsgs + 1));
1073                                 }
1074                                 if ((i >= startmsg) && (i < startmsg + maxmsgs)) {
1075                                         displayed_msgs[num_displayed] = Msg->msgnum;
1076                                         if (lowest_displayed < 0) lowest_displayed = a;
1077                                         highest_displayed = a;
1078                         
1079                                         num_displayed++;
1080                                 }
1081                         }
1082                 } 
1083                 i++;
1084         }
1085         DeleteHashPos(&at);
1086
1087 NO_MSG_LOOP:
1088         /*
1089          * Done iterating the message list. now tasks we want to do after.
1090          */
1091         switch (WCC->wc_view) {
1092         case VIEW_MAILBOX:
1093           DoTemplate(HKEY("mailsummary_json"),NULL, &SubTP);
1094           break;
1095         case VIEW_BBS:
1096                 if (displayed_msgs != NULL) {
1097                         /* if we do a split bbview in the future, begin messages div here */
1098                         
1099                         for (a=0; a<num_displayed; ++a) {
1100                                 read_message(WCC->WBuf, HKEY("view_message"), displayed_msgs[a], NULL, &Mime);
1101                         }
1102                         
1103                         /* if we do a split bbview in the future, end messages div here */
1104                         
1105                         free(displayed_msgs);
1106                         displayed_msgs = NULL;
1107                 }
1108                 memset(&SubTP, 0, sizeof(WCTemplputParams));
1109                 SubTP.Filter.ContextType = CTX_STRBUF;
1110                 SubTP.Context = MessageDropdown;
1111                 DoTemplate(HKEY("msg_listselector_bottom"), BBViewToolBar, &SubTP);
1112                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
1113
1114                 FreeStrBuf(&BBViewToolBar);
1115                 FreeStrBuf(&MessageDropdown);
1116         }
1117
1118         
1119 DONE:
1120         switch (WCC->wc_view) {
1121         case VIEW_WIKI:
1122                 break;
1123         case VIEW_CALBRIEF:
1124         case VIEW_CALENDAR:
1125                 render_calendar_view(&calv);
1126                 break;
1127         case VIEW_TASKS:
1128                 do_tasks_view();        /* Render the task list */
1129                 break;
1130         case VIEW_NOTES:
1131                 break;
1132         case VIEW_ADDRESSBOOK:
1133                 if (is_singlecard)
1134                         read_message(WC->WBuf, HKEY("view_message"), lbstr("startmsg"), NULL, &Mime);
1135                 else
1136                         do_addrbook_view(addrbook, num_ab);     /* Render the address book */
1137                 break;
1138         case VIEW_MAILBOX: 
1139         case VIEW_BBS:
1140         default:
1141                 break;
1142         }
1143         /* Note: wDumpContent() will output one additional </div> tag. */
1144         if (WCC->wc_view != VIEW_MAILBOX) {
1145                 /* We ought to move this out into template */
1146                 wDumpContent(1);
1147         } else {
1148                 end_burst();
1149         }
1150         WCC->startmsg = 0;
1151         WCC->maxmsgs = 0;
1152         if (WCC->summ != NULL) {
1153                 DeleteHash(&WCC->summ);
1154         }
1155         if (addrbook != NULL) free(addrbook);
1156         FreeStrBuf(&BBViewToolBar);
1157 }
1158
1159
1160 /*
1161  * Back end for post_message()
1162  * ... this is where the actual message gets transmitted to the server.
1163  */
1164 void post_mime_to_server(void) {
1165         wcsession *WCC = WC;
1166         char top_boundary[SIZ];
1167         char alt_boundary[SIZ];
1168         int is_multipart = 0;
1169         static int seq = 0;
1170         wc_mime_attachment *att;
1171         char *encoded;
1172         size_t encoded_length;
1173         size_t encoded_strlen;
1174         char *txtmail = NULL;
1175
1176         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
1177                 ChrPtr(WCC->serv_info->serv_fqdn),
1178                 getpid(),
1179                 ++seq
1180         );
1181         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
1182                 ChrPtr(WCC->serv_info->serv_fqdn),
1183                 getpid(),
1184                 ++seq
1185         );
1186
1187         /* RFC2045 requires this, and some clients look for it... */
1188         serv_puts("MIME-Version: 1.0");
1189         serv_puts("X-Mailer: " PACKAGE_STRING);
1190
1191         /* If there are attachments, we have to do multipart/mixed */
1192         if (GetCount(WCC->attachments) > 0) {
1193                 is_multipart = 1;
1194         }
1195
1196         if (is_multipart) {
1197                 /* Remember, serv_printf() appends an extra newline */
1198                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
1199                 serv_printf("This is a multipart message in MIME format.\n");
1200                 serv_printf("--%s", top_boundary);
1201         }
1202
1203         /* Remember, serv_printf() appends an extra newline */
1204         serv_printf("Content-type: multipart/alternative; "
1205                 "boundary=\"%s\"\n", alt_boundary);
1206         serv_printf("This is a multipart message in MIME format.\n");
1207         serv_printf("--%s", alt_boundary);
1208
1209         serv_puts("Content-type: text/plain; charset=utf-8");
1210         serv_puts("Content-Transfer-Encoding: quoted-printable");
1211         serv_puts("");
1212         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
1213         text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
1214         free(txtmail);
1215
1216         serv_printf("--%s", alt_boundary);
1217
1218         serv_puts("Content-type: text/html; charset=utf-8");
1219         serv_puts("Content-Transfer-Encoding: quoted-printable");
1220         serv_puts("");
1221         serv_puts("<html><body>\r\n");
1222         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
1223         serv_puts("</body></html>\r\n");
1224
1225         serv_printf("--%s--", alt_boundary);
1226         
1227         if (is_multipart) {
1228                 long len;
1229                 const char *Key; 
1230                 void *vAtt;
1231                 HashPos  *it;
1232
1233                 /* Add in the attachments */
1234                 it = GetNewHashPos(WCC->attachments, 0);
1235                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
1236                         att = (wc_mime_attachment *)vAtt;
1237                         encoded_length = ((att->length * 150) / 100);
1238                         encoded = malloc(encoded_length);
1239                         if (encoded == NULL) break;
1240                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
1241
1242                         serv_printf("--%s", top_boundary);
1243                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
1244                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
1245                         serv_puts("Content-transfer-encoding: base64");
1246                         serv_puts("");
1247                         serv_write(encoded, encoded_strlen);
1248                         serv_puts("");
1249                         serv_puts("");
1250                         free(encoded);
1251                 }
1252                 serv_printf("--%s--", top_boundary);
1253                 DeleteHashPos(&it);
1254         }
1255
1256         serv_puts("000");
1257 }
1258
1259
1260 /*
1261  * Post message (or don't post message)
1262  *
1263  * Note regarding the "dont_post" variable:
1264  * A random value (actually, it's just a timestamp) is inserted as a hidden
1265  * field called "postseq" when the display_enter page is generated.  This
1266  * value is checked when posting, using the static variable dont_post.  If a
1267  * user attempts to post twice using the same dont_post value, the message is
1268  * discarded.  This prevents the accidental double-saving of the same message
1269  * if the user happens to click the browser "back" button.
1270  */
1271 void post_message(void)
1272 {
1273         char buf[1024];
1274         StrBuf *encoded_subject = NULL;
1275         static long dont_post = (-1L);
1276         wc_mime_attachment  *att;
1277         int is_anonymous = 0;
1278         const StrBuf *display_name = NULL;
1279         wcsession *WCC = WC;
1280         StrBuf *Buf;
1281         
1282         if (havebstr("force_room")) {
1283                 gotoroom(sbstr("force_room"));
1284         }
1285
1286         if (havebstr("display_name")) {
1287                 display_name = sbstr("display_name");
1288                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1289                         display_name = NULL;
1290                         is_anonymous = 1;
1291                 }
1292         }
1293
1294         if (WCC->upload_length > 0) {
1295                 const char *pch;
1296                 int n;
1297                 char N[64];
1298
1299                 /* There's an attachment.  Save it to this struct... */
1300                 lprintf(9, "Client is uploading %d bytes\n", WCC->upload_length);
1301                 att = malloc(sizeof(wc_mime_attachment));
1302                 memset(att, 0, sizeof(wc_mime_attachment ));
1303                 att->length = WCC->upload_length;
1304                 att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1305                 att->FileName = NewStrBufPlain(WCC->upload_filename, -1);
1306                 
1307                 if (WCC->attachments == NULL) {
1308                         WCC->attachments = NewHash(1, NULL);
1309                 }
1310
1311                 /* And add it to the list. */
1312                 n = snprintf(N, sizeof N, "%d", GetCount(WCC->attachments) + 1);
1313                 Put(WCC->attachments, N, n, att, DestroyMime);
1314
1315                 /*
1316                  * Mozilla sends a simple filename, which is what we want,
1317                  * but Satan's Browser sends an entire pathname.  Reduce
1318                  * the path to just a filename if we need to.
1319                  */
1320                 pch = strrchr(ChrPtr(att->FileName), '/');
1321                 if (pch != NULL) {
1322                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1323                 }
1324                 pch = strrchr(ChrPtr(att->FileName), '\\');
1325                 if (pch != NULL) {
1326                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1327                 }
1328
1329                 /*
1330                  * Transfer control of this memory from the upload struct
1331                  * to the attachment struct.
1332                  */
1333                 att->Data = WCC->upload;
1334                 WCC->upload = NULL;
1335                 WCC->upload_length = 0;
1336                 display_enter();
1337                 return;
1338         }
1339
1340         if (havebstr("cancel_button")) {
1341                 sprintf(WCC->ImportantMessage, 
1342                         _("Cancelled.  Message was not posted."));
1343         } else if (havebstr("attach_button")) {
1344                 display_enter();
1345                 return;
1346         } else if (lbstr("postseq") == dont_post) {
1347                 sprintf(WCC->ImportantMessage, 
1348                         _("Automatically cancelled because you have already "
1349                         "saved this message."));
1350         } else {
1351                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1352                 const StrBuf *Recp = NULL; 
1353                 const StrBuf *Cc = NULL;
1354                 const StrBuf *Bcc = NULL;
1355                 const StrBuf *Wikipage = NULL;
1356                 const StrBuf *my_email_addr = NULL;
1357                 StrBuf *CmdBuf = NULL;
1358                 StrBuf *references = NULL;
1359                 int save_to_drafts;
1360
1361                 save_to_drafts = havebstr("save_button");
1362                 Buf = NewStrBuf();
1363
1364                 if (save_to_drafts) {
1365                         /* temporarily change to the drafts room */
1366                         serv_puts("GOTO _DRAFTS_");
1367                         StrBuf_ServGetln(Buf);
1368                         if (GetServerStatus(Buf, NULL) != 2) {
1369                                 /* You probably don't even have a dumb Drafts folder */
1370                                 StrBufCutLeft(Buf, 4);
1371                                 lprintf(9, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1372                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Saved to Drafts failed: "), -1, 0);
1373                                 StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1374                                 display_enter();
1375                                 FreeStrBuf(&Buf);
1376                                 return;
1377                         }
1378                 }
1379
1380                 if (havebstr("references"))
1381                 {
1382                         const StrBuf *ref = sbstr("references");
1383                         references = NewStrBufDup(ref);
1384                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1385                                 StrBufCutLeft(references, 1);
1386                         }
1387                         StrBufReplaceChars(references, '|', '!');
1388                 }
1389                 if (havebstr("subject")) {
1390                         const StrBuf *Subj;
1391                         /*
1392                          * make enough room for the encoded string; 
1393                          * plus the QP header 
1394                          */
1395                         Subj = sbstr("subject");
1396                         
1397                         StrBufRFC2047encode(&encoded_subject, Subj);
1398                 }
1399                 Recp = sbstr("recp");
1400                 Cc = sbstr("cc");
1401                 Bcc = sbstr("bcc");
1402                 Wikipage = sbstr("wikipage");
1403                 my_email_addr = sbstr("my_email_addr");
1404                 
1405                 CmdBuf = NewStrBufPlain(NULL, 
1406                                         sizeof (CMD) + 
1407                                         StrLength(Recp) + 
1408                                         StrLength(encoded_subject) +
1409                                         StrLength(Cc) +
1410                                         StrLength(Bcc) + 
1411                                         StrLength(Wikipage) +
1412                                         StrLength(my_email_addr) + 
1413                                         StrLength(references));
1414
1415                 StrBufPrintf(CmdBuf, 
1416                              CMD,
1417                              save_to_drafts?"":ChrPtr(Recp),
1418                              is_anonymous,
1419                              ChrPtr(encoded_subject),
1420                              ChrPtr(display_name),
1421                              save_to_drafts?"":ChrPtr(Cc),
1422                              save_to_drafts?"":ChrPtr(Bcc),
1423                              ChrPtr(Wikipage),
1424                              ChrPtr(my_email_addr),
1425                              ChrPtr(references));
1426                 FreeStrBuf(&references);
1427                 FreeStrBuf(&encoded_subject);
1428
1429                 lprintf(9, "%s\n", ChrPtr(CmdBuf));
1430                 serv_puts(ChrPtr(CmdBuf));
1431                 FreeStrBuf(&CmdBuf);
1432
1433                 StrBuf_ServGetln(Buf);
1434                 if (GetServerStatus(Buf, NULL) == 4) {
1435                         if (save_to_drafts) {
1436                                 if (  (havebstr("recp"))
1437                                     || (havebstr("cc"  ))
1438                                     || (havebstr("bcc" )) ) {
1439                                         /* save recipient headers or room to post to */
1440                                         serv_printf("To: %s", ChrPtr(Recp));
1441                                         serv_printf("Cc: %s", ChrPtr(Cc));
1442                                         serv_printf("Bcc: %s", ChrPtr(Bcc));
1443                                 } else {
1444                                         serv_printf("X-Citadel-Room: %s", ChrPtr(WC->wc_roomname));
1445                                 }
1446                         }
1447                         post_mime_to_server();
1448                         if (save_to_drafts) {
1449                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been saved to Drafts.\n"), -1, 0);
1450                                 gotoroom(WCC->wc_roomname);
1451                                 display_enter();
1452                                 FreeStrBuf(&Buf);
1453                                 return;
1454                         } else if (  (havebstr("recp"))
1455                            || (havebstr("cc"  ))
1456                            || (havebstr("bcc" ))
1457                         ) {
1458                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been sent.\n"), -1, 0);
1459                         }
1460                         else {
1461                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been posted.\n"), -1, 0);
1462                         }
1463                         dont_post = lbstr("postseq");
1464                 } else {
1465                         StrBufCutLeft(Buf, 4);
1466
1467                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1468                         StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1469                         if (save_to_drafts) gotoroom(WCC->wc_roomname);
1470                         display_enter();
1471                         FreeStrBuf(&Buf);
1472                         return;
1473                 }
1474                 FreeStrBuf(&Buf);
1475         }
1476
1477         DeleteHash(&WCC->attachments);
1478
1479         /*
1480          *  We may have been supplied with instructions regarding the location
1481          *  to which we must return after posting.  If found, go there.
1482          */
1483         if (havebstr("return_to")) {
1484                 http_redirect(bstr("return_to"));
1485         }
1486         /*
1487          *  If we were editing a page in a wiki room, go to that page now.
1488          */
1489         else if (havebstr("wikipage")) {
1490                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
1491                 http_redirect(buf);
1492         }
1493         /*
1494          *  Otherwise, just go to the "read messages" loop.
1495          */
1496         else {
1497                 readloop(readnew);
1498         }
1499 }
1500
1501
1502
1503
1504 /*
1505  * display the message entry screen
1506  */
1507 void display_enter(void)
1508 {
1509         char buf[SIZ];
1510         long now;
1511         const StrBuf *display_name = NULL;
1512         int recipient_required = 0;
1513         int subject_required = 0;
1514         int recipient_bad = 0;
1515         int is_anonymous = 0;
1516         wcsession *WCC = WC;
1517
1518         now = time(NULL);
1519
1520         if (havebstr("force_room")) {
1521                 gotoroom(sbstr("force_room"));
1522         }
1523
1524         display_name = sbstr("display_name");
1525         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1526                 display_name = NULL;
1527                 is_anonymous = 1;
1528         }
1529
1530         /* First test to see whether this is a room that requires recipients to be entered */
1531         serv_puts("ENT0 0");
1532         serv_getln(buf, sizeof buf);
1533
1534         if (!strncmp(buf, "570", 3)) {          /* 570 means that we need a recipient here */
1535                 recipient_required = 1;
1536         }
1537         else if (buf[0] != '2') {               /* Any other error means that we cannot continue */
1538                 sprintf(WCC->ImportantMessage, "%s", &buf[4]);
1539                 readloop(readnew);
1540                 return;
1541         }
1542
1543         /* Is the server strongly recommending that the user enter a message subject? */
1544         if ((buf[3] != '\0') && (buf[4] != '\0')) {
1545                 subject_required = extract_int(&buf[4], 1);
1546         }
1547
1548         /*
1549          * Are we perhaps in an address book view?  If so, then an "enter
1550          * message" command really means "add new entry."
1551          */
1552         if (WCC->wc_default_view == VIEW_ADDRESSBOOK) {
1553                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->wc_roomname));
1554                 return;
1555         }
1556
1557         /*
1558          * Are we perhaps in a calendar room?  If so, then an "enter
1559          * message" command really means "add new calendar item."
1560          */
1561         if (WCC->wc_default_view == VIEW_CALENDAR) {
1562                 display_edit_event();
1563                 return;
1564         }
1565
1566         /*
1567          * Are we perhaps in a tasks view?  If so, then an "enter
1568          * message" command really means "add new task."
1569          */
1570         if (WCC->wc_default_view == VIEW_TASKS) {
1571                 display_edit_task();
1572                 return;
1573         }
1574
1575         /*
1576          * Otherwise proceed normally.
1577          * Do a custom room banner with no navbar...
1578          */
1579
1580         if (recipient_required) {
1581                 const StrBuf *Recp = NULL; 
1582                 const StrBuf *Cc = NULL;
1583                 const StrBuf *Bcc = NULL;
1584                 const StrBuf *Wikipage = NULL;
1585                 StrBuf *CmdBuf = NULL;
1586                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1587                 
1588                 Recp = sbstr("recp");
1589                 Cc = sbstr("cc");
1590                 Bcc = sbstr("bcc");
1591                 Wikipage = sbstr("wikipage");
1592                 
1593                 CmdBuf = NewStrBufPlain(NULL, 
1594                                         sizeof (CMD) + 
1595                                         StrLength(Recp) + 
1596                                         StrLength(display_name) +
1597                                         StrLength(Cc) +
1598                                         StrLength(Bcc) + 
1599                                         StrLength(Wikipage));
1600
1601                 StrBufPrintf(CmdBuf, 
1602                              CMD,
1603                              ChrPtr(Recp), 
1604                              is_anonymous,
1605                              ChrPtr(display_name),
1606                              ChrPtr(Cc), 
1607                              ChrPtr(Bcc), 
1608                              ChrPtr(Wikipage));
1609                 serv_puts(ChrPtr(CmdBuf));
1610                 serv_getln(buf, sizeof buf);
1611                 FreeStrBuf(&CmdBuf);
1612
1613                 if (!strncmp(buf, "570", 3)) {  /* 570 means we have an invalid recipient listed */
1614                         if (havebstr("recp") && 
1615                             havebstr("cc"  ) && 
1616                             havebstr("bcc" )) {
1617                                 recipient_bad = 1;
1618                         }
1619                 }
1620                 else if (buf[0] != '2') {       /* Any other error means that we cannot continue */
1621                         wprintf("<em>%s</em><br />\n", &buf[4]);        /* TODO -> important message */
1622                         return;
1623                 }
1624         }
1625         svputlong("RCPTREQUIRED", recipient_required);
1626         svputlong("SUBJREQUIRED", recipient_required || subject_required);
1627
1628         begin_burst();
1629         output_headers(1, 0, 0, 0, 1, 0);
1630         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1631         end_burst();
1632
1633         return;
1634 }
1635
1636 /*
1637  * delete a message
1638  */
1639 void delete_msg(void)
1640 {
1641         long msgid;
1642         char buf[SIZ];
1643
1644         msgid = lbstr("msgid");
1645
1646         if (WC->wc_is_trash) {  /* Delete from Trash is a real delete */
1647                 serv_printf("DELE %ld", msgid); 
1648         }
1649         else {                  /* Otherwise move it to Trash */
1650                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1651         }
1652
1653         serv_getln(buf, sizeof buf);
1654         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1655         readloop(readnew);
1656 }
1657
1658
1659 /*
1660  * move a message to another room
1661  */
1662 void move_msg(void)
1663 {
1664         long msgid;
1665         char buf[SIZ];
1666
1667         msgid = lbstr("msgid");
1668
1669         if (havebstr("move_button")) {
1670                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
1671                 serv_puts(buf);
1672                 serv_getln(buf, sizeof buf);
1673                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
1674         } else {
1675                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
1676         }
1677
1678         readloop(readnew);
1679 }
1680
1681
1682 /*
1683  * Confirm move of a message
1684  */
1685 void confirm_move_msg(void)
1686 {
1687         long msgid;
1688         char buf[SIZ];
1689         char targ[SIZ];
1690
1691         msgid = lbstr("msgid");
1692
1693
1694         output_headers(1, 1, 2, 0, 0, 0);
1695         wprintf("<div id=\"banner\">\n");
1696         wprintf("<h1>");
1697         wprintf(_("Confirm move of message"));
1698         wprintf("</h1>");
1699         wprintf("</div>\n");
1700
1701         wprintf("<div id=\"content\" class=\"service\">\n");
1702
1703         wprintf("<CENTER>");
1704
1705         wprintf(_("Move this message to:"));
1706         wprintf("<br />\n");
1707
1708         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
1709         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
1710         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
1711
1712         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
1713         serv_puts("LKRA");
1714         serv_getln(buf, sizeof buf);
1715         if (buf[0] == '1') {
1716                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1717                         extract_token(targ, buf, 0, '|', sizeof targ);
1718                         wprintf("<OPTION>");
1719                         escputs(targ);
1720                         wprintf("\n");
1721                 }
1722         }
1723         wprintf("</SELECT>\n");
1724         wprintf("<br />\n");
1725
1726         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
1727         wprintf("&nbsp;");
1728         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
1729         wprintf("</form></CENTER>\n");
1730
1731         wprintf("</CENTER>\n");
1732         wDumpContent(1);
1733 }
1734
1735
1736 /*
1737  * Generic function to output an arbitrary MIME attachment from
1738  * message being composed
1739  *
1740  * partnum              The MIME part to be output
1741  * filename             Fake filename to give
1742  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1743  */
1744 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1745 {
1746         void *vPart;
1747         StrBuf *content_type;
1748         wc_mime_attachment *part;
1749         
1750         if (GetHash(WC->attachments, SKEY(partnum), &vPart) &&
1751             (vPart != NULL)) {
1752                 part = (wc_mime_attachment*) vPart;
1753                 if (force_download) {
1754                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1755                 }
1756                 else {
1757                         content_type = NewStrBufDup(part->ContentType);
1758                 }
1759                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1760                 http_transmit_thing(ChrPtr(content_type), 0);
1761         } else {
1762                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1763                 output_headers(0, 0, 0, 0, 0, 0);
1764                 hprintf("Content-Type: text/plain\r\n");
1765                 wprintf(_("An error occurred while retrieving this part: %s/%s\n"), 
1766                         ChrPtr(partnum), ChrPtr(filename));
1767                 end_burst();
1768         }
1769         FreeStrBuf(&content_type);
1770 }
1771
1772
1773 /*
1774  * Generic function to output an arbitrary MIME part from an arbitrary
1775  * message number on the server.
1776  *
1777  * msgnum               Number of the item on the citadel server
1778  * partnum              The MIME part to be output
1779  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1780  */
1781 void mimepart(int force_download)
1782 {
1783         long msgnum;
1784         StrBuf *att;
1785         wcsession *WCC = WC;
1786         StrBuf *Buf;
1787         off_t bytes;
1788         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1789         const char *CT;
1790
1791         att = Buf = NewStrBuf();
1792         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1793         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1794
1795         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1796         StrBuf_ServGetln(Buf);
1797         if (GetServerStatus(Buf, NULL) == 2) {
1798                 StrBufCutLeft(Buf, 4);
1799                 bytes = StrBufExtract_long(Buf, 0, '|');
1800                 if (!force_download) {
1801                         StrBufExtract_token(ContentType, Buf, 3, '|');
1802                 }
1803
1804                 read_server_binary(WCC->WBuf, bytes, Buf);
1805                 serv_puts("CLOS");
1806                 StrBuf_ServGetln(Buf);
1807                 CT = ChrPtr(ContentType);
1808
1809                 if (!force_download) {
1810                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1811                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1812                                 CT = GuessMimeByFilename(SKEY(Buf));
1813                         }
1814                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1815                                 CT = GuessMimeType(SKEY(WCC->WBuf));
1816                         }
1817                 }
1818                 http_transmit_thing(CT, 0);
1819         } else {
1820                 StrBufCutLeft(Buf, 4);
1821                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1822                 output_headers(0, 0, 0, 0, 0, 0);
1823                 hprintf("Content-Type: text/plain\r\n");
1824                 wprintf(_("An error occurred while retrieving this part: %s\n"), 
1825                         ChrPtr(Buf));
1826                 end_burst();
1827         }
1828         FreeStrBuf(&ContentType);
1829         FreeStrBuf(&Buf);
1830 }
1831
1832
1833 /*
1834  * Read any MIME part of a message, from the server, into memory.
1835  */
1836 StrBuf *load_mimepart(long msgnum, char *partnum)
1837 {
1838         off_t bytes;
1839         StrBuf *Buf;
1840         
1841         Buf = NewStrBuf();
1842         serv_printf("DLAT %ld|%s", msgnum, partnum);
1843         StrBuf_ServGetln(Buf);
1844         if (GetServerStatus(Buf, NULL) == 6) {
1845                 StrBufCutLeft(Buf, 4);
1846                 bytes = StrBufExtract_long(Buf, 0, '|');
1847                 FreeStrBuf(&Buf);
1848                 Buf = NewStrBuf();
1849                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1850                 return(Buf);
1851         }
1852         else {
1853                 FreeStrBuf(&Buf);
1854                 return(NULL);
1855         }
1856 }
1857
1858 /*
1859  * Read any MIME part of a message, from the server, into memory.
1860  */
1861 void MimeLoadData(wc_mime_attachment *Mime)
1862 {
1863         StrBuf *Buf;
1864         off_t bytes;
1865         /* TODO: is there a chance the content type is different from the one we know? */
1866         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1867         Buf = NewStrBuf();
1868         StrBuf_ServGetln(Buf);
1869         if (GetServerStatus(Buf, NULL) == 6) {
1870                 bytes = extract_long(&(ChrPtr(Buf)[4]), 0);
1871                                      
1872                 if (Mime->Data == NULL)
1873                         Mime->Data = NewStrBufPlain(NULL, bytes);
1874                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1875         }
1876         else {
1877                 FlushStrBuf(Mime->Data);
1878                 /* TODO XImportant message */
1879         }
1880         FreeStrBuf(&Buf);
1881 }
1882
1883
1884
1885
1886 void view_mimepart(void) {
1887         mimepart(0);
1888 }
1889
1890 void download_mimepart(void) {
1891         mimepart(1);
1892 }
1893
1894 void view_postpart(void) {
1895         StrBuf *filename = NewStrBuf();
1896         StrBuf *partnum = NewStrBuf();
1897
1898         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1899         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1900
1901         postpart(partnum, filename, 0);
1902
1903         FreeStrBuf(&filename);
1904         FreeStrBuf(&partnum);
1905 }
1906
1907 void download_postpart(void) {
1908         StrBuf *filename = NewStrBuf();
1909         StrBuf *partnum = NewStrBuf();
1910
1911         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1912         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1913
1914         postpart(partnum, filename, 1);
1915
1916         FreeStrBuf(&filename);
1917         FreeStrBuf(&partnum);
1918 }
1919
1920 void h_readnew(void) { readloop(readnew);}
1921 void h_readold(void) { readloop(readold);}
1922 void h_readfwd(void) { readloop(readfwd);}
1923 void h_headers(void) { readloop(headers);}
1924 void h_do_search(void) { readloop(do_search);}
1925 void h_readgt(void) { readloop(readgt);}
1926
1927 void jsonMessageListHdr(void) 
1928 {
1929         /* TODO: make a generic function */
1930         hprintf("HTTP/1.1 200 OK\r\n");
1931         hprintf("Content-type: application/json; charset=utf-8\r\n");
1932         hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1933         hprintf("Connection: close\r\n");
1934         hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1935         begin_burst();
1936 }
1937
1938 /* Spit out the new summary view. This is basically a static page, so clients can cache the layout, all the dirty work is javascript :) */
1939 void new_summary_view(void) {
1940         begin_burst();
1941         DoTemplate(HKEY("msg_listview"),NULL,&NoCtx);
1942         DoTemplate(HKEY("trailing"),NULL,&NoCtx);
1943         end_burst();
1944 }
1945
1946 /* Output message list in JSON format */
1947 void jsonMessageList(void) {
1948         const StrBuf *room = sbstr("room");
1949         long oper = (havebstr("query")) ? do_search : readnew;
1950         WC->is_ajax = 1; 
1951         gotoroom(room);
1952         readloop(oper);
1953         WC->is_ajax = 0;
1954 }
1955
1956 void 
1957 InitModule_MSG
1958 (void)
1959 {
1960         RegisterPreference("use_sig",
1961                            _("Attach signature to email messages?"), 
1962                            PRF_YESNO, 
1963                            NULL);
1964         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1965         RegisterPreference("default_header_charset", 
1966                            _("Default character set for email headers:"), 
1967                            PRF_STRING, 
1968                            NULL);
1969         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1970         RegisterPreference("defaultname", 
1971                            _("Preferred display name for email messages"), 
1972                            PRF_STRING, 
1973                            NULL);
1974         RegisterPreference("defaulthandle", 
1975                            _("Preferred display name for bulletin board posts"), 
1976                            PRF_STRING, 
1977                            NULL);
1978         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1979
1980         WebcitAddUrlHandler(HKEY("readnew"), h_readnew, NEED_URL);
1981         WebcitAddUrlHandler(HKEY("readold"), h_readold, NEED_URL);
1982         WebcitAddUrlHandler(HKEY("readfwd"), h_readfwd, NEED_URL);
1983         WebcitAddUrlHandler(HKEY("headers"), h_headers, NEED_URL);
1984         WebcitAddUrlHandler(HKEY("readgt"), h_readgt, NEED_URL);
1985         WebcitAddUrlHandler(HKEY("do_search"), h_do_search, 0);
1986         WebcitAddUrlHandler(HKEY("display_enter"), display_enter, 0);
1987         WebcitAddUrlHandler(HKEY("post"), post_message, 0);
1988         WebcitAddUrlHandler(HKEY("move_msg"), move_msg, 0);
1989         WebcitAddUrlHandler(HKEY("delete_msg"), delete_msg, 0);
1990         WebcitAddUrlHandler(HKEY("confirm_move_msg"), confirm_move_msg, 0);
1991         WebcitAddUrlHandler(HKEY("msg"), embed_message, NEED_URL);
1992         WebcitAddUrlHandler(HKEY("message"), handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1993         WebcitAddUrlHandler(HKEY("printmsg"), print_message, NEED_URL);
1994         WebcitAddUrlHandler(HKEY("mobilemsg"), mobile_message_view, NEED_URL);
1995         WebcitAddUrlHandler(HKEY("msgheaders"), display_headers, NEED_URL);
1996
1997         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1998         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1999         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
2000         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
2001
2002         /* json */
2003         WebcitAddUrlHandler(HKEY("roommsgs"), jsonMessageList,0);
2004         return ;
2005 }
2006
2007 void
2008 SessionDetachModule_MSG
2009 (wcsession *sess)
2010 {
2011         DeleteHash(&sess->summ);
2012 }