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