47f6f41c5eafb2e90c4efa992a7b57d1637f5268
[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"
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                 SetAccessCommand(oper);
931
932                 if (havebstr("maxmsgs"))
933                         maxmsgs = ibstr("maxmsgs");
934                 if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
935
936                 if (havebstr("startmsg")) {
937                         startmsg = lbstr("startmsg");
938                 }
939                 
940         }
941
942         nummsgs = load_msg_ptrs(cmd, with_headers);
943         if (nummsgs == 0) {
944                 if (care_for_empty_list) {
945                         wprintf("<div class=\"nomsgs\"><br><em>");
946                         switch (oper) {
947                         case readnew:
948                                 wprintf(_("No new messages."));
949                                 break;
950                         case readold:
951                                 wprintf(_("No old messages."));
952                                 break;
953                         default:
954                                 wprintf(_("No messages here."));
955                         }
956                         wprintf("</em><br></div>\n");
957                         goto DONE;
958                 }
959
960         }
961
962         if (sortit) {
963                 CompareFunc SortIt;
964                 memset(&SubTP, 0, sizeof(WCTemplputParams));
965                 SubTP.Filter.ContextType = CTX_NONE;
966                 SubTP.Context = NULL;
967                 SortIt =  RetrieveSort(&SubTP, NULL, 0,
968                                        HKEY("date"), defaultsortorder);
969                 if (SortIt != NULL)
970                         SortByPayload(WCC->summ, SortIt);
971                 if (WCC->wc_view == VIEW_BBS) {
972                         if (lbstr("SortOrder") == 2) {
973                                 bbs_reverse = 1;
974                                 num_displayed = -DEFAULT_MAXMSGS;
975                         }
976                         else {
977                                 bbs_reverse = 0;
978                                 num_displayed = DEFAULT_MAXMSGS;
979                         }
980                 }
981         }
982         if (startmsg < 0) startmsg = (bbs_reverse) ? nummsgs - 1 : 0;
983
984         if (load_seen) load_seen_flags();
985         
986         /*
987          * Print any inforation above the message list...
988          */
989         switch (WCC->wc_view) {
990         case VIEW_BBS:
991                 BBViewToolBar = NewStrBufPlain(NULL, SIZ);
992                 MessageDropdown = NewStrBufPlain(NULL, SIZ);
993
994                 maxmsgs = DrawMessageDropdown(MessageDropdown, maxmsgs, startmsg, num_displayed);
995                 if (num_displayed < 0) {
996                         startmsg += maxmsgs;
997                         if (num_displayed != maxmsgs)                           
998                                 maxmsgs = abs(maxmsgs) + 1;
999                         else
1000                                 maxmsgs = abs(maxmsgs);
1001
1002                 }
1003                 memset(&SubTP, 0, sizeof(WCTemplputParams));
1004                 SubTP.Filter.ContextType = CTX_STRBUF;
1005                 SubTP.Context = MessageDropdown;
1006                 DoTemplate(HKEY("msg_listselector_top"), BBViewToolBar, &SubTP);
1007                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
1008                 FlushStrBuf(BBViewToolBar);
1009                 break;
1010         }
1011         WCC->startmsg =  startmsg;
1012         WCC->maxmsgs = maxmsgs;
1013         WCC->num_displayed = 0;
1014
1015         /* Put some helpful data in vars for mailsummary_json */
1016         svputlong("READLOOP:TOTALMSGS", nummsgs);
1017         svputlong("READLOOP:STARTMSG", startmsg);
1018         svputlong("WCVIEW", WCC->wc_view);
1019
1020         /*
1021          * iterate over each message. if we need to load an attachment, do it here. 
1022          */
1023         if (WCC->wc_view == VIEW_MAILBOX) goto NO_MSG_LOOP;
1024         at = GetNewHashPos(WCC->summ, 0);
1025         num_displayed = i = 0;
1026         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
1027                 Msg = (message_summary*) vMsg;          
1028                 if ((Msg->msgnum >= startmsg) && (num_displayed <= maxmsgs)) {                  
1029                         switch (WCC->wc_view) {
1030                         case VIEW_WIKI:
1031                                 break;
1032                         case VIEW_CALBRIEF: /* load the mime attachments for special tasks... */
1033                         case VIEW_CALENDAR:
1034                                 load_calendar_item(Msg, Msg->is_new, &calv);
1035                                 break;
1036                         case VIEW_TASKS:
1037                                 display_task(Msg, Msg->is_new);
1038                                 break;
1039                         case VIEW_NOTES:
1040                                 display_note(Msg, Msg->is_new);
1041                                 break;
1042                         case VIEW_ADDRESSBOOK:
1043                                 ab_name = NULL;
1044                                 fetch_ab_name(Msg, &ab_name);
1045                                 if (ab_name == NULL) 
1046                                         break;
1047                                 ++num_ab;
1048                                 addrbook = realloc(addrbook,
1049                                                    (sizeof(addrbookent) * num_ab) );
1050                                 safestrncpy(addrbook[num_ab-1].ab_name, ab_name,
1051                                             sizeof(addrbook[num_ab-1].ab_name));
1052                                 addrbook[num_ab-1].ab_msgnum = Msg->msgnum;
1053                                 free(ab_name);
1054                                 break;
1055                         case VIEW_BBS: /* Tag the mails we want to show in bbview... */
1056                         default:
1057                                 if (displayed_msgs == NULL) {
1058                                         displayed_msgs = malloc(sizeof(long) *
1059                                                                 (maxmsgs<nummsgs ? maxmsgs + 1 : nummsgs + 1));
1060                                 }
1061                                 if ((i >= startmsg) && (i < startmsg + maxmsgs)) {
1062                                         displayed_msgs[num_displayed] = Msg->msgnum;
1063                                         if (lowest_displayed < 0) lowest_displayed = a;
1064                                         highest_displayed = a;
1065                         
1066                                         num_displayed++;
1067                                 }
1068                         }
1069                 } 
1070                 i++;
1071         }
1072         DeleteHashPos(&at);
1073
1074 NO_MSG_LOOP:
1075         /*
1076          * Done iterating the message list. now tasks we want to do after.
1077          */
1078         switch (WCC->wc_view) {
1079         case VIEW_MAILBOX:
1080           DoTemplate(HKEY("mailsummary_json"),NULL, &SubTP);
1081           break;
1082         case VIEW_BBS:
1083                 if (displayed_msgs != NULL) {
1084                         /** if we do a split bbview in the future, begin messages div here */
1085                         
1086                         for (a=0; a<num_displayed; ++a) {
1087                                 read_message(WCC->WBuf, HKEY("view_message"), displayed_msgs[a], NULL, &Mime);
1088                         }
1089                         
1090                         /* if we do a split bbview in the future, end messages div here */
1091                         
1092                         free(displayed_msgs);
1093                         displayed_msgs = NULL;
1094                 }
1095                 memset(&SubTP, 0, sizeof(WCTemplputParams));
1096                 SubTP.Filter.ContextType = CTX_STRBUF;
1097                 SubTP.Context = MessageDropdown;
1098                 DoTemplate(HKEY("msg_listselector_bottom"), BBViewToolBar, &SubTP);
1099                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
1100
1101                 FreeStrBuf(&BBViewToolBar);
1102                 FreeStrBuf(&MessageDropdown);
1103         }
1104
1105         
1106 DONE:
1107         switch (WCC->wc_view) {
1108         case VIEW_WIKI:
1109                 break;
1110         case VIEW_CALBRIEF:
1111         case VIEW_CALENDAR:
1112                 render_calendar_view(&calv);
1113                 break;
1114         case VIEW_TASKS:
1115                 do_tasks_view();        /** Render the task list */
1116                 break;
1117         case VIEW_NOTES:
1118                 break;
1119         case VIEW_ADDRESSBOOK:
1120                 if (is_singlecard)
1121                         read_message(WC->WBuf, HKEY("view_message"), lbstr("startmsg"), NULL, &Mime);
1122                 else
1123                         do_addrbook_view(addrbook, num_ab);     /* Render the address book */
1124                 break;
1125         case VIEW_MAILBOX: 
1126         case VIEW_BBS:
1127         default:
1128                 break;
1129         }
1130         /** Note: wDumpContent() will output one additional </div> tag. */
1131         if (WCC->wc_view != VIEW_MAILBOX) {
1132                 /* We ought to move this out into template */
1133                 wDumpContent(1);
1134         } else {
1135                 end_burst();
1136         }
1137         WCC->startmsg = 0;
1138         WCC->maxmsgs = 0;
1139         if (WCC->summ != NULL) {
1140                 DeleteHash(&WCC->summ);
1141         }
1142         if (addrbook != NULL) free(addrbook);
1143         FreeStrBuf(&BBViewToolBar);
1144 }
1145
1146
1147 /*
1148  * Back end for post_message()
1149  * ... this is where the actual message gets transmitted to the server.
1150  */
1151 void post_mime_to_server(void) {
1152         wcsession *WCC = WC;
1153         char top_boundary[SIZ];
1154         char alt_boundary[SIZ];
1155         int is_multipart = 0;
1156         static int seq = 0;
1157         wc_mime_attachment *att;
1158         char *encoded;
1159         size_t encoded_length;
1160         size_t encoded_strlen;
1161         char *txtmail = NULL;
1162
1163         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
1164                 ChrPtr(WCC->serv_info->serv_fqdn),
1165                 getpid(),
1166                 ++seq
1167         );
1168         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
1169                 ChrPtr(WCC->serv_info->serv_fqdn),
1170                 getpid(),
1171                 ++seq
1172         );
1173
1174         /* RFC2045 requires this, and some clients look for it... */
1175         serv_puts("MIME-Version: 1.0");
1176         serv_puts("X-Mailer: " PACKAGE_STRING);
1177
1178         /* If there are attachments, we have to do multipart/mixed */
1179         if (GetCount(WCC->attachments) > 0) {
1180                 is_multipart = 1;
1181         }
1182
1183         if (is_multipart) {
1184                 /* Remember, serv_printf() appends an extra newline */
1185                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
1186                 serv_printf("This is a multipart message in MIME format.\n");
1187                 serv_printf("--%s", top_boundary);
1188         }
1189
1190         /* Remember, serv_printf() appends an extra newline */
1191         serv_printf("Content-type: multipart/alternative; "
1192                 "boundary=\"%s\"\n", alt_boundary);
1193         serv_printf("This is a multipart message in MIME format.\n");
1194         serv_printf("--%s", alt_boundary);
1195
1196         serv_puts("Content-type: text/plain; charset=utf-8");
1197         serv_puts("Content-Transfer-Encoding: quoted-printable");
1198         serv_puts("");
1199         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
1200         text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
1201         free(txtmail);
1202
1203         serv_printf("--%s", alt_boundary);
1204
1205         serv_puts("Content-type: text/html; charset=utf-8");
1206         serv_puts("Content-Transfer-Encoding: quoted-printable");
1207         serv_puts("");
1208         serv_puts("<html><body>\r\n");
1209         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
1210         serv_puts("</body></html>\r\n");
1211
1212         serv_printf("--%s--", alt_boundary);
1213         
1214         if (is_multipart) {
1215                 long len;
1216                 const char *Key; 
1217                 void *vAtt;
1218                 HashPos  *it;
1219
1220                 /* Add in the attachments */
1221                 it = GetNewHashPos(WCC->attachments, 0);
1222                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
1223                         att = (wc_mime_attachment *)vAtt;
1224                         encoded_length = ((att->length * 150) / 100);
1225                         encoded = malloc(encoded_length);
1226                         if (encoded == NULL) break;
1227                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
1228
1229                         serv_printf("--%s", top_boundary);
1230                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
1231                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
1232                         serv_puts("Content-transfer-encoding: base64");
1233                         serv_puts("");
1234                         serv_write(encoded, encoded_strlen);
1235                         serv_puts("");
1236                         serv_puts("");
1237                         free(encoded);
1238                 }
1239                 serv_printf("--%s--", top_boundary);
1240                 DeleteHashPos(&it);
1241         }
1242
1243         serv_puts("000");
1244 }
1245
1246
1247 /*
1248  * Post message (or don't post message)
1249  *
1250  * Note regarding the "dont_post" variable:
1251  * A random value (actually, it's just a timestamp) is inserted as a hidden
1252  * field called "postseq" when the display_enter page is generated.  This
1253  * value is checked when posting, using the static variable dont_post.  If a
1254  * user attempts to post twice using the same dont_post value, the message is
1255  * discarded.  This prevents the accidental double-saving of the same message
1256  * if the user happens to click the browser "back" button.
1257  */
1258 void post_message(void)
1259 {
1260         char buf[1024];
1261         StrBuf *encoded_subject = NULL;
1262         static long dont_post = (-1L);
1263         wc_mime_attachment  *att;
1264         int is_anonymous = 0;
1265         const StrBuf *display_name = NULL;
1266         wcsession *WCC = WC;
1267         StrBuf *Buf;
1268         
1269         if (havebstr("force_room")) {
1270                 gotoroom(sbstr("force_room"));
1271         }
1272
1273         if (havebstr("display_name")) {
1274                 display_name = sbstr("display_name");
1275                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1276                         display_name = NULL;
1277                         is_anonymous = 1;
1278                 }
1279         }
1280
1281         if (WCC->upload_length > 0) {
1282                 const char *pch;
1283                 int n;
1284                 char N[64];
1285
1286                 /* There's an attachment.  Save it to this struct... */
1287                 lprintf(9, "Client is uploading %d bytes\n", WCC->upload_length);
1288                 att = malloc(sizeof(wc_mime_attachment));
1289                 memset(att, 0, sizeof(wc_mime_attachment ));
1290                 att->length = WCC->upload_length;
1291                 att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1292                 att->FileName = NewStrBufPlain(WCC->upload_filename, -1);
1293                 
1294                 if (WCC->attachments == NULL) {
1295                         WCC->attachments = NewHash(1, NULL);
1296                 }
1297
1298                 /* And add it to the list. */
1299                 n = snprintf(N, sizeof N, "%d", GetCount(WCC->attachments) + 1);
1300                 Put(WCC->attachments, N, n, att, DestroyMime);
1301
1302                 /*
1303                  * Mozilla sends a simple filename, which is what we want,
1304                  * but Satan's Browser sends an entire pathname.  Reduce
1305                  * the path to just a filename if we need to.
1306                  */
1307                 pch = strrchr(ChrPtr(att->FileName), '/');
1308                 if (pch != NULL) {
1309                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1310                 }
1311                 pch = strrchr(ChrPtr(att->FileName), '\\');
1312                 if (pch != NULL) {
1313                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1314                 }
1315
1316                 /*
1317                  * Transfer control of this memory from the upload struct
1318                  * to the attachment struct.
1319                  */
1320                 att->Data = WCC->upload;
1321                 WCC->upload = NULL;
1322                 WCC->upload_length = 0;
1323                 display_enter();
1324                 return;
1325         }
1326
1327         if (havebstr("cancel_button")) {
1328                 sprintf(WCC->ImportantMessage, 
1329                         _("Cancelled.  Message was not posted."));
1330         } else if (havebstr("attach_button")) {
1331                 display_enter();
1332                 return;
1333         } else if (lbstr("postseq") == dont_post) {
1334                 sprintf(WCC->ImportantMessage, 
1335                         _("Automatically cancelled because you have already "
1336                         "saved this message."));
1337         } else {
1338                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1339                 const StrBuf *Recp = NULL; 
1340                 const StrBuf *Cc = NULL;
1341                 const StrBuf *Bcc = NULL;
1342                 const StrBuf *Wikipage = NULL;
1343                 const StrBuf *my_email_addr = NULL;
1344                 StrBuf *CmdBuf = NULL;
1345                 StrBuf *references = NULL;
1346                 int save_to_drafts;
1347
1348                 save_to_drafts = havebstr("save_button");
1349                 Buf = NewStrBuf();
1350
1351                 if (save_to_drafts) {
1352                         /* temporarily change to the drafts room */
1353                         serv_puts("GOTO _DRAFTS_");
1354                         StrBuf_ServGetln(Buf);
1355                         if (GetServerStatus(Buf, NULL) != 2) {
1356                                 /* You probably don't even have a dumb Drafts folder */
1357                                 StrBufCutLeft(Buf, 4);
1358                                 lprintf(9, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1359                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Saved to Drafts failed: "), -1, 0);
1360                                 StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1361                                 display_enter();
1362                                 FreeStrBuf(&Buf);
1363                                 return;
1364                         }
1365                 }
1366
1367                 if (havebstr("references"))
1368                 {
1369                         const StrBuf *ref = sbstr("references");
1370                         references = NewStrBufDup(ref);
1371                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1372                                 StrBufCutLeft(references, 1);
1373                         }
1374                         StrBufReplaceChars(references, '|', '!');
1375                 }
1376                 if (havebstr("subject")) {
1377                         const StrBuf *Subj;
1378                         /*
1379                          * make enough room for the encoded string; 
1380                          * plus the QP header 
1381                          */
1382                         Subj = sbstr("subject");
1383                         
1384                         StrBufRFC2047encode(&encoded_subject, Subj);
1385                 }
1386                 Recp = sbstr("recp");
1387                 Cc = sbstr("cc");
1388                 Bcc = sbstr("bcc");
1389                 Wikipage = sbstr("wikipage");
1390                 my_email_addr = sbstr("my_email_addr");
1391                 
1392                 CmdBuf = NewStrBufPlain(NULL, 
1393                                         sizeof (CMD) + 
1394                                         StrLength(Recp) + 
1395                                         StrLength(encoded_subject) +
1396                                         StrLength(Cc) +
1397                                         StrLength(Bcc) + 
1398                                         StrLength(Wikipage) +
1399                                         StrLength(my_email_addr) + 
1400                                         StrLength(references));
1401
1402                 StrBufPrintf(CmdBuf, 
1403                              CMD,
1404                              save_to_drafts?"":ChrPtr(Recp),
1405                              is_anonymous,
1406                              ChrPtr(encoded_subject),
1407                              ChrPtr(display_name),
1408                              save_to_drafts?"":ChrPtr(Cc),
1409                              save_to_drafts?"":ChrPtr(Bcc),
1410                              ChrPtr(Wikipage),
1411                              ChrPtr(my_email_addr),
1412                              ChrPtr(references));
1413                 FreeStrBuf(&references);
1414                 FreeStrBuf(&encoded_subject);
1415
1416                 lprintf(9, "%s\n", ChrPtr(CmdBuf));
1417                 serv_puts(ChrPtr(CmdBuf));
1418                 FreeStrBuf(&CmdBuf);
1419
1420                 StrBuf_ServGetln(Buf);
1421                 if (GetServerStatus(Buf, NULL) == 4) {
1422                         if (save_to_drafts) {
1423                                 if (  (havebstr("recp"))
1424                                     || (havebstr("cc"  ))
1425                                     || (havebstr("bcc" )) ) {
1426                                         /* save recipient headers or room to post to */
1427                                         serv_printf("To: %s", ChrPtr(Recp));
1428                                         serv_printf("Cc: %s", ChrPtr(Cc));
1429                                         serv_printf("Bcc: %s", ChrPtr(Bcc));
1430                                 } else {
1431                                         serv_printf("X-Citadel-Room: %s", ChrPtr(WC->wc_roomname));
1432                                 }
1433                         }
1434                         post_mime_to_server();
1435                         if (save_to_drafts) {
1436                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been saved to Drafts.\n"), -1, 0);
1437                                 gotoroom(WCC->wc_roomname);
1438                                 display_enter();
1439                                 FreeStrBuf(&Buf);
1440                                 return;
1441                         } else if (  (havebstr("recp"))
1442                            || (havebstr("cc"  ))
1443                            || (havebstr("bcc" ))
1444                         ) {
1445                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been sent.\n"), -1, 0);
1446                         }
1447                         else {
1448                                 StrBufAppendBufPlain(WCC->ImportantMsg, _("Message has been posted.\n"), -1, 0);
1449                         }
1450                         dont_post = lbstr("postseq");
1451                 } else {
1452                         StrBufCutLeft(Buf, 4);
1453
1454                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, ChrPtr(Buf));
1455                         StrBufAppendBuf(WCC->ImportantMsg, Buf, 0);
1456                         if (save_to_drafts) gotoroom(WCC->wc_roomname);
1457                         display_enter();
1458                         FreeStrBuf(&Buf);
1459                         return;
1460                 }
1461                 FreeStrBuf(&Buf);
1462         }
1463
1464         DeleteHash(&WCC->attachments);
1465
1466         /*
1467          *  We may have been supplied with instructions regarding the location
1468          *  to which we must return after posting.  If found, go there.
1469          */
1470         if (havebstr("return_to")) {
1471                 http_redirect(bstr("return_to"));
1472         }
1473         /*
1474          *  If we were editing a page in a wiki room, go to that page now.
1475          */
1476         else if (havebstr("wikipage")) {
1477                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
1478                 http_redirect(buf);
1479         }
1480         /*
1481          *  Otherwise, just go to the "read messages" loop.
1482          */
1483         else {
1484                 readloop(readnew);
1485         }
1486 }
1487
1488
1489
1490
1491 /*
1492  * display the message entry screen
1493  */
1494 void display_enter(void)
1495 {
1496         char buf[SIZ];
1497         long now;
1498         const StrBuf *display_name = NULL;
1499         int recipient_required = 0;
1500         int subject_required = 0;
1501         int recipient_bad = 0;
1502         int is_anonymous = 0;
1503         wcsession *WCC = WC;
1504
1505         now = time(NULL);
1506
1507         if (havebstr("force_room")) {
1508                 gotoroom(sbstr("force_room"));
1509         }
1510
1511         display_name = sbstr("display_name");
1512         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1513                 display_name = NULL;
1514                 is_anonymous = 1;
1515         }
1516
1517         /* First test to see whether this is a room that requires recipients to be entered */
1518         serv_puts("ENT0 0");
1519         serv_getln(buf, sizeof buf);
1520
1521         if (!strncmp(buf, "570", 3)) {          /* 570 means that we need a recipient here */
1522                 recipient_required = 1;
1523         }
1524         else if (buf[0] != '2') {               /* Any other error means that we cannot continue */
1525                 sprintf(WCC->ImportantMessage, "%s", &buf[4]);
1526                 readloop(readnew);
1527                 return;
1528         }
1529
1530         /* Is the server strongly recommending that the user enter a message subject? */
1531         if ((buf[3] != '\0') && (buf[4] != '\0')) {
1532                 subject_required = extract_int(&buf[4], 1);
1533         }
1534
1535         /**
1536          * Are we perhaps in an address book view?  If so, then an "enter
1537          * message" command really means "add new entry."
1538          */
1539         if (WCC->wc_default_view == VIEW_ADDRESSBOOK) {
1540                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WCC->wc_roomname));
1541                 return;
1542         }
1543
1544         /*
1545          * Are we perhaps in a calendar room?  If so, then an "enter
1546          * message" command really means "add new calendar item."
1547          */
1548         if (WCC->wc_default_view == VIEW_CALENDAR) {
1549                 display_edit_event();
1550                 return;
1551         }
1552
1553         /*
1554          * Are we perhaps in a tasks view?  If so, then an "enter
1555          * message" command really means "add new task."
1556          */
1557         if (WCC->wc_default_view == VIEW_TASKS) {
1558                 display_edit_task();
1559                 return;
1560         }
1561
1562         /*
1563          * Otherwise proceed normally.
1564          * Do a custom room banner with no navbar...
1565          */
1566
1567         if (recipient_required) {
1568                 const StrBuf *Recp = NULL; 
1569                 const StrBuf *Cc = NULL;
1570                 const StrBuf *Bcc = NULL;
1571                 const StrBuf *Wikipage = NULL;
1572                 StrBuf *CmdBuf = NULL;
1573                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1574                 
1575                 Recp = sbstr("recp");
1576                 Cc = sbstr("cc");
1577                 Bcc = sbstr("bcc");
1578                 Wikipage = sbstr("wikipage");
1579                 
1580                 CmdBuf = NewStrBufPlain(NULL, 
1581                                         sizeof (CMD) + 
1582                                         StrLength(Recp) + 
1583                                         StrLength(display_name) +
1584                                         StrLength(Cc) +
1585                                         StrLength(Bcc) + 
1586                                         StrLength(Wikipage));
1587
1588                 StrBufPrintf(CmdBuf, 
1589                              CMD,
1590                              ChrPtr(Recp), 
1591                              is_anonymous,
1592                              ChrPtr(display_name),
1593                              ChrPtr(Cc), 
1594                              ChrPtr(Bcc), 
1595                              ChrPtr(Wikipage));
1596                 serv_puts(ChrPtr(CmdBuf));
1597                 serv_getln(buf, sizeof buf);
1598                 FreeStrBuf(&CmdBuf);
1599
1600                 if (!strncmp(buf, "570", 3)) {  /* 570 means we have an invalid recipient listed */
1601                         if (havebstr("recp") && 
1602                             havebstr("cc"  ) && 
1603                             havebstr("bcc" )) {
1604                                 recipient_bad = 1;
1605                         }
1606                 }
1607                 else if (buf[0] != '2') {       /* Any other error means that we cannot continue */
1608                         wprintf("<em>%s</em><br />\n", &buf[4]);        /* TODO -> important message */
1609                         return;
1610                 }
1611         }
1612         svputlong("RCPTREQUIRED", recipient_required);
1613         svputlong("SUBJREQUIRED", recipient_required || subject_required);
1614
1615         begin_burst();
1616         output_headers(1, 0, 0, 0, 1, 0);
1617         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1618         end_burst();
1619
1620         return;
1621 }
1622
1623 /*
1624  * delete a message
1625  */
1626 void delete_msg(void)
1627 {
1628         long msgid;
1629         char buf[SIZ];
1630
1631         msgid = lbstr("msgid");
1632
1633         if (WC->wc_is_trash) {  /* Delete from Trash is a real delete */
1634                 serv_printf("DELE %ld", msgid); 
1635         }
1636         else {                  /* Otherwise move it to Trash */
1637                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1638         }
1639
1640         serv_getln(buf, sizeof buf);
1641         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1642         readloop(readnew);
1643 }
1644
1645
1646 /*
1647  * move a message to another room
1648  */
1649 void move_msg(void)
1650 {
1651         long msgid;
1652         char buf[SIZ];
1653
1654         msgid = lbstr("msgid");
1655
1656         if (havebstr("move_button")) {
1657                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
1658                 serv_puts(buf);
1659                 serv_getln(buf, sizeof buf);
1660                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
1661         } else {
1662                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
1663         }
1664
1665         readloop(readnew);
1666 }
1667
1668
1669 /*
1670  * Confirm move of a message
1671  */
1672 void confirm_move_msg(void)
1673 {
1674         long msgid;
1675         char buf[SIZ];
1676         char targ[SIZ];
1677
1678         msgid = lbstr("msgid");
1679
1680
1681         output_headers(1, 1, 2, 0, 0, 0);
1682         wprintf("<div id=\"banner\">\n");
1683         wprintf("<h1>");
1684         wprintf(_("Confirm move of message"));
1685         wprintf("</h1>");
1686         wprintf("</div>\n");
1687
1688         wprintf("<div id=\"content\" class=\"service\">\n");
1689
1690         wprintf("<CENTER>");
1691
1692         wprintf(_("Move this message to:"));
1693         wprintf("<br />\n");
1694
1695         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
1696         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
1697         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
1698
1699         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
1700         serv_puts("LKRA");
1701         serv_getln(buf, sizeof buf);
1702         if (buf[0] == '1') {
1703                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1704                         extract_token(targ, buf, 0, '|', sizeof targ);
1705                         wprintf("<OPTION>");
1706                         escputs(targ);
1707                         wprintf("\n");
1708                 }
1709         }
1710         wprintf("</SELECT>\n");
1711         wprintf("<br />\n");
1712
1713         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
1714         wprintf("&nbsp;");
1715         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
1716         wprintf("</form></CENTER>\n");
1717
1718         wprintf("</CENTER>\n");
1719         wDumpContent(1);
1720 }
1721
1722
1723 /*
1724  * Generic function to output an arbitrary MIME attachment from
1725  * message being composed
1726  *
1727  * partnum              The MIME part to be output
1728  * filename             Fake filename to give
1729  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1730  */
1731 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1732 {
1733         void *vPart;
1734         StrBuf *content_type;
1735         wc_mime_attachment *part;
1736         
1737         if (GetHash(WC->attachments, SKEY(partnum), &vPart) &&
1738             (vPart != NULL)) {
1739                 part = (wc_mime_attachment*) vPart;
1740                 if (force_download) {
1741                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1742                 }
1743                 else {
1744                         content_type = NewStrBufDup(part->ContentType);
1745                 }
1746                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1747                 http_transmit_thing(ChrPtr(content_type), 0);
1748         } else {
1749                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1750                 output_headers(0, 0, 0, 0, 0, 0);
1751                 hprintf("Content-Type: text/plain\r\n");
1752                 wprintf(_("An error occurred while retrieving this part: %s/%s\n"), 
1753                         ChrPtr(partnum), ChrPtr(filename));
1754                 end_burst();
1755         }
1756         FreeStrBuf(&content_type);
1757 }
1758
1759
1760 /*
1761  * Generic function to output an arbitrary MIME part from an arbitrary
1762  * message number on the server.
1763  *
1764  * msgnum               Number of the item on the citadel server
1765  * partnum              The MIME part to be output
1766  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1767  */
1768 void mimepart(int force_download)
1769 {
1770         long msgnum;
1771         StrBuf *att;
1772         wcsession *WCC = WC;
1773         StrBuf *Buf;
1774         off_t bytes;
1775         StrBuf *ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1776         const char *CT;
1777
1778         att = Buf = NewStrBuf();
1779         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
1780         StrBufExtract_token(att, WCC->Hdr->HR.ReqLine, 1, '/');
1781
1782         serv_printf("OPNA %ld|%s", msgnum, ChrPtr(att));
1783         StrBuf_ServGetln(Buf);
1784         if (GetServerStatus(Buf, NULL) == 2) {
1785                 StrBufCutLeft(Buf, 4);
1786                 bytes = StrBufExtract_long(Buf, 0, '|');
1787                 if (!force_download) {
1788                         StrBufExtract_token(ContentType, Buf, 3, '|');
1789                 }
1790
1791                 read_server_binary(WCC->WBuf, bytes, Buf);
1792                 serv_puts("CLOS");
1793                 StrBuf_ServGetln(Buf);
1794                 CT = ChrPtr(ContentType);
1795
1796                 if (!force_download) {
1797                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1798                                 StrBufExtract_token(Buf, WCC->Hdr->HR.ReqLine, 2, '/');
1799                                 CT = GuessMimeByFilename(SKEY(Buf));
1800                         }
1801                         if (!strcasecmp(ChrPtr(ContentType), "application/octet-stream")) {
1802                                 CT = GuessMimeType(SKEY(WCC->WBuf));
1803                         }
1804                 }
1805                 http_transmit_thing(CT, 0);
1806         } else {
1807                 StrBufCutLeft(Buf, 4);
1808                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(Buf));
1809                 output_headers(0, 0, 0, 0, 0, 0);
1810                 hprintf("Content-Type: text/plain\r\n");
1811                 wprintf(_("An error occurred while retrieving this part: %s\n"), 
1812                         ChrPtr(Buf));
1813                 end_burst();
1814         }
1815         FreeStrBuf(&ContentType);
1816         FreeStrBuf(&Buf);
1817 }
1818
1819
1820 /*
1821  * Read any MIME part of a message, from the server, into memory.
1822  */
1823 StrBuf *load_mimepart(long msgnum, char *partnum)
1824 {
1825         off_t bytes;
1826         StrBuf *Buf;
1827         
1828         Buf = NewStrBuf();
1829         serv_printf("DLAT %ld|%s", msgnum, partnum);
1830         StrBuf_ServGetln(Buf);
1831         if (GetServerStatus(Buf, NULL) == 6) {
1832                 StrBufCutLeft(Buf, 4);
1833                 bytes = StrBufExtract_long(Buf, 0, '|');
1834                 FreeStrBuf(&Buf);
1835                 Buf = NewStrBuf();
1836                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1837                 return(Buf);
1838         }
1839         else {
1840                 FreeStrBuf(&Buf);
1841                 return(NULL);
1842         }
1843 }
1844
1845 /*
1846  * Read any MIME part of a message, from the server, into memory.
1847  */
1848 void MimeLoadData(wc_mime_attachment *Mime)
1849 {
1850         StrBuf *Buf;
1851         off_t bytes;
1852         /* TODO: is there a chance the content type is different from the one we know? */
1853         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1854         Buf = NewStrBuf();
1855         StrBuf_ServGetln(Buf);
1856         if (GetServerStatus(Buf, NULL) == 6) {
1857                 bytes = extract_long(&(ChrPtr(Buf)[4]), 0);
1858                                      
1859                 if (Mime->Data == NULL)
1860                         Mime->Data = NewStrBufPlain(NULL, bytes);
1861                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1862         }
1863         else {
1864                 FlushStrBuf(Mime->Data);
1865                 /* TODO XImportant message */
1866         }
1867         FreeStrBuf(&Buf);
1868 }
1869
1870
1871
1872
1873 void view_mimepart(void) {
1874         mimepart(0);
1875 }
1876
1877 void download_mimepart(void) {
1878         mimepart(1);
1879 }
1880
1881 void view_postpart(void) {
1882         StrBuf *filename = NewStrBuf();
1883         StrBuf *partnum = NewStrBuf();
1884
1885         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1886         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1887
1888         postpart(partnum, filename, 0);
1889
1890         FreeStrBuf(&filename);
1891         FreeStrBuf(&partnum);
1892 }
1893
1894 void download_postpart(void) {
1895         StrBuf *filename = NewStrBuf();
1896         StrBuf *partnum = NewStrBuf();
1897
1898         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1899         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1900
1901         postpart(partnum, filename, 1);
1902
1903         FreeStrBuf(&filename);
1904         FreeStrBuf(&partnum);
1905 }
1906
1907 void h_readnew(void) { readloop(readnew);}
1908 void h_readold(void) { readloop(readold);}
1909 void h_readfwd(void) { readloop(readfwd);}
1910 void h_headers(void) { readloop(headers);}
1911 void h_do_search(void) { readloop(do_search);}
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("do_search"), h_do_search, 0);
1971         WebcitAddUrlHandler(HKEY("display_enter"), display_enter, 0);
1972         WebcitAddUrlHandler(HKEY("post"), post_message, 0);
1973         WebcitAddUrlHandler(HKEY("move_msg"), move_msg, 0);
1974         WebcitAddUrlHandler(HKEY("delete_msg"), delete_msg, 0);
1975         WebcitAddUrlHandler(HKEY("confirm_move_msg"), confirm_move_msg, 0);
1976         WebcitAddUrlHandler(HKEY("msg"), embed_message, NEED_URL);
1977         WebcitAddUrlHandler(HKEY("message"), handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1978         WebcitAddUrlHandler(HKEY("printmsg"), print_message, NEED_URL);
1979         WebcitAddUrlHandler(HKEY("mobilemsg"), mobile_message_view, NEED_URL);
1980         WebcitAddUrlHandler(HKEY("msgheaders"), display_headers, NEED_URL);
1981
1982         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1983         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1984         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
1985         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
1986
1987         /* json */
1988         WebcitAddUrlHandler(HKEY("roommsgs"), jsonMessageList,0);
1989         return ;
1990 }
1991
1992 void
1993 SessionDetachModule_MSG
1994 (wcsession *sess)
1995 {
1996         DeleteHash(&sess->summ);
1997 }