* Eliminated the 'gotonext' problem with the bbs view drop-down selector by changing...
[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 /* startmsg is an index within the message list.
705  * starting_from is the Citadel message number to be supplied to a "MSGS GT" operation
706  */
707 long DrawMessageDropdown(StrBuf *Selector, long maxmsgs, long startmsg, int nMessages, long starting_from)
708 {
709         StrBuf *TmpBuf;
710         wcsession *WCC = WC;
711         void *vMsg;
712         int lo, hi;
713         long ret;
714         long hklen;
715         const char *key;
716         int done = 0;
717         int nItems;
718         HashPos *At;
719         long vector[16];
720         WCTemplputParams SubTP;
721
722         memset(&SubTP, 0, sizeof(WCTemplputParams));
723         SubTP.Filter.ContextType = CTX_LONGVECTOR;
724         SubTP.Context = &vector;
725         TmpBuf = NewStrBufPlain(NULL, SIZ);
726         At = GetNewHashPos(WCC->summ, nMessages);
727         nItems = GetCount(WCC->summ);
728         ret = nMessages;
729         vector[0] = 7;
730         vector[2] = 1;
731         vector[1] = startmsg;
732         vector[3] = 0;
733         vector[7] = starting_from;
734
735         while (!done) {
736                 vector[3] = abs(nMessages);
737                 lo = GetHashPosCounter(At);
738                 if (nMessages > 0) {
739                         if (lo + nMessages >= nItems) {
740                                 hi = nItems - 1;
741                                 vector[3] = nItems - lo;
742                                 if (startmsg == lo) 
743                                         ret = vector[3];
744                         }
745                         else {
746                                 hi = lo + nMessages - 1;
747                         }
748                 } else {
749                         if (lo + nMessages < -1) {
750                                 hi = 0;
751                         }
752                         else {
753                                 if ((lo % abs(nMessages)) != 0) {
754                                         int offset = (lo % abs(nMessages) *
755                                                       (nMessages / abs(nMessages)));
756                                         hi = lo + offset;
757                                         vector[3] = abs(offset);
758                                         if (startmsg == lo)
759                                                  ret = offset;
760                                 }
761                                 else
762                                         hi = lo + nMessages;
763                         }
764                 }
765                 done = !GetNextHashPos(WCC->summ, At, &hklen, &key, &vMsg);
766                 
767                 /*
768                  * Bump these because although we're thinking in zero base, the user
769                  * is a drooling idiot and is thinking in one base.
770                  */
771                 vector[4] = lo + 1;
772                 vector[5] = hi + 1;
773                 vector[6] = lo;
774                 FlushStrBuf(TmpBuf);
775                 dbg_print_longvector(vector);
776                 DoTemplate(HKEY("select_messageindex"), TmpBuf, &SubTP);
777                 StrBufAppendBuf(Selector, TmpBuf, 0);
778         }
779         vector[6] = 0;
780         FlushStrBuf(TmpBuf);
781         if (maxmsgs == 9999999) {
782                 vector[1] = 1;
783                 ret = maxmsgs;
784         }
785         else
786                 vector[1] = 0;          
787         vector[2] = 0;
788         dbg_print_longvector(vector);
789         DoTemplate(HKEY("select_messageindex_all"), TmpBuf, &SubTP);
790         StrBufAppendBuf(Selector, TmpBuf, 0);
791         FreeStrBuf(&TmpBuf);
792         DeleteHashPos(&At);
793         return ret;
794 }
795
796 void load_seen_flags(void)
797 {
798         message_summary *Msg;
799         const char *HashKey;
800         long HKLen;
801         HashPos *at;
802         void *vMsg;
803         StrBuf *OldMsg;
804         wcsession *WCC = WC;
805
806         OldMsg = NewStrBuf();
807         serv_puts("GTSN");
808         StrBuf_ServGetln(OldMsg);
809         if (GetServerStatus(OldMsg, NULL) == 2) {
810                 StrBufCutLeft(OldMsg, 4);
811         }
812         else {
813                 FreeStrBuf(&OldMsg);
814                 return;
815         }
816         at = GetNewHashPos(WCC->summ, 0);
817         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
818                 /* Are you a new message, or an old message? */
819                 Msg = (message_summary*) vMsg;
820                 if (is_msg_in_mset(ChrPtr(OldMsg), Msg->msgnum)) {
821                         Msg->is_new = 0;
822                 }
823                 else {
824                         Msg->is_new = 1;
825                 }
826         }
827         FreeStrBuf(&OldMsg);
828         DeleteHashPos(&at);
829 }
830
831 extern readloop_struct rlid[];
832
833 /*
834  * command loop for reading messages
835  *
836  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt"
837  */
838 void readloop(long oper)
839 {
840         StrBuf *MessageDropdown = NULL;
841         StrBuf *BBViewToolBar = NULL;
842         void *vMsg;
843         message_summary *Msg;
844         char cmd[256] = "";
845         char buf[SIZ];
846         int a = 0;
847         int with_headers = 0;
848         int nummsgs;
849         long startmsg = 0;
850         int maxmsgs = 0;
851         long *displayed_msgs = NULL;
852         int num_displayed = 0;
853         int is_singlecard = 0;
854         struct calview calv;
855         int i;
856         int lowest_displayed = (-1);
857         int highest_displayed = 0;
858         addrbookent *addrbook = NULL;
859         int num_ab = 0;
860         int bbs_reverse = 0;
861         wcsession *WCC = WC;
862         HashPos *at;
863         const char *HashKey;
864         long HKLen;
865         int care_for_empty_list = 0;
866         int load_seen = 0;
867         int sortit = 0;
868         int defaultsortorder = 0;
869         WCTemplputParams SubTP;
870         char *ab_name;
871         const StrBuf *Mime;
872         long lowest_found = (-1);
873         long highest_found = (-1);
874
875         if (havebstr("is_summary") && (1 == (ibstr("is_summary"))))
876                 WCC->wc_view = VIEW_MAILBOX;
877
878         if (!WCC->is_ajax) {
879                 output_headers(1, 1, 1, 0, 0, 0);
880         } else if (WCC->wc_view == VIEW_MAILBOX) {
881                 jsonMessageListHdr();
882         }
883
884         switch (WCC->wc_view) {
885         case VIEW_WIKI:
886                 sprintf(buf, "wiki?room=%s&page=home", ChrPtr(WCC->wc_roomname));
887                 http_redirect(buf);
888                 return;
889         case VIEW_CALBRIEF:
890         case VIEW_CALENDAR:
891                 load_seen = 1;
892                 strcpy(cmd, "MSGS ALL");
893                 maxmsgs = 32767;
894                 parse_calendar_view_request(&calv);
895                 break;
896         case VIEW_TASKS:
897                 strcpy(cmd, "MSGS ALL");
898                 maxmsgs = 32767;
899                 break;
900         case VIEW_NOTES:
901                 strcpy(cmd, "MSGS ALL");
902                 maxmsgs = 32767;
903                 wprintf("<div id=\"new_notes_here\"></div>\n");
904                 break;
905         case VIEW_ADDRESSBOOK:
906                 is_singlecard = ibstr("is_singlecard");
907                 if (is_singlecard != 1) {
908                         if (oper == do_search) {
909                                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
910                         }
911                         else {
912                                 strcpy(cmd, "MSGS ALL");
913                         }
914                         maxmsgs = 9999999;
915                         break;
916                 }
917                 break;
918         case VIEW_MAILBOX: 
919           if (!WCC->is_ajax) {
920             new_summary_view();
921             return;
922           } else {
923                 defaultsortorder = 2;
924                 sortit = 1;
925                 load_seen = 1;
926                 care_for_empty_list = 0;
927                 with_headers = 1;
928                 /* Generally using maxmsgs|startmsg is not required
929                    in mailbox view, but we have a 'safemode' for clients
930                    (*cough* Exploder) that simply can't handle too many */
931                 if (havebstr("maxmsgs")) maxmsgs = ibstr("maxmsgs");
932                 else maxmsgs = 9999999;
933                 if (havebstr("startmsg")) startmsg = lbstr("startmsg");
934                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
935                          (oper == do_search) ? "SEARCH" : "ALL",
936                          (oper == do_search) ? bstr("query") : ""
937                         );
938           }
939                 break;
940         case VIEW_BBS:
941         default:
942                 defaultsortorder = 1;
943                 startmsg = -1;
944                 sortit = 1;
945                 care_for_empty_list = 1;
946
947                 rlid[oper].cmd(cmd, sizeof(cmd));
948
949                 if (havebstr("maxmsgs"))
950                         maxmsgs = ibstr("maxmsgs");
951                 if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
952
953                 if (havebstr("startmsg")) {
954                         startmsg = lbstr("startmsg");
955                 }
956                 
957         }
958
959         nummsgs = load_msg_ptrs(cmd, with_headers, &lowest_found, &highest_found);
960         if (nummsgs == 0) {
961                 if (care_for_empty_list) {
962                         wprintf("<div class=\"nomsgs\"><br><em>");
963                         switch (oper) {
964                         case readnew:
965                                 wprintf(_("No new messages."));
966                                 break;
967                         case readold:
968                                 wprintf(_("No old messages."));
969                                 break;
970                         default:
971                                 wprintf(_("No messages here."));
972                         }
973                         wprintf("</em><br></div>\n");
974                         goto DONE;
975                 }
976
977         }
978
979         if (sortit) {
980                 CompareFunc SortIt;
981                 memset(&SubTP, 0, sizeof(WCTemplputParams));
982                 SubTP.Filter.ContextType = CTX_NONE;
983                 SubTP.Context = NULL;
984                 SortIt =  RetrieveSort(&SubTP, NULL, 0,
985                                        HKEY("date"), defaultsortorder);
986                 if (SortIt != NULL)
987                         SortByPayload(WCC->summ, SortIt);
988                 if (WCC->wc_view == VIEW_BBS) {
989                         if (lbstr("SortOrder") == 2) {
990                                 bbs_reverse = 1;
991                                 num_displayed = -DEFAULT_MAXMSGS;
992                         }
993                         else {
994                                 bbs_reverse = 0;
995                                 num_displayed = DEFAULT_MAXMSGS;
996                         }
997                 }
998         }
999         if (startmsg < 0) startmsg = (bbs_reverse) ? nummsgs - 1 : 0;
1000
1001         if (load_seen) load_seen_flags();
1002         
1003         /*
1004          * Print any inforation above the message list...
1005          */
1006         switch (WCC->wc_view) {
1007         case VIEW_BBS:
1008                 BBViewToolBar = NewStrBufPlain(NULL, SIZ);
1009                 MessageDropdown = NewStrBufPlain(NULL, SIZ);
1010
1011                 maxmsgs = DrawMessageDropdown(MessageDropdown, maxmsgs, startmsg,
1012                                                 num_displayed, lowest_found-1);
1013                 if (num_displayed < 0) {
1014                         startmsg += maxmsgs;
1015                         if (num_displayed != maxmsgs)                           
1016                                 maxmsgs = abs(maxmsgs) + 1;
1017                         else
1018                                 maxmsgs = abs(maxmsgs);
1019
1020                 }
1021                 memset(&SubTP, 0, sizeof(WCTemplputParams));
1022                 SubTP.Filter.ContextType = CTX_STRBUF;
1023                 SubTP.Context = MessageDropdown;
1024                 DoTemplate(HKEY("msg_listselector_top"), BBViewToolBar, &SubTP);
1025                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
1026                 FlushStrBuf(BBViewToolBar);
1027                 break;
1028         }
1029         WCC->startmsg =  startmsg;
1030         WCC->maxmsgs = maxmsgs;
1031         WCC->num_displayed = 0;
1032
1033         /* Put some helpful data in vars for mailsummary_json */
1034         svputlong("READLOOP:TOTALMSGS", nummsgs);
1035         svputlong("READLOOP:STARTMSG", startmsg);
1036         svputlong("WCVIEW", WCC->wc_view);
1037
1038         /*
1039          * iterate over each message. if we need to load an attachment, do it here. 
1040          */
1041         if (WCC->wc_view == VIEW_MAILBOX) goto NO_MSG_LOOP;
1042         at = GetNewHashPos(WCC->summ, 0);
1043         num_displayed = i = 0;
1044         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
1045                 Msg = (message_summary*) vMsg;          
1046                 if ((Msg->msgnum >= startmsg) && (num_displayed <= maxmsgs)) {                  
1047                         switch (WCC->wc_view) {
1048                         case VIEW_WIKI:
1049                                 break;
1050                         case VIEW_CALBRIEF: /* load the mime attachments for special tasks... */
1051                         case VIEW_CALENDAR:
1052                                 load_calendar_item(Msg, Msg->is_new, &calv);
1053                                 break;
1054                         case VIEW_TASKS:
1055                                 display_task(Msg, Msg->is_new);
1056                                 break;
1057                         case VIEW_NOTES:
1058                                 display_note(Msg, Msg->is_new);
1059                                 break;
1060                         case VIEW_ADDRESSBOOK:
1061                                 ab_name = NULL;
1062                                 fetch_ab_name(Msg, &ab_name);
1063                                 if (ab_name == NULL) 
1064                                         break;
1065                                 ++num_ab;
1066                                 addrbook = realloc(addrbook,
1067                                                    (sizeof(addrbookent) * num_ab) );
1068                                 safestrncpy(addrbook[num_ab-1].ab_name, ab_name,
1069                                             sizeof(addrbook[num_ab-1].ab_name));
1070                                 addrbook[num_ab-1].ab_msgnum = Msg->msgnum;
1071                                 free(ab_name);
1072                                 break;
1073                         case VIEW_BBS: /* Tag the mails we want to show in bbview... */
1074                         default:
1075                                 if (displayed_msgs == NULL) {
1076                                         displayed_msgs = malloc(sizeof(long) *
1077                                                                 (maxmsgs<nummsgs ? maxmsgs + 1 : nummsgs + 1));
1078                                 }
1079                                 if ((i >= startmsg) && (i < startmsg + maxmsgs)) {
1080                                         displayed_msgs[num_displayed] = Msg->msgnum;
1081                                         if (lowest_displayed < 0) lowest_displayed = a;
1082                                         highest_displayed = a;
1083                         
1084                                         num_displayed++;
1085                                 }
1086                         }
1087                 } 
1088                 i++;
1089         }
1090         DeleteHashPos(&at);
1091
1092 NO_MSG_LOOP:
1093         /*
1094          * Done iterating the message list. now tasks we want to do after.
1095          */
1096         switch (WCC->wc_view) {
1097         case VIEW_MAILBOX:
1098           DoTemplate(HKEY("mailsummary_json"),NULL, &SubTP);
1099           break;
1100         case VIEW_BBS:
1101                 if (displayed_msgs != NULL) {
1102                         /* if we do a split bbview in the future, begin messages div here */
1103                         
1104                         for (a=0; a<num_displayed; ++a) {
1105                                 read_message(WCC->WBuf, HKEY("view_message"), displayed_msgs[a], NULL, &Mime);
1106                         }
1107                         
1108                         /* if we do a split bbview in the future, end messages div here */
1109                         
1110                         free(displayed_msgs);
1111                         displayed_msgs = NULL;
1112                 }
1113                 memset(&SubTP, 0, sizeof(WCTemplputParams));
1114                 SubTP.Filter.ContextType = CTX_STRBUF;
1115                 SubTP.Context = MessageDropdown;
1116                 DoTemplate(HKEY("msg_listselector_bottom"), BBViewToolBar, &SubTP);
1117                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
1118
1119                 FreeStrBuf(&BBViewToolBar);
1120                 FreeStrBuf(&MessageDropdown);
1121         }
1122
1123         
1124 DONE:
1125         switch (WCC->wc_view) {
1126         case VIEW_WIKI:
1127                 break;
1128         case VIEW_CALBRIEF:
1129         case VIEW_CALENDAR:
1130                 render_calendar_view(&calv);
1131                 break;
1132         case VIEW_TASKS:
1133                 do_tasks_view();        /* Render the task list */
1134                 break;
1135         case VIEW_NOTES:
1136                 break;
1137         case VIEW_ADDRESSBOOK:
1138                 if (is_singlecard)
1139                         read_message(WC->WBuf, HKEY("view_message"), lbstr("startmsg"), NULL, &Mime);
1140                 else
1141                         do_addrbook_view(addrbook, num_ab);     /* Render the address book */
1142                 break;
1143         case VIEW_MAILBOX: 
1144         case VIEW_BBS:
1145         default:
1146                 break;
1147         }
1148         /* Note: wDumpContent() will output one additional </div> tag. */
1149         if (WCC->wc_view != VIEW_MAILBOX) {
1150                 /* We ought to move this out into template */
1151                 wDumpContent(1);
1152         } else {
1153                 end_burst();
1154         }
1155         WCC->startmsg = 0;
1156         WCC->maxmsgs = 0;
1157         if (WCC->summ != NULL) {
1158                 DeleteHash(&WCC->summ);
1159         }
1160         if (addrbook != NULL) free(addrbook);
1161         FreeStrBuf(&BBViewToolBar);
1162 }
1163
1164
1165 /*
1166  * Back end for post_message()
1167  * ... this is where the actual message gets transmitted to the server.
1168  */
1169 void post_mime_to_server(void) {
1170         wcsession *WCC = WC;
1171         char top_boundary[SIZ];
1172         char alt_boundary[SIZ];
1173         int is_multipart = 0;
1174         static int seq = 0;
1175         wc_mime_attachment *att;
1176         char *encoded;
1177         size_t encoded_length;
1178         size_t encoded_strlen;
1179         char *txtmail = NULL;
1180
1181         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
1182                 ChrPtr(WCC->serv_info->serv_fqdn),
1183                 getpid(),
1184                 ++seq
1185         );
1186         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
1187                 ChrPtr(WCC->serv_info->serv_fqdn),
1188                 getpid(),
1189                 ++seq
1190         );
1191
1192         /* RFC2045 requires this, and some clients look for it... */
1193         serv_puts("MIME-Version: 1.0");
1194         serv_puts("X-Mailer: " PACKAGE_STRING);
1195
1196         /* If there are attachments, we have to do multipart/mixed */
1197         if (GetCount(WCC->attachments) > 0) {
1198                 is_multipart = 1;
1199         }
1200
1201         if (is_multipart) {
1202                 /* Remember, serv_printf() appends an extra newline */
1203                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
1204                 serv_printf("This is a multipart message in MIME format.\n");
1205                 serv_printf("--%s", top_boundary);
1206         }
1207
1208         /* Remember, serv_printf() appends an extra newline */
1209         serv_printf("Content-type: multipart/alternative; "
1210                 "boundary=\"%s\"\n", alt_boundary);
1211         serv_printf("This is a multipart message in MIME format.\n");
1212         serv_printf("--%s", alt_boundary);
1213
1214         serv_puts("Content-type: text/plain; charset=utf-8");
1215         serv_puts("Content-Transfer-Encoding: quoted-printable");
1216         serv_puts("");
1217         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
1218         text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
1219         free(txtmail);
1220
1221         serv_printf("--%s", alt_boundary);
1222
1223         serv_puts("Content-type: text/html; charset=utf-8");
1224         serv_puts("Content-Transfer-Encoding: quoted-printable");
1225         serv_puts("");
1226         serv_puts("<html><body>\r\n");
1227         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
1228         serv_puts("</body></html>\r\n");
1229
1230         serv_printf("--%s--", alt_boundary);
1231         
1232         if (is_multipart) {
1233                 long len;
1234                 const char *Key; 
1235                 void *vAtt;
1236                 HashPos  *it;
1237
1238                 /* Add in the attachments */
1239                 it = GetNewHashPos(WCC->attachments, 0);
1240                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
1241                         att = (wc_mime_attachment *)vAtt;
1242                         encoded_length = ((att->length * 150) / 100);
1243                         encoded = malloc(encoded_length);
1244                         if (encoded == NULL) break;
1245                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
1246
1247                         serv_printf("--%s", top_boundary);
1248                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
1249                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
1250                         serv_puts("Content-transfer-encoding: base64");
1251                         serv_puts("");
1252                         serv_write(encoded, encoded_strlen);
1253                         serv_puts("");
1254                         serv_puts("");
1255                         free(encoded);
1256                 }
1257                 serv_printf("--%s--", top_boundary);
1258                 DeleteHashPos(&it);
1259         }
1260
1261         serv_puts("000");
1262 }
1263
1264
1265 /*
1266  * Post message (or don't post message)
1267  *
1268  * Note regarding the "dont_post" variable:
1269  * A random value (actually, it's just a timestamp) is inserted as a hidden
1270  * field called "postseq" when the display_enter page is generated.  This
1271  * value is checked when posting, using the static variable dont_post.  If a
1272  * user attempts to post twice using the same dont_post value, the message is
1273  * discarded.  This prevents the accidental double-saving of the same message
1274  * if the user happens to click the browser "back" button.
1275  */
1276 void post_message(void)
1277 {
1278         char buf[1024];
1279         StrBuf *encoded_subject = NULL;
1280         static long dont_post = (-1L);
1281         wc_mime_attachment  *att;
1282         int is_anonymous = 0;
1283         const StrBuf *display_name = NULL;
1284         wcsession *WCC = WC;
1285         StrBuf *Buf;
1286         
1287         if (havebstr("force_room")) {
1288                 gotoroom(sbstr("force_room"));
1289         }
1290
1291         if (havebstr("display_name")) {
1292                 display_name = sbstr("display_name");
1293                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1294                         display_name = NULL;
1295                         is_anonymous = 1;
1296                 }
1297         }
1298
1299         if (WCC->upload_length > 0) {
1300                 const char *pch;
1301                 int n;
1302                 char N[64];
1303
1304                 /* There's an attachment.  Save it to this struct... */
1305                 lprintf(9, "Client is uploading %d bytes\n", WCC->upload_length);
1306                 att = malloc(sizeof(wc_mime_attachment));
1307                 memset(att, 0, sizeof(wc_mime_attachment ));
1308                 att->length = WCC->upload_length;
1309                 att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1310                 att->FileName = NewStrBufPlain(WCC->upload_filename, -1);
1311                 
1312                 if (WCC->attachments == NULL) {
1313                         WCC->attachments = NewHash(1, NULL);
1314                 }
1315
1316                 /* And add it to the list. */
1317                 n = snprintf(N, sizeof N, "%d", GetCount(WCC->attachments) + 1);
1318                 Put(WCC->attachments, N, n, att, DestroyMime);
1319
1320                 /*
1321                  * Mozilla sends a simple filename, which is what we want,
1322                  * but Satan's Browser sends an entire pathname.  Reduce
1323                  * the path to just a filename if we need to.
1324                  */
1325                 pch = strrchr(ChrPtr(att->FileName), '/');
1326                 if (pch != NULL) {
1327                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1328                 }
1329                 pch = strrchr(ChrPtr(att->FileName), '\\');
1330                 if (pch != NULL) {
1331                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1332                 }
1333
1334                 /*
1335                  * Transfer control of this memory from the upload struct
1336                  * to the attachment struct.
1337                  */
1338                 att->Data = WCC->upload;
1339                 WCC->upload = NULL;
1340                 WCC->upload_length = 0;
1341                 display_enter();
1342                 return;
1343         }
1344
1345         if (havebstr("cancel_button")) {
1346                 sprintf(WCC->ImportantMessage, 
1347                         _("Cancelled.  Message was not posted."));
1348         } else if (havebstr("attach_button")) {
1349                 display_enter();
1350                 return;
1351         } else if (lbstr("postseq") == dont_post) {
1352                 sprintf(WCC->ImportantMessage, 
1353                         _("Automatically cancelled because you have already "
1354                         "saved this message."));
1355         } else {
1356                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1357                 const StrBuf *Recp = NULL; 
1358                 const StrBuf *Cc = NULL;
1359                 const StrBuf *Bcc = NULL;
1360                 const StrBuf *Wikipage = NULL;
1361                 const StrBuf *my_email_addr = NULL;
1362                 StrBuf *CmdBuf = NULL;
1363                 StrBuf *references = NULL;
1364                 int save_to_drafts;
1365
1366                 save_to_drafts = havebstr("save_button");
1367                 Buf = NewStrBuf();
1368
1369                 if (save_to_drafts) {
1370                         /* temporarily change to the drafts room */
1371                         serv_puts("GOTO _DRAFTS_");
1372                         StrBuf_ServGetln(Buf);
1373                         if (GetServerStatus(Buf, NULL) != 2) {
1374                                 /* You probably don't even have a dumb Drafts folder */
1375                                 StrBufCutLeft(Buf, 4);
1376                                 lprintf(9, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1377                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Saved to Drafts failed: "), -1, 0);
1378                                 StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1379                                 display_enter();
1380                                 FreeStrBuf(&Buf);
1381                                 return;
1382                         }
1383                 }
1384
1385                 if (havebstr("references"))
1386                 {
1387                         const StrBuf *ref = sbstr("references");
1388                         references = NewStrBufDup(ref);
1389                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1390                                 StrBufCutLeft(references, 1);
1391                         }
1392                         StrBufReplaceChars(references, '|', '!');
1393                 }
1394                 if (havebstr("subject")) {
1395                         const StrBuf *Subj;
1396                         /*
1397                          * make enough room for the encoded string; 
1398                          * plus the QP header 
1399                          */
1400                         Subj = sbstr("subject");
1401                         
1402                         StrBufRFC2047encode(&encoded_subject, Subj);
1403                 }
1404                 Recp = sbstr("recp");
1405                 Cc = sbstr("cc");
1406                 Bcc = sbstr("bcc");
1407                 Wikipage = sbstr("wikipage");
1408                 my_email_addr = sbstr("my_email_addr");
1409                 
1410                 CmdBuf = NewStrBufPlain(NULL, 
1411                                         sizeof (CMD) + 
1412                                         StrLength(Recp) + 
1413                                         StrLength(encoded_subject) +
1414                                         StrLength(Cc) +
1415                                         StrLength(Bcc) + 
1416                                         StrLength(Wikipage) +
1417                                         StrLength(my_email_addr) + 
1418                                         StrLength(references));
1419
1420                 StrBufPrintf(CmdBuf, 
1421                              CMD,
1422                              save_to_drafts?"":ChrPtr(Recp),
1423                              is_anonymous,
1424                              ChrPtr(encoded_subject),
1425                              ChrPtr(display_name),
1426                              save_to_drafts?"":ChrPtr(Cc),
1427                              save_to_drafts?"":ChrPtr(Bcc),
1428                              ChrPtr(Wikipage),
1429                              ChrPtr(my_email_addr),
1430                              ChrPtr(references));
1431                 FreeStrBuf(&references);
1432                 FreeStrBuf(&encoded_subject);
1433
1434                 lprintf(9, "%s\n", ChrPtr(CmdBuf));
1435                 serv_puts(ChrPtr(CmdBuf));
1436                 FreeStrBuf(&CmdBuf);
1437
1438                 StrBuf_ServGetln(Buf);
1439                 if (GetServerStatus(Buf, NULL) == 4) {
1440                         if (save_to_drafts) {
1441                                 if (  (havebstr("recp"))
1442                                     || (havebstr("cc"  ))
1443                                     || (havebstr("bcc" )) ) {
1444                                         /* save recipient headers or room to post to */
1445                                         serv_printf("To: %s", ChrPtr(Recp));
1446                                         serv_printf("Cc: %s", ChrPtr(Cc));
1447                                         serv_printf("Bcc: %s", ChrPtr(Bcc));
1448                                 } else {
1449                                         serv_printf("X-Citadel-Room: %s", ChrPtr(WC->wc_roomname));
1450                                 }
1451                         }
1452                         post_mime_to_server();
1453                         if (save_to_drafts) {
1454                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been saved to Drafts.\n"), -1, 0);
1455                                 gotoroom(WCC->wc_roomname);
1456                                 display_enter();
1457                                 FreeStrBuf(&Buf);
1458                                 return;
1459                         } else if (  (havebstr("recp"))
1460                            || (havebstr("cc"  ))
1461                            || (havebstr("bcc" ))
1462                         ) {
1463                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been sent.\n"), -1, 0);
1464                         }
1465                         else {
1466                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been posted.\n"), -1, 0);
1467                         }
1468                         dont_post = lbstr("postseq");
1469                 } else {
1470                         StrBufCutLeft(Buf, 4);
1471
1472                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1473                         StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1474                         if (save_to_drafts) gotoroom(WCC->wc_roomname);
1475                         display_enter();
1476                         FreeStrBuf(&Buf);
1477                         return;
1478                 }
1479                 FreeStrBuf(&Buf);
1480         }
1481
1482         DeleteHash(&WCC->attachments);
1483
1484         /*
1485          *  We may have been supplied with instructions regarding the location
1486          *  to which we must return after posting.  If found, go there.
1487          */
1488         if (havebstr("return_to")) {
1489                 http_redirect(bstr("return_to"));
1490         }
1491         /*
1492          *  If we were editing a page in a wiki room, go to that page now.
1493          */
1494         else if (havebstr("wikipage")) {
1495                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
1496                 http_redirect(buf);
1497         }
1498         /*
1499          *  Otherwise, just go to the "read messages" loop.
1500          */
1501         else {
1502                 readloop(readnew);
1503         }
1504 }
1505
1506
1507
1508
1509 /*
1510  * display the message entry screen
1511  */
1512 void display_enter(void)
1513 {
1514         char buf[SIZ];
1515         long now;
1516         const StrBuf *display_name = NULL;
1517         int recipient_required = 0;
1518         int subject_required = 0;
1519         int recipient_bad = 0;
1520         int is_anonymous = 0;
1521         wcsession *WCC = WC;
1522
1523         now = time(NULL);
1524
1525         if (havebstr("force_room")) {
1526                 gotoroom(sbstr("force_room"));
1527         }
1528
1529         display_name = sbstr("display_name");
1530         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1531                 display_name = NULL;
1532                 is_anonymous = 1;
1533         }
1534
1535         /* First test to see whether this is a room that requires recipients to be entered */
1536         serv_puts("ENT0 0");
1537         serv_getln(buf, sizeof buf);
1538
1539         if (!strncmp(buf, "570", 3)) {          /* 570 means that we need a recipient here */
1540                 recipient_required = 1;
1541         }
1542         else if (buf[0] != '2') {               /* Any other error means that we cannot continue */
1543                 sprintf(WCC->ImportantMessage, "%s", &buf[4]);
1544                 readloop(readnew);
1545                 return;
1546         }
1547
1548         /* Is the server strongly recommending that the user enter a message subject? */
1549         if ((buf[3] != '\0') && (buf[4] != '\0')) {
1550                 subject_required = extract_int(&buf[4], 1);
1551         }
1552
1553         /*
1554          * Are we perhaps in an address book view?  If so, then an "enter
1555          * message" command really means "add new entry."
1556          */
1557         if (WCC->wc_default_view == VIEW_ADDRESSBOOK) {
1558                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->wc_roomname));
1559                 return;
1560         }
1561
1562         /*
1563          * Are we perhaps in a calendar room?  If so, then an "enter
1564          * message" command really means "add new calendar item."
1565          */
1566         if (WCC->wc_default_view == VIEW_CALENDAR) {
1567                 display_edit_event();
1568                 return;
1569         }
1570
1571         /*
1572          * Are we perhaps in a tasks view?  If so, then an "enter
1573          * message" command really means "add new task."
1574          */
1575         if (WCC->wc_default_view == VIEW_TASKS) {
1576                 display_edit_task();
1577                 return;
1578         }
1579
1580         /*
1581          * Otherwise proceed normally.
1582          * Do a custom room banner with no navbar...
1583          */
1584
1585         if (recipient_required) {
1586                 const StrBuf *Recp = NULL; 
1587                 const StrBuf *Cc = NULL;
1588                 const StrBuf *Bcc = NULL;
1589                 const StrBuf *Wikipage = NULL;
1590                 StrBuf *CmdBuf = NULL;
1591                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1592                 
1593                 Recp = sbstr("recp");
1594                 Cc = sbstr("cc");
1595                 Bcc = sbstr("bcc");
1596                 Wikipage = sbstr("wikipage");
1597                 
1598                 CmdBuf = NewStrBufPlain(NULL, 
1599                                         sizeof (CMD) + 
1600                                         StrLength(Recp) + 
1601                                         StrLength(display_name) +
1602                                         StrLength(Cc) +
1603                                         StrLength(Bcc) + 
1604                                         StrLength(Wikipage));
1605
1606                 StrBufPrintf(CmdBuf, 
1607                              CMD,
1608                              ChrPtr(Recp), 
1609                              is_anonymous,
1610                              ChrPtr(display_name),
1611                              ChrPtr(Cc), 
1612                              ChrPtr(Bcc), 
1613                              ChrPtr(Wikipage));
1614                 serv_puts(ChrPtr(CmdBuf));
1615                 serv_getln(buf, sizeof buf);
1616                 FreeStrBuf(&CmdBuf);
1617
1618                 if (!strncmp(buf, "570", 3)) {  /* 570 means we have an invalid recipient listed */
1619                         if (havebstr("recp") && 
1620                             havebstr("cc"  ) && 
1621                             havebstr("bcc" )) {
1622                                 recipient_bad = 1;
1623                         }
1624                 }
1625                 else if (buf[0] != '2') {       /* Any other error means that we cannot continue */
1626                         wprintf("<em>%s</em><br />\n", &buf[4]);        /* TODO -> important message */
1627                         return;
1628                 }
1629         }
1630         svputlong("RCPTREQUIRED", recipient_required);
1631         svputlong("SUBJREQUIRED", recipient_required || subject_required);
1632
1633         begin_burst();
1634         output_headers(1, 0, 0, 0, 1, 0);
1635         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1636         end_burst();
1637
1638         return;
1639 }
1640
1641 /*
1642  * delete a message
1643  */
1644 void delete_msg(void)
1645 {
1646         long msgid;
1647         char buf[SIZ];
1648
1649         msgid = lbstr("msgid");
1650
1651         if (WC->wc_is_trash) {  /* Delete from Trash is a real delete */
1652                 serv_printf("DELE %ld", msgid); 
1653         }
1654         else {                  /* Otherwise move it to Trash */
1655                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1656         }
1657
1658         serv_getln(buf, sizeof buf);
1659         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1660         readloop(readnew);
1661 }
1662
1663
1664 /*
1665  * move a message to another room
1666  */
1667 void move_msg(void)
1668 {
1669         long msgid;
1670         char buf[SIZ];
1671
1672         msgid = lbstr("msgid");
1673
1674         if (havebstr("move_button")) {
1675                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
1676                 serv_puts(buf);
1677                 serv_getln(buf, sizeof buf);
1678                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
1679         } else {
1680                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
1681         }
1682
1683         readloop(readnew);
1684 }
1685
1686
1687 /*
1688  * Confirm move of a message
1689  */
1690 void confirm_move_msg(void)
1691 {
1692         long msgid;
1693         char buf[SIZ];
1694         char targ[SIZ];
1695
1696         msgid = lbstr("msgid");
1697
1698
1699         output_headers(1, 1, 2, 0, 0, 0);
1700         wprintf("<div id=\"banner\">\n");
1701         wprintf("<h1>");
1702         wprintf(_("Confirm move of message"));
1703         wprintf("</h1>");
1704         wprintf("</div>\n");
1705
1706         wprintf("<div id=\"content\" class=\"service\">\n");
1707
1708         wprintf("<CENTER>");
1709
1710         wprintf(_("Move this message to:"));
1711         wprintf("<br />\n");
1712
1713         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
1714         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
1715         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
1716
1717         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
1718         serv_puts("LKRA");
1719         serv_getln(buf, sizeof buf);
1720         if (buf[0] == '1') {
1721                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1722                         extract_token(targ, buf, 0, '|', sizeof targ);
1723                         wprintf("<OPTION>");
1724                         escputs(targ);
1725                         wprintf("\n");
1726                 }
1727         }
1728         wprintf("</SELECT>\n");
1729         wprintf("<br />\n");
1730
1731         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
1732         wprintf("&nbsp;");
1733         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
1734         wprintf("</form></CENTER>\n");
1735
1736         wprintf("</CENTER>\n");
1737         wDumpContent(1);
1738 }
1739
1740
1741 /*
1742  * Generic function to output an arbitrary MIME attachment from
1743  * message being composed
1744  *
1745  * partnum              The MIME part to be output
1746  * filename             Fake filename to give
1747  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1748  */
1749 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1750 {
1751         void *vPart;
1752         StrBuf *content_type;
1753         wc_mime_attachment *part;
1754         
1755         if (GetHash(WC->attachments, SKEY(partnum), &vPart) &&
1756             (vPart != NULL)) {
1757                 part = (wc_mime_attachment*) vPart;
1758                 if (force_download) {
1759                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1760                 }
1761                 else {
1762                         content_type = NewStrBufDup(part->ContentType);
1763                 }
1764                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1765                 http_transmit_thing(ChrPtr(content_type), 0);
1766         } else {
1767                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1768                 output_headers(0, 0, 0, 0, 0, 0);
1769                 hprintf("Content-Type: text/plain\r\n");
1770                 wprintf(_("An error occurred while retrieving this part: %s/%s\n"), 
1771                         ChrPtr(partnum), ChrPtr(filename));
1772                 end_burst();
1773         }
1774         FreeStrBuf(&content_type);
1775 }
1776
1777
1778 /*
1779  * Generic function to output an arbitrary MIME part from an arbitrary
1780  * message number on the server.
1781  *
1782  * msgnum               Number of the item on the citadel server
1783  * partnum              The MIME part to be output
1784  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1785  */
1786 void mimepart(int force_download)
1787 {
1788         long msgnum;
1789         StrBuf *att;
1790         wcsession *WCC = WC;
1791         StrBuf *Buf;
1792         off_t bytes;
1793         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1794         const char *CT;
1795
1796         att = Buf = NewStrBuf();
1797         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1798         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1799
1800         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1801         StrBuf_ServGetln(Buf);
1802         if (GetServerStatus(Buf, NULL) == 2) {
1803                 StrBufCutLeft(Buf, 4);
1804                 bytes = StrBufExtract_long(Buf, 0, '|');
1805                 if (!force_download) {
1806                         StrBufExtract_token(ContentType, Buf, 3, '|');
1807                 }
1808
1809                 read_server_binary(WCC->WBuf, bytes, Buf);
1810                 serv_puts("CLOS");
1811                 StrBuf_ServGetln(Buf);
1812                 CT = ChrPtr(ContentType);
1813
1814                 if (!force_download) {
1815                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1816                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1817                                 CT = GuessMimeByFilename(SKEY(Buf));
1818                         }
1819                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1820                                 CT = GuessMimeType(SKEY(WCC->WBuf));
1821                         }
1822                 }
1823                 http_transmit_thing(CT, 0);
1824         } else {
1825                 StrBufCutLeft(Buf, 4);
1826                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1827                 output_headers(0, 0, 0, 0, 0, 0);
1828                 hprintf("Content-Type: text/plain\r\n");
1829                 wprintf(_("An error occurred while retrieving this part: %s\n"), 
1830                         ChrPtr(Buf));
1831                 end_burst();
1832         }
1833         FreeStrBuf(&ContentType);
1834         FreeStrBuf(&Buf);
1835 }
1836
1837
1838 /*
1839  * Read any MIME part of a message, from the server, into memory.
1840  */
1841 StrBuf *load_mimepart(long msgnum, char *partnum)
1842 {
1843         off_t bytes;
1844         StrBuf *Buf;
1845         
1846         Buf = NewStrBuf();
1847         serv_printf("DLAT %ld|%s", msgnum, partnum);
1848         StrBuf_ServGetln(Buf);
1849         if (GetServerStatus(Buf, NULL) == 6) {
1850                 StrBufCutLeft(Buf, 4);
1851                 bytes = StrBufExtract_long(Buf, 0, '|');
1852                 FreeStrBuf(&Buf);
1853                 Buf = NewStrBuf();
1854                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1855                 return(Buf);
1856         }
1857         else {
1858                 FreeStrBuf(&Buf);
1859                 return(NULL);
1860         }
1861 }
1862
1863 /*
1864  * Read any MIME part of a message, from the server, into memory.
1865  */
1866 void MimeLoadData(wc_mime_attachment *Mime)
1867 {
1868         StrBuf *Buf;
1869         off_t bytes;
1870         /* TODO: is there a chance the content type is different from the one we know? */
1871         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1872         Buf = NewStrBuf();
1873         StrBuf_ServGetln(Buf);
1874         if (GetServerStatus(Buf, NULL) == 6) {
1875                 bytes = extract_long(&(ChrPtr(Buf)[4]), 0);
1876                                      
1877                 if (Mime->Data == NULL)
1878                         Mime->Data = NewStrBufPlain(NULL, bytes);
1879                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1880         }
1881         else {
1882                 FlushStrBuf(Mime->Data);
1883                 /* TODO XImportant message */
1884         }
1885         FreeStrBuf(&Buf);
1886 }
1887
1888
1889
1890
1891 void view_mimepart(void) {
1892         mimepart(0);
1893 }
1894
1895 void download_mimepart(void) {
1896         mimepart(1);
1897 }
1898
1899 void view_postpart(void) {
1900         StrBuf *filename = NewStrBuf();
1901         StrBuf *partnum = NewStrBuf();
1902
1903         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1904         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1905
1906         postpart(partnum, filename, 0);
1907
1908         FreeStrBuf(&filename);
1909         FreeStrBuf(&partnum);
1910 }
1911
1912 void download_postpart(void) {
1913         StrBuf *filename = NewStrBuf();
1914         StrBuf *partnum = NewStrBuf();
1915
1916         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1917         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1918
1919         postpart(partnum, filename, 1);
1920
1921         FreeStrBuf(&filename);
1922         FreeStrBuf(&partnum);
1923 }
1924
1925 void h_readnew(void) { readloop(readnew);}
1926 void h_readold(void) { readloop(readold);}
1927 void h_readfwd(void) { readloop(readfwd);}
1928 void h_headers(void) { readloop(headers);}
1929 void h_do_search(void) { readloop(do_search);}
1930 void h_readgt(void) { readloop(readgt);}
1931
1932 void jsonMessageListHdr(void) 
1933 {
1934         /* TODO: make a generic function */
1935         hprintf("HTTP/1.1 200 OK\r\n");
1936         hprintf("Content-type: application/json; charset=utf-8\r\n");
1937         hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1938         hprintf("Connection: close\r\n");
1939         hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1940         begin_burst();
1941 }
1942
1943 /* Spit out the new summary view. This is basically a static page, so clients can cache the layout, all the dirty work is javascript :) */
1944 void new_summary_view(void) {
1945         begin_burst();
1946         DoTemplate(HKEY("msg_listview"),NULL,&NoCtx);
1947         DoTemplate(HKEY("trailing"),NULL,&NoCtx);
1948         end_burst();
1949 }
1950
1951 /* Output message list in JSON format */
1952 void jsonMessageList(void) {
1953         const StrBuf *room = sbstr("room");
1954         long oper = (havebstr("query")) ? do_search : readnew;
1955         WC->is_ajax = 1; 
1956         gotoroom(room);
1957         readloop(oper);
1958         WC->is_ajax = 0;
1959 }
1960
1961 void 
1962 InitModule_MSG
1963 (void)
1964 {
1965         RegisterPreference("use_sig",
1966                            _("Attach signature to email messages?"), 
1967                            PRF_YESNO, 
1968                            NULL);
1969         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1970         RegisterPreference("default_header_charset", 
1971                            _("Default character set for email headers:"), 
1972                            PRF_STRING, 
1973                            NULL);
1974         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1975         RegisterPreference("defaultname", 
1976                            _("Preferred display name for email messages"), 
1977                            PRF_STRING, 
1978                            NULL);
1979         RegisterPreference("defaulthandle", 
1980                            _("Preferred display name for bulletin board posts"), 
1981                            PRF_STRING, 
1982                            NULL);
1983         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1984
1985         WebcitAddUrlHandler(HKEY("readnew"), h_readnew, NEED_URL);
1986         WebcitAddUrlHandler(HKEY("readold"), h_readold, NEED_URL);
1987         WebcitAddUrlHandler(HKEY("readfwd"), h_readfwd, NEED_URL);
1988         WebcitAddUrlHandler(HKEY("headers"), h_headers, NEED_URL);
1989         WebcitAddUrlHandler(HKEY("readgt"), h_readgt, NEED_URL);
1990         WebcitAddUrlHandler(HKEY("do_search"), h_do_search, 0);
1991         WebcitAddUrlHandler(HKEY("display_enter"), display_enter, 0);
1992         WebcitAddUrlHandler(HKEY("post"), post_message, 0);
1993         WebcitAddUrlHandler(HKEY("move_msg"), move_msg, 0);
1994         WebcitAddUrlHandler(HKEY("delete_msg"), delete_msg, 0);
1995         WebcitAddUrlHandler(HKEY("confirm_move_msg"), confirm_move_msg, 0);
1996         WebcitAddUrlHandler(HKEY("msg"), embed_message, NEED_URL);
1997         WebcitAddUrlHandler(HKEY("message"), handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1998         WebcitAddUrlHandler(HKEY("printmsg"), print_message, NEED_URL);
1999         WebcitAddUrlHandler(HKEY("mobilemsg"), mobile_message_view, NEED_URL);
2000         WebcitAddUrlHandler(HKEY("msgheaders"), display_headers, NEED_URL);
2001
2002         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
2003         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
2004         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
2005         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
2006
2007         /* json */
2008         WebcitAddUrlHandler(HKEY("roommsgs"), jsonMessageList,0);
2009         return ;
2010 }
2011
2012 void
2013 SessionDetachModule_MSG
2014 (wcsession *sess)
2015 {
2016         DeleteHash(&sess->summ);
2017 }