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