* Style cleanup
[citadel.git] / webcit / messages.c
1 /*
2  * $Id$
3  *
4  * Functions which deal with the fetching and displaying of messages.
5  *
6  */
7
8 #include "webcit.h"
9 #include "webserver.h"
10 #include "groupdav.h"
11
12 HashList *MsgHeaderHandler = NULL;
13 HashList *MsgEvaluators = NULL;
14 HashList *MimeRenderHandler = NULL;
15 int dbg_analyze_msg = 0;
16
17 #define SUBJ_COL_WIDTH_PCT              50      /* Mailbox view column width */
18 #define SENDER_COL_WIDTH_PCT            30      /* Mailbox view column width */
19 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /* Mailbox view column width */
20
21 void jsonMessageListHdr(void);
22
23 void display_enter(void);
24
25 typedef void (*MsgPartEvaluatorFunc)(message_summary *Sum, StrBuf *Buf);
26
27 typedef struct _MsgPartEvaluatorStruct {
28         MsgPartEvaluatorFunc f;
29 } MsgPartEvaluatorStruct;
30
31 int load_message(message_summary *Msg, 
32                  StrBuf *FoundCharset,
33                  StrBuf **Error)
34 {
35         wcsession *WCC = WC;
36         StrBuf *Buf;
37         StrBuf *HdrToken;
38         headereval *Hdr;
39         void *vHdr;
40         char buf[SIZ];
41         int Done = 0;
42         int state=0;
43         
44         Buf = NewStrBuf();
45         lprintf(9, "MSG4 %ld|%s\n", Msg->msgnum, ChrPtr(Msg->PartNum));
46         if (Msg->PartNum != NULL) {
47                 serv_printf("MSG4 %ld|%s", Msg->msgnum, ChrPtr(Msg->PartNum));
48         }
49         else {
50                 serv_printf("MSG4 %ld", Msg->msgnum);
51         }
52
53         StrBuf_ServGetln(Buf);
54         if (GetServerStatus(Buf, NULL) != 1) {
55                 *Error = NewStrBuf();
56                 StrBufAppendPrintf(*Error, "<strong>");
57                 StrBufAppendPrintf(*Error, _("ERROR:"));
58                 StrBufAppendPrintf(*Error, "</strong> %s<br />\n", &buf[4]);
59                 FreeStrBuf(&Buf);
60                 return 0;
61         }
62
63         /* begin everythingamundo table */
64         HdrToken = NewStrBuf();
65         while ((StrBuf_ServGetln(Buf)>=0) && !Done) {
66                 if ( (StrLength(Buf)==3) && 
67                     !strcmp(ChrPtr(Buf), "000")) 
68                 {
69                         Done = 1;
70                         if (state < 2) {
71                                 lprintf(1, _("unexpected end of message"));
72                                 if (Msg->MsgBody->Data == NULL)
73                                         Msg->MsgBody->Data = NewStrBuf();
74                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
75                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
76                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("unexpected end of message"));
77                                 StrBufAppendPrintf(Msg->MsgBody->Data, " (1)</i><br /><br />\n");
78                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
79                         }
80                         break;
81                 }
82                 switch (state) {
83                 case 0:/* Citadel Message Headers */
84                         if (StrLength(Buf) == 0) {
85                                 state ++;
86                                 break;
87                         }
88                         StrBufExtract_token(HdrToken, Buf, 0, '=');
89                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
90                         
91 #ifdef TECH_PREVIEW
92                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
93 #endif
94                         /* look up one of the examine_* functions to parse the content */
95                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
96                             (vHdr != NULL)) {
97                                 Hdr = (headereval*)vHdr;
98                                 Hdr->evaluator(Msg, Buf, FoundCharset);
99                                 if (Hdr->Type == 1) {
100                                         state++;
101                                 }
102                         }/* TODO: 
103                         else LogError(Target, 
104                                       __FUNCTION__,  
105                                       "don't know how to handle message header[%s]\n", 
106                                       ChrPtr(HdrToken));
107                          */
108                         break;
109                 case 1:/* Message Mime Header */
110                         if (StrLength(Buf) == 0) {
111                                 state++;
112                                 if (Msg->MsgBody->ContentType == NULL)
113                                         /* end of header or no header? */
114                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
115                                  /* usual end of mime header */
116                         }
117                         else
118                         {
119                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
120                                 if (StrLength(HdrToken) > 0) {
121                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
122 #ifdef TECH_PREVIEW
123                                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
124 #endif
125                                         /* the examine*'s know how to do with mime headers too... */
126                                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
127                                             (vHdr != NULL)) {
128                                                 Hdr = (headereval*)vHdr;
129                                                 Hdr->evaluator(Msg, Buf, FoundCharset);
130                                         }
131                                         break;
132                                 }
133                         }
134                 case 2: /* Message Body */
135                         
136                         if (Msg->MsgBody->size_known > 0) {
137                                 StrBuf_ServGetBLOBBuffered(Msg->MsgBody->Data, Msg->MsgBody->length);
138                                 state ++;
139                                 /*/ todo: check next line, if not 000, append following lines */
140                         }
141                         else if (1){
142                                 if (StrLength(Msg->MsgBody->Data) > 0)
143                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
144                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
145                         }
146                         break;
147                 case 3:
148                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
149                         break;
150                 }
151         }
152
153         if (Msg->AllAttach == NULL)
154                 Msg->AllAttach = NewHash(1,NULL);
155         /* now we put the body mimepart we read above into the mimelist */
156         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
157         
158         /* Generate a reply-to address */
159         if (StrLength(Msg->Rfca) > 0) {
160                 if (Msg->reply_to == NULL)
161                         Msg->reply_to = NewStrBuf();
162                 if (StrLength(Msg->from) > 0) {
163                         StrBufPrintf(Msg->reply_to, "%s <%s>", ChrPtr(Msg->from), ChrPtr(Msg->Rfca));
164                 }
165                 else {
166                         FlushStrBuf(Msg->reply_to);
167                         StrBufAppendBuf(Msg->reply_to, Msg->Rfca, 0);
168                 }
169         }
170         else 
171         {
172                 if ((StrLength(Msg->OtherNode)>0) && 
173                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_nodename))) &&
174                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_humannode)) ))
175                 {
176                         if (Msg->reply_to == NULL)
177                                 Msg->reply_to = NewStrBuf();
178                         StrBufPrintf(Msg->reply_to, 
179                                      "%s @ %s",
180                                      ChrPtr(Msg->from), 
181                                      ChrPtr(Msg->OtherNode));
182                 }
183                 else {
184                         if (Msg->reply_to == NULL)
185                                 Msg->reply_to = NewStrBuf();
186                         FlushStrBuf(Msg->reply_to);
187                         StrBufAppendBuf(Msg->reply_to, Msg->from, 0);
188                 }
189         }
190         FreeStrBuf(&Buf);
191         FreeStrBuf(&HdrToken);
192         return 1;
193 }
194
195
196
197 /*
198  * I wanna SEE that message!
199  *
200  * msgnum               Message number to display
201  * printable_view       Nonzero to display a printable view
202  * section              Optional for encapsulated message/rfc822 submessage
203  */
204 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, const StrBuf *PartNum, const StrBuf **OutMime) 
205 {
206         StrBuf *Buf;
207         StrBuf *FoundCharset;
208         HashPos  *it;
209         void *vMime;
210         message_summary *Msg = NULL;
211         void *vHdr;
212         long len;
213         const char *Key;
214         WCTemplputParams SubTP;
215         StrBuf *Error = NULL;
216
217         Buf = NewStrBuf();
218         FoundCharset = NewStrBuf();
219         Msg = (message_summary *)malloc(sizeof(message_summary));
220         memset(Msg, 0, sizeof(message_summary));
221         Msg->msgnum = msgnum;
222         Msg->PartNum = PartNum;
223         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
224         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
225         Msg->MsgBody->msgnum = msgnum;
226
227         if (!load_message(Msg, FoundCharset, &Error)) {
228                 StrBufAppendBuf(Target, Error, 0);
229                 FreeStrBuf(&Error);
230         }
231
232         /* strip the bare contenttype, so we ommit charset etc. */
233         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
234         StrBufTrim(Buf);
235         StrBufLowerCase(Buf);
236         /* look up the renderer, that will convert this mimeitem into the htmlized form */
237         if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
238             (vHdr != NULL)) {
239                 RenderMimeFuncStruct *Render;
240                 Render = (RenderMimeFuncStruct*)vHdr;
241                 Render->f(Msg->MsgBody, NULL, FoundCharset);
242         }
243
244         if (StrLength(Msg->reply_references)> 0) {
245                 /* Trim down excessively long lists of thread references.  We eliminate the
246                  * second one in the list so that the thread root remains intact.
247                  */
248                 int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
249                 int rrlen = StrLength(Msg->reply_references);
250                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
251                         StrBufRemove_token(Msg->reply_references, 1, '|');
252                 }
253         }
254
255         /* now check if we need to translate some mimeparts, and remove the duplicate */
256         it = GetNewHashPos(Msg->AllAttach, 0);
257         while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
258                (vMime != NULL)) {
259                 wc_mime_attachment *Mime = (wc_mime_attachment*) vMime;
260                 evaluate_mime_part(Msg, Mime);
261         }
262         DeleteHashPos(&it);
263         memset(&SubTP, 0, sizeof(WCTemplputParams));
264         SubTP.Filter.ContextType = CTX_MAILSUM;
265         SubTP.Context = Msg;
266         *OutMime = DoTemplate(tmpl, tmpllen, Target, &SubTP);
267
268         DestroyMessageSummary(Msg);
269         FreeStrBuf(&FoundCharset);
270         FreeStrBuf(&Buf);
271         return 1;
272 }
273
274
275 void
276 HttpStatus(long CitadelStatus)
277 {
278         long httpstatus = 502;
279         
280         switch (MAJORCODE(CitadelStatus))
281         {
282         case LISTING_FOLLOWS:
283         case CIT_OK:
284                 httpstatus = 201;
285                 break;
286         case ERROR:
287                 switch (MINORCODE(CitadelStatus))
288                 {
289                 case INTERNAL_ERROR:
290                         httpstatus = 403;
291                         break;
292                         
293                 case TOO_BIG:
294                 case ILLEGAL_VALUE:
295                 case HIGHER_ACCESS_REQUIRED:
296                 case MAX_SESSIONS_EXCEEDED:
297                 case RESOURCE_BUSY:
298                 case RESOURCE_NOT_OPEN:
299                 case NOT_HERE:
300                 case INVALID_FLOOR_OPERATION:
301                 case FILE_NOT_FOUND:
302                 case ROOM_NOT_FOUND:
303                         httpstatus = 409;
304                         break;
305
306                 case MESSAGE_NOT_FOUND:
307                 case ALREADY_EXISTS:
308                         httpstatus = 403;
309                         break;
310
311                 case NO_SUCH_SYSTEM:
312                         httpstatus = 502;
313                         break;
314
315                 default:
316                 case CMD_NOT_SUPPORTED:
317                 case PASSWORD_REQUIRED:
318                 case ALREADY_LOGGED_IN:
319                 case USERNAME_REQUIRED:
320                 case NOT_LOGGED_IN:
321                 case SERVER_SHUTTING_DOWN:
322                 case NO_SUCH_USER:
323                 case ASYNC_GEXP:
324                         httpstatus = 502;
325                         break;
326                 }
327                 break;
328
329         default:
330         case BINARY_FOLLOWS:
331         case SEND_BINARY:
332         case START_CHAT_MODE:
333         case ASYNC_MSG:
334         case MORE_DATA:
335         case SEND_LISTING:
336                 httpstatus = 502; /* aeh... whut? */
337                 break;
338         }
339
340
341 }
342
343 /*
344  * Unadorned HTML output of an individual message, suitable
345  * for placing in a hidden iframe, for printing, or whatever
346  */
347 void handle_one_message(void) 
348 {
349         long CitStatus;
350         int CopyMessage = 0;
351         const StrBuf *Destination;
352         void *vLine;
353         const StrBuf *Mime;
354         long msgnum = 0L;
355         wcsession *WCC = WC;
356         const StrBuf *Tmpl;
357         StrBuf *CmdBuf = NULL;
358         const char *pMsg;
359
360
361         pMsg = strchr(ChrPtr(WCC->Hdr->HR.ReqLine), '/');
362         if (pMsg == NULL) {
363                 HttpStatus(CitStatus);
364                 return;
365         }
366
367         msgnum = atol(pMsg + 1);
368         StrBufCutAt(WCC->Hdr->HR.ReqLine, 0, pMsg);
369         gotoroom(WCC->Hdr->HR.ReqLine);
370         switch (WCC->Hdr->HR.eReqType)
371         {
372         case eGET:
373         case ePOST:
374                 Tmpl = sbstr("template");
375                 if (StrLength(Tmpl) > 0) 
376                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime);
377                 else 
378                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
379                 http_transmit_thing(ChrPtr(Mime), 0);
380                 break;
381         case eDELETE:
382                 CmdBuf = NewStrBuf ();
383                 if (WCC->wc_is_trash) { /* Delete from Trash is a real delete */
384                         serv_printf("DELE %ld", msgnum);        
385                 }
386                 else {                  /* Otherwise move it to Trash */
387                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
388                 }
389                 StrBuf_ServGetln(CmdBuf);
390                 FlushStrBuf(WCC->ImportantMsg);
391                 StrBufAppendBuf(WCC->ImportantMsg, CmdBuf, 4);
392                 GetServerStatus(CmdBuf, &CitStatus);
393                 HttpStatus(CitStatus);
394                 break;
395         case eCOPY:
396                 CopyMessage = 1;
397         case eMOVE:
398                 if (GetHash(WCC->Hdr->HTTPHeaders, HKEY("DESTINATION"), &vLine) &&
399                     (vLine!=NULL)) {
400                         Destination = (StrBuf*) vLine;
401                         serv_printf("MOVE %ld|%s|%d", msgnum, ChrPtr(Destination), CopyMessage);
402                         StrBuf_ServGetln(CmdBuf);
403                         FlushStrBuf(WCC->ImportantMsg);
404                         StrBufAppendBuf(WCC->ImportantMsg, CmdBuf, 4);
405                         GetServerStatus(CmdBuf, &CitStatus);
406                         HttpStatus(CitStatus);
407                 }
408                 else
409                         HttpStatus(500);
410                 break;
411         default:
412                 break;
413
414         }
415 }
416
417
418 /*
419  * Unadorned HTML output of an individual message, suitable
420  * for placing in a hidden iframe, for printing, or whatever
421  */
422 void embed_message(void) {
423         const StrBuf *Mime;
424         long msgnum = 0L;
425         wcsession *WCC = WC;
426         const StrBuf *Tmpl;
427         StrBuf *CmdBuf = NULL;
428
429         msgnum = StrBufExtract_long(WCC->Hdr->HR.ReqLine, 0, '/');
430         switch (WCC->Hdr->HR.eReqType)
431         {
432         case eGET:
433         case ePOST:
434                 Tmpl = sbstr("template");
435                 if (StrLength(Tmpl) > 0) 
436                         read_message(WCC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime);
437                 else 
438                         read_message(WCC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
439                 http_transmit_thing(ChrPtr(Mime), 0);
440                 break;
441         case eDELETE:
442                 CmdBuf = NewStrBuf ();
443                 if (WCC->wc_is_trash) { /* Delete from Trash is a real delete */
444                         serv_printf("DELE %ld", msgnum);        
445                 }
446                 else {                  /* Otherwise move it to Trash */
447                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
448                 }
449                 StrBuf_ServGetln(CmdBuf);
450                 FlushStrBuf(WCC->ImportantMsg);
451                 StrBufAppendBuf(WCC->ImportantMsg, CmdBuf, 4);
452                 break;
453         default:
454                 break;
455
456         }
457 }
458
459
460 /*
461  * Printable view of a message
462  */
463 void print_message(void) {
464         long msgnum = 0L;
465         const StrBuf *Mime;
466
467         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
468         output_headers(0, 0, 0, 0, 0, 0);
469
470         hprintf("Content-type: text/html\r\n"
471                 "Server: " PACKAGE_STRING "\r\n"
472                 "Connection: close\r\n");
473
474         begin_burst();
475
476         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, NULL, &Mime);
477
478         wDumpContent(0);
479 }
480
481 /* 
482  * Mobile browser view of message
483  */
484 void mobile_message_view(void) 
485 {
486         long msgnum = 0L;
487         const StrBuf *Mime;
488   
489         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
490         output_headers(1, 0, 0, 0, 0, 1);
491         begin_burst();
492         do_template("msgcontrols", NULL);
493         read_message(WC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime);
494         wDumpContent(0);
495 }
496
497 /*
498  * Display a message's headers
499  */
500 void display_headers(void) {
501         long msgnum = 0L;
502         char buf[1024];
503
504         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
505         output_headers(0, 0, 0, 0, 0, 0);
506
507         hprintf("Content-type: text/plain\r\n"
508                 "Server: %s\r\n"
509                 "Connection: close\r\n",
510                 PACKAGE_STRING);
511         begin_burst();
512
513         serv_printf("MSG2 %ld|3", msgnum);
514         serv_getln(buf, sizeof buf);
515         if (buf[0] == '1') {
516                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
517                         wprintf("%s\n", buf);
518                 }
519         }
520
521         wDumpContent(0);
522 }
523
524
525 message_summary *ReadOneMessageSummary(StrBuf *RawMessage, const char *DefaultSubject, long MsgNum) 
526 {
527         void                 *vEval;
528         MsgPartEvaluatorStruct  *Eval;
529         message_summary      *Msg;
530         StrBuf *Buf;
531         const char *buf;
532         const char *ebuf;
533         int nBuf;
534         long len;
535         
536         Buf = NewStrBuf();
537
538         serv_printf("MSG0 %ld|1", MsgNum);      /* ask for headers only */
539         
540         StrBuf_ServGetln(Buf);
541         if (GetServerStatus(Buf, NULL) == 1) {
542                 FreeStrBuf(&Buf);
543                 return NULL;
544         }
545
546         Msg = (message_summary*)malloc(sizeof(message_summary));
547         memset(Msg, 0, sizeof(message_summary));
548         while (len = StrBuf_ServGetln(Buf),
549                ((len != 3)  ||
550                 strcmp(ChrPtr(Buf), "000")== 0)){
551                 buf = ChrPtr(Buf);
552                 ebuf = strchr(ChrPtr(Buf), '=');
553                 nBuf = ebuf - buf;
554                 if (GetHash(MsgEvaluators, buf, nBuf, &vEval) && vEval != NULL) {
555                         Eval = (MsgPartEvaluatorStruct*) vEval;
556                         StrBufCutLeft(Buf, nBuf + 1);
557                         Eval->f(Msg, Buf);
558                 }
559                 else lprintf(1, "Don't know how to handle Message Headerline [%s]", ChrPtr(Buf));
560         }
561         return Msg;
562 }
563
564
565
566
567
568 /*
569  * load message pointers from the server for a "read messages" operation
570  *
571  * servcmd:             the citadel command to send to the citserver
572  * with_headers:        also include some of the headers with the message numbers (more expensive)
573  */
574 int load_msg_ptrs(const char *servcmd, int with_headers)
575 {
576         StrBuf* FoundCharset = NULL;
577         wcsession *WCC = WC;
578         message_summary *Msg;
579         StrBuf *Buf, *Buf2;
580         int nummsgs = 0;
581         int maxload = 0;
582         long len;
583         int n;
584         int skipit;
585         const char *Ptr = NULL;
586
587         if (WCC->summ != NULL) {
588                 DeleteHash(&WCC->summ);
589         }
590         WCC->summ = NewHash(1, Flathash);
591         maxload = 10000;
592         
593         Buf = NewStrBuf();
594         serv_puts(servcmd);
595         StrBuf_ServGetln(Buf);
596         if (GetServerStatus(Buf, NULL) != 1) {
597                 FreeStrBuf(&Buf);
598                 return (nummsgs);
599         }
600         Buf2 = NewStrBuf();
601         while (len = StrBuf_ServGetln(Buf),
602                ((len != 3)  ||
603                 strcmp(ChrPtr(Buf), "000")!= 0))
604         {
605                 if (nummsgs < maxload) {
606                         skipit = 0;
607                         Ptr = NULL;
608                         Msg = (message_summary*)malloc(sizeof(message_summary));
609                         memset(Msg, 0, sizeof(message_summary));
610
611                         Msg->msgnum = StrBufExtractNext_long(Buf, &Ptr, '|');
612                         Msg->date = StrBufExtractNext_long(Buf, &Ptr, '|');
613
614                         if ((Msg->msgnum == 0) && (StrLength(Buf) < 32)) {
615                                 free(Msg);
616                                 continue;
617                         }
618                         /* 
619                          * as citserver probably gives us messages in forward date sorting
620                          * nummsgs should be the same order as the message date.
621                          */
622                         if (Msg->date == 0) {
623                                 Msg->date = nummsgs;
624                                 if (StrLength(Buf) < 32) 
625                                         skipit = 1;
626                         }
627                         if (!skipit) {
628                                 Msg->from = NewStrBufPlain(NULL, StrLength(Buf));
629                                 StrBufExtract_NextToken(Buf2, Buf, &Ptr, '|');
630                                 if (StrLength(Buf2) != 0) {
631                                         /* Handle senders with RFC2047 encoding */
632                                         StrBuf_RFC822_to_Utf8(Msg->from, Buf2, WCC->DefaultCharset, FoundCharset);
633                                 }
634                         
635                                 /* node name */
636                                 StrBufExtract_NextToken(Buf2, Buf, &Ptr, '|');
637                                 if ((StrLength(Buf2) !=0 ) &&
638                                     ( ((WCC->room_flags & QR_NETWORK)
639                                        || ((strcasecmp(ChrPtr(Buf2), ChrPtr(WCC->serv_info->serv_nodename))
640                                             && (strcasecmp(ChrPtr(Buf2), ChrPtr(WCC->serv_info->serv_fqdn))))))))
641                                 {
642                                         StrBufAppendBufPlain(Msg->from, HKEY(" @ "), 0);
643                                         StrBufAppendBuf(Msg->from, Buf2, 0);
644                                 }
645
646                                 /* Internet address (not used)
647                                  *      StrBufExtract_token(Msg->inetaddr, Buf, 4, '|');
648                                  */
649                                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 1);
650                                 Msg->subj = NewStrBufPlain(NULL, StrLength(Buf));
651                                 StrBufExtract_NextToken(Buf2,  Buf, &Ptr, '|');
652                                 if (StrLength(Buf2) == 0)
653                                         StrBufAppendBufPlain(Msg->subj, _("(no subject)"), -1,0);
654                                 else {
655                                         StrBuf_RFC822_to_Utf8(Msg->subj, Buf2, WCC->DefaultCharset, FoundCharset);
656                                         if ((StrLength(Msg->subj) > 75) && 
657                                             (StrBuf_Utf8StrLen(Msg->subj) > 75)) {
658                                                 StrBuf_Utf8StrCut(Msg->subj, 72);
659                                                 StrBufAppendBufPlain(Msg->subj, HKEY("..."), 0);
660                                         }
661                                 }
662
663                                 if ((StrLength(Msg->from) > 25) && 
664                                     (StrBuf_Utf8StrLen(Msg->from) > 25)) {
665                                         StrBuf_Utf8StrCut(Msg->from, 23);
666                                         StrBufAppendBufPlain(Msg->from, HKEY("..."), 0);
667                                 }
668                         }
669                         n = Msg->msgnum;
670                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
671                 }
672                 nummsgs++;
673         }
674         FreeStrBuf(&Buf2);
675         FreeStrBuf(&Buf);
676         return (nummsgs);
677 }
678
679
680 inline message_summary* GetMessagePtrAt(int n, HashList *Summ)
681 {
682         const char *Key;
683         long HKLen;
684         void *vMsg;
685
686         if (Summ == NULL)
687                 return NULL;
688         GetHashAt(Summ, n, &HKLen, &Key, &vMsg);
689         return (message_summary*) vMsg;
690 }
691
692
693 long DrawMessageDropdown(StrBuf *Selector, long maxmsgs, long startmsg, int nMessages)
694 {
695         StrBuf *TmpBuf;
696         wcsession *WCC = WC;
697         void *vMsg;
698         int lo, hi;
699         long ret;
700         long hklen;
701         const char *key;
702         int done = 0;
703         int nItems;
704         HashPos *At;
705         long vector[16];
706         WCTemplputParams SubTP;
707
708         memset(&SubTP, 0, sizeof(WCTemplputParams));
709         SubTP.Filter.ContextType = CTX_LONGVECTOR;
710         SubTP.Context = &vector;
711         TmpBuf = NewStrBufPlain(NULL, SIZ);
712         At = GetNewHashPos(WCC->summ, nMessages);
713         nItems = GetCount(WCC->summ);
714         ret = nMessages;
715         vector[0] = 7;
716         vector[2] = 1;
717         vector[1] = startmsg;
718         vector[3] = 0;
719
720         while (!done) {
721                 vector[3] = abs(nMessages);
722                 lo = GetHashPosCounter(At);
723                 if (nMessages > 0) {
724                         if (lo + nMessages >= nItems) {
725                                 hi = nItems - 1;
726                                 vector[3] = nItems - lo;
727                                 if (startmsg == lo) 
728                                         ret = vector[3];
729                         }
730                         else {
731                                 hi = lo + nMessages - 1;
732                         }
733                 } else {
734                         if (lo + nMessages < -1) {
735                                 hi = 0;
736                         }
737                         else {
738                                 if ((lo % abs(nMessages)) != 0) {
739                                         int offset = (lo % abs(nMessages) *
740                                                       (nMessages / abs(nMessages)));
741                                         hi = lo + offset;
742                                         vector[3] = abs(offset);
743                                         if (startmsg == lo)
744                                                  ret = offset;
745                                 }
746                                 else
747                                         hi = lo + nMessages;
748                         }
749                 }
750                 done = !GetNextHashPos(WCC->summ, At, &hklen, &key, &vMsg);
751                 
752                 /*
753                  * Bump these because although we're thinking in zero base, the user
754                  * is a drooling idiot and is thinking in one base.
755                  */
756                 vector[4] = lo + 1;
757                 vector[5] = hi + 1;
758                 vector[6] = lo;
759                 FlushStrBuf(TmpBuf);
760                 dbg_print_longvector(vector);
761                 DoTemplate(HKEY("select_messageindex"), TmpBuf, &SubTP);
762                 StrBufAppendBuf(Selector, TmpBuf, 0);
763         }
764         vector[6] = 0;
765         FlushStrBuf(TmpBuf);
766         if (maxmsgs == 9999999) {
767                 vector[1] = 1;
768                 ret = maxmsgs;
769         }
770         else
771                 vector[1] = 0;          
772         vector[2] = 0;
773         dbg_print_longvector(vector);
774         DoTemplate(HKEY("select_messageindex_all"), TmpBuf, &SubTP);
775         StrBufAppendBuf(Selector, TmpBuf, 0);
776         FreeStrBuf(&TmpBuf);
777         DeleteHashPos(&At);
778         return ret;
779 }
780
781 void load_seen_flags(void)
782 {
783         message_summary *Msg;
784         const char *HashKey;
785         long HKLen;
786         HashPos *at;
787         void *vMsg;
788         StrBuf *OldMsg;
789         wcsession *WCC = WC;
790
791         OldMsg = NewStrBuf();
792         serv_puts("GTSN");
793         StrBuf_ServGetln(OldMsg);
794         if (GetServerStatus(OldMsg, NULL) == 2) {
795                 StrBufCutLeft(OldMsg, 4);
796         }
797         else {
798                 FreeStrBuf(&OldMsg);
799                 return;
800         }
801         at = GetNewHashPos(WCC->summ, 0);
802         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
803                 /* Are you a new message, or an old message? */
804                 Msg = (message_summary*) vMsg;
805                 if (is_msg_in_mset(ChrPtr(OldMsg), Msg->msgnum)) {
806                         Msg->is_new = 0;
807                 }
808                 else {
809                         Msg->is_new = 1;
810                 }
811         }
812         FreeStrBuf(&OldMsg);
813         DeleteHashPos(&at);
814 }
815
816 extern readloop_struct rlid[];
817
818 /*
819  * command loop for reading messages
820  *
821  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt"
822  */
823 void readloop(long oper)
824 {
825         StrBuf *MessageDropdown = NULL;
826         StrBuf *BBViewToolBar = NULL;
827         void *vMsg;
828         message_summary *Msg;
829         char cmd[256] = "";
830         char buf[SIZ];
831         int a = 0;
832         int with_headers = 0;
833         int nummsgs;
834         long startmsg = 0;
835         int maxmsgs = 0;
836         long *displayed_msgs = NULL;
837         int num_displayed = 0;
838         int is_singlecard = 0;
839         struct calview calv;
840         int i;
841         int lowest_displayed = (-1);
842         int highest_displayed = 0;
843         addrbookent *addrbook = NULL;
844         int num_ab = 0;
845         int bbs_reverse = 0;
846         wcsession *WCC = WC;
847         HashPos *at;
848         const char *HashKey;
849         long HKLen;
850         int care_for_empty_list = 0;
851         int load_seen = 0;
852         int sortit = 0;
853         int defaultsortorder = 0;
854         WCTemplputParams SubTP;
855         char *ab_name;
856         const StrBuf *Mime;
857
858         if (havebstr("is_summary") && (1 == (ibstr("is_summary"))))
859                 WCC->wc_view = VIEW_MAILBOX;
860
861         if (!WCC->is_ajax) {
862                 output_headers(1, 1, 1, 0, 0, 0);
863         } else if (WCC->wc_view == VIEW_MAILBOX) {
864                 jsonMessageListHdr();
865         }
866
867         switch (WCC->wc_view) {
868         case VIEW_WIKI:
869                 sprintf(buf, "wiki?room=%s&page=home", ChrPtr(WCC->wc_roomname));
870                 http_redirect(buf);
871                 return;
872         case VIEW_CALBRIEF:
873         case VIEW_CALENDAR:
874                 load_seen = 1;
875                 strcpy(cmd, "MSGS ALL");
876                 maxmsgs = 32767;
877                 parse_calendar_view_request(&calv);
878                 break;
879         case VIEW_TASKS:
880                 strcpy(cmd, "MSGS ALL");
881                 maxmsgs = 32767;
882                 break;
883         case VIEW_NOTES:
884                 strcpy(cmd, "MSGS ALL");
885                 maxmsgs = 32767;
886                 wprintf("<div id=\"new_notes_here\"></div>\n");
887                 break;
888         case VIEW_ADDRESSBOOK:
889                 is_singlecard = ibstr("is_singlecard");
890                 if (is_singlecard != 1) {
891                         if (oper == do_search) {
892                                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
893                         }
894                         else {
895                                 strcpy(cmd, "MSGS ALL");
896                         }
897                         maxmsgs = 9999999;
898                         break;
899                 }
900                 break;
901         case VIEW_MAILBOX: 
902           if (!WCC->is_ajax) {
903             new_summary_view();
904             return;
905           } else {
906                 defaultsortorder = 2;
907                 sortit = 1;
908                 load_seen = 1;
909                 care_for_empty_list = 0;
910                 with_headers = 1;
911                 /* Generally using maxmsgs|startmsg is not required
912                    in mailbox view, but we have a 'safemode' for clients
913                    (*cough* Exploder) that simply can't handle too many */
914                 if (havebstr("maxmsgs")) maxmsgs = ibstr("maxmsgs");
915                 else maxmsgs = 9999999;
916                 if (havebstr("startmsg")) startmsg = lbstr("startmsg");
917                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
918                          (oper == do_search) ? "SEARCH" : "ALL",
919                          (oper == do_search) ? bstr("query") : ""
920                         );
921           }
922                 break;
923         case VIEW_BBS:
924         default:
925                 defaultsortorder = 1;
926                 startmsg = -1;
927                 sortit = 1;
928                 care_for_empty_list = 1;
929
930                 rlid[oper].cmd(cmd, sizeof(cmd));
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 void h_readgt(void) { readloop(readgt);}
1913
1914 void jsonMessageListHdr(void) 
1915 {
1916         /* TODO: make a generic function */
1917         hprintf("HTTP/1.1 200 OK\r\n");
1918         hprintf("Content-type: application/json; charset=utf-8\r\n");
1919         hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1920         hprintf("Connection: close\r\n");
1921         hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1922         begin_burst();
1923 }
1924
1925 /* Spit out the new summary view. This is basically a static page, so clients can cache the layout, all the dirty work is javascript :) */
1926 void new_summary_view(void) {
1927         begin_burst();
1928         DoTemplate(HKEY("msg_listview"),NULL,&NoCtx);
1929         DoTemplate(HKEY("trailing"),NULL,&NoCtx);
1930         end_burst();
1931 }
1932
1933 /* Output message list in JSON format */
1934 void jsonMessageList(void) {
1935         const StrBuf *room = sbstr("room");
1936         long oper = (havebstr("query")) ? do_search : readnew;
1937         WC->is_ajax = 1; 
1938         gotoroom(room);
1939         readloop(oper);
1940         WC->is_ajax = 0;
1941 }
1942
1943 void 
1944 InitModule_MSG
1945 (void)
1946 {
1947         RegisterPreference("use_sig",
1948                            _("Attach signature to email messages?"), 
1949                            PRF_YESNO, 
1950                            NULL);
1951         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1952         RegisterPreference("default_header_charset", 
1953                            _("Default character set for email headers:"), 
1954                            PRF_STRING, 
1955                            NULL);
1956         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1957         RegisterPreference("defaultname", 
1958                            _("Preferred display name for email messages"), 
1959                            PRF_STRING, 
1960                            NULL);
1961         RegisterPreference("defaulthandle", 
1962                            _("Preferred display name for bulletin board posts"), 
1963                            PRF_STRING, 
1964                            NULL);
1965         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1966
1967         WebcitAddUrlHandler(HKEY("readnew"), h_readnew, NEED_URL);
1968         WebcitAddUrlHandler(HKEY("readold"), h_readold, NEED_URL);
1969         WebcitAddUrlHandler(HKEY("readfwd"), h_readfwd, NEED_URL);
1970         WebcitAddUrlHandler(HKEY("headers"), h_headers, NEED_URL);
1971         WebcitAddUrlHandler(HKEY("readgt"), h_readgt, NEED_URL);
1972         WebcitAddUrlHandler(HKEY("do_search"), h_do_search, 0);
1973         WebcitAddUrlHandler(HKEY("display_enter"), display_enter, 0);
1974         WebcitAddUrlHandler(HKEY("post"), post_message, 0);
1975         WebcitAddUrlHandler(HKEY("move_msg"), move_msg, 0);
1976         WebcitAddUrlHandler(HKEY("delete_msg"), delete_msg, 0);
1977         WebcitAddUrlHandler(HKEY("confirm_move_msg"), confirm_move_msg, 0);
1978         WebcitAddUrlHandler(HKEY("msg"), embed_message, NEED_URL);
1979         WebcitAddUrlHandler(HKEY("message"), handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1980         WebcitAddUrlHandler(HKEY("printmsg"), print_message, NEED_URL);
1981         WebcitAddUrlHandler(HKEY("mobilemsg"), mobile_message_view, NEED_URL);
1982         WebcitAddUrlHandler(HKEY("msgheaders"), display_headers, NEED_URL);
1983
1984         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1985         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1986         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
1987         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
1988
1989         /* json */
1990         WebcitAddUrlHandler(HKEY("roommsgs"), jsonMessageList,0);
1991         return ;
1992 }
1993
1994 void
1995 SessionDetachModule_MSG
1996 (wcsession *sess)
1997 {
1998         DeleteHash(&sess->summ);
1999 }