]> code.citadel.org Git - citadel.git/blob - webcit/messages.c
c3303792bee553215325cbf60829a4c961a44382
[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 /*----------------------------------------------------------------------------*/
26
27
28 typedef void (*MsgPartEvaluatorFunc)(message_summary *Sum, StrBuf *Buf);
29
30 typedef struct _MsgPartEvaluatorStruct {
31         MsgPartEvaluatorFunc f;
32 }MsgPartEvaluatorStruct;
33
34
35 /*----------------------------------------------------------------------------*/
36
37
38
39 /*
40  * I wanna SEE that message!
41  *
42  * msgnum               Message number to display
43  * printable_view       Nonzero to display a printable view
44  * section              Optional for encapsulated message/rfc822 submessage
45  */
46 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, int printable_view, const StrBuf *PartNum) 
47 {
48         wcsession *WCC = WC;
49         StrBuf *Buf;
50         StrBuf *HdrToken;
51         StrBuf *FoundCharset;
52         HashPos  *it;
53         void *vMime;
54         message_summary *Msg = NULL;
55         headereval *Hdr;
56         void *vHdr;
57         char buf[SIZ];
58         int Done = 0;
59         int state=0;
60         long len;
61         const char *Key;
62         WCTemplputParams SubTP;
63
64         Buf = NewStrBuf();
65         lprintf(1, "----------%s---------MSG4 %ld|%s--------------\n", tmpl, msgnum, ChrPtr(PartNum));
66         serv_printf("MSG4 %ld|%s", msgnum, ChrPtr(PartNum));
67         StrBuf_ServGetln(Buf);
68         if (GetServerStatus(Buf, NULL) != 1) {
69                 StrBufAppendPrintf(Target, "<strong>");
70                 StrBufAppendPrintf(Target, _("ERROR:"));
71                 StrBufAppendPrintf(Target, "</strong> %s<br />\n", &buf[4]);
72                 FreeStrBuf(&Buf);
73                 return 0;
74         }
75
76         /** begin everythingamundo table */
77
78
79         HdrToken = NewStrBuf();
80         Msg = (message_summary *)malloc(sizeof(message_summary));
81         memset(Msg, 0, sizeof(message_summary));
82         Msg->msgnum = msgnum;
83         Msg->PartNum = PartNum;
84         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
85         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
86         Msg->MsgBody->msgnum = msgnum;
87         FoundCharset = NewStrBuf();
88         while ((StrBuf_ServGetln(Buf)>=0) && !Done) {
89                 if ( (StrLength(Buf)==3) && 
90                     !strcmp(ChrPtr(Buf), "000")) 
91                 {
92                         Done = 1;
93                         if (state < 2) {
94                                 lprintf(1, _("unexpected end of message"));
95                                 
96                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
97                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
98                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("unexpected end of message"));
99                                 StrBufAppendPrintf(Msg->MsgBody->Data, " (1)</i><br /><br />\n");
100                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
101                         }
102                         break;
103                 }
104                 switch (state) {
105                 case 0:/* Citadel Message Headers */
106                         if (StrLength(Buf) == 0) {
107                                 state ++;
108                                 break;
109                         }
110                         StrBufExtract_token(HdrToken, Buf, 0, '=');
111                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
112                         
113 #ifdef TECH_PREVIEW
114                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
115 #endif
116                         /* look up one of the examine_* functions to parse the content */
117                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
118                             (vHdr != NULL)) {
119                                 Hdr = (headereval*)vHdr;
120                                 Hdr->evaluator(Msg, Buf, FoundCharset);
121                                 if (Hdr->Type == 1) {
122                                         state++;
123                                 }
124                         }
125                         else LogError(Target, 
126                                       __FUNCTION__,  
127                                       "don't know how to handle message header[%s]\n", 
128                                       ChrPtr(HdrToken));
129                         break;
130                 case 1:/* Message Mime Header */
131                         if (StrLength(Buf) == 0) {
132                                 state++;
133                                 if (Msg->MsgBody->ContentType == NULL)
134                                         /* end of header or no header? */
135                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
136                                  /* usual end of mime header */
137                         }
138                         else
139                         {
140                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
141                                 if (StrLength(HdrToken) > 0) {
142                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
143 #ifdef TECH_PREVIEW
144                                         if (dbg_analyze_msg) lprintf(1, ":: [%s] = [%s]\n", ChrPtr(HdrToken), ChrPtr(Buf));
145 #endif
146                                         /* the examine*'s know how to do with mime headers too... */
147                                         if (GetHash(MsgHeaderHandler, SKEY(HdrToken), &vHdr) &&
148                                             (vHdr != NULL)) {
149                                                 Hdr = (headereval*)vHdr;
150                                                 Hdr->evaluator(Msg, Buf, FoundCharset);
151                                         }
152                                         break;
153                                 }
154                         }
155                 case 2: /* Message Body */
156                         
157                         if (Msg->MsgBody->size_known > 0) {
158                                 StrBuf_ServGetBLOB(Msg->MsgBody->Data, Msg->MsgBody->length);
159                                 state ++;
160                                 /*/ todo: check next line, if not 000, append following lines */
161                         }
162                         else if (1){
163                                 if (StrLength(Msg->MsgBody->Data) > 0)
164                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
165                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
166                         }
167                         break;
168                 case 3:
169                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
170                         break;
171                 }
172         }
173
174         if (Msg->AllAttach == NULL)
175                 Msg->AllAttach = NewHash(1,NULL);
176         /* now we put the body mimepart we read above into the mimelist */
177         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
178         
179         /* strip the bare contenttype, so we ommit charset etc. */
180         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
181         StrBufTrim(Buf);
182         /* look up the renderer, that will convert this mimeitem into the htmlized form */
183         if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
184             (vHdr != NULL)) {
185                 RenderMimeFuncStruct *Render;
186                 Render = (RenderMimeFuncStruct*)vHdr;
187                 Render->f(Msg->MsgBody, NULL, FoundCharset);
188         }
189
190         if (StrLength(Msg->reply_references)> 0) {
191                 /* Trim down excessively long lists of thread references.  We eliminate the
192                  * second one in the list so that the thread root remains intact.
193                  */
194                 int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
195                 int rrlen = StrLength(Msg->reply_references);
196                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
197                         StrBufRemove_token(Msg->reply_references, 1, '|');
198                 }
199         }
200
201         /* Generate a reply-to address */
202         if (StrLength(Msg->Rfca) > 0) {
203                 if (Msg->reply_to == NULL)
204                         Msg->reply_to = NewStrBuf();
205                 if (StrLength(Msg->from) > 0) {
206                         StrBufPrintf(Msg->reply_to, "%s <%s>", ChrPtr(Msg->from), ChrPtr(Msg->Rfca));
207                 }
208                 else {
209                         FlushStrBuf(Msg->reply_to);
210                         StrBufAppendBuf(Msg->reply_to, Msg->Rfca, 0);
211                 }
212         }
213         else 
214         {
215                 if ((StrLength(Msg->OtherNode)>0) && 
216                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_nodename))) &&
217                     (strcasecmp(ChrPtr(Msg->OtherNode), ChrPtr(WCC->serv_info->serv_humannode)) ))
218                 {
219                         if (Msg->reply_to == NULL)
220                                 Msg->reply_to = NewStrBuf();
221                         StrBufPrintf(Msg->reply_to, 
222                                      "%s @ %s",
223                                      ChrPtr(Msg->from), 
224                                      ChrPtr(Msg->OtherNode));
225                 }
226                 else {
227                         if (Msg->reply_to == NULL)
228                                 Msg->reply_to = NewStrBuf();
229                         FlushStrBuf(Msg->reply_to);
230                         StrBufAppendBuf(Msg->reply_to, Msg->from, 0);
231                 }
232         }
233
234         /* now check if we need to translate some mimeparts, and remove the duplicate */
235         it = GetNewHashPos(Msg->AllAttach, 0);
236         while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
237                (vMime != NULL)) {
238                 wc_mime_attachment *Mime = (wc_mime_attachment*) vMime;
239                 evaluate_mime_part(Msg, Mime);
240         }
241         DeleteHashPos(&it);
242         memset(&SubTP, 0, sizeof(WCTemplputParams));
243         SubTP.Filter.ContextType = CTX_MAILSUM;
244         SubTP.Context = Msg;
245         DoTemplate(tmpl, tmpllen, Target, &SubTP);
246
247         DestroyMessageSummary(Msg);
248         FreeStrBuf(&FoundCharset);
249         FreeStrBuf(&HdrToken);
250         FreeStrBuf(&Buf);
251         return 1;
252 }
253
254
255
256 /*
257  * Unadorned HTML output of an individual message, suitable
258  * for placing in a hidden iframe, for printing, or whatever
259  *
260  * msgnum_as_string == Message number, as a string instead of as a long int
261  */
262 void embed_message(void) {
263         long msgnum = 0L;
264         wcsession *WCC = WC;
265         const StrBuf *Tmpl = sbstr("template");
266
267         msgnum = StrTol(WCC->UrlFragment2);
268         if (StrLength(Tmpl) > 0) 
269                 read_message(WCC->WBuf, SKEY(Tmpl), msgnum, 0, NULL);
270         else 
271                 read_message(WCC->WBuf, HKEY("view_message"), msgnum, 0, NULL);
272 }
273
274
275 /*
276  * Printable view of a message
277  *
278  * msgnum_as_string == Message number, as a string instead of as a long int
279  */
280 void print_message(void) {
281         long msgnum = 0L;
282
283         msgnum = StrTol(WC->UrlFragment2);
284         output_headers(0, 0, 0, 0, 0, 0);
285
286         hprintf("Content-type: text/html\r\n"
287                 "Server: " PACKAGE_STRING "\r\n"
288                 "Connection: close\r\n");
289
290         begin_burst();
291
292         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, 1, NULL);
293
294         wDumpContent(0);
295 }
296
297 /* 
298  * Mobile browser view of message
299  *
300  * @param msg_num_as_string Message number as a string instead of as a long int 
301  */
302 void mobile_message_view(void) {
303   long msgnum = 0L;
304   msgnum = StrTol(WC->UrlFragment2);
305   output_headers(1, 0, 0, 0, 0, 1);
306   begin_burst();
307   do_template("msgcontrols", NULL);
308   read_message(WC->WBuf, HKEY("view_message"), msgnum,1, NULL);
309   wDumpContent(0);
310 }
311
312 /**
313  * \brief Display a message's headers
314  *
315  * \param msgnum_as_string Message number, as a string instead of as a long int
316  */
317 void display_headers(void) {
318         long msgnum = 0L;
319         char buf[1024];
320
321         msgnum = StrTol(WC->UrlFragment2);
322         output_headers(0, 0, 0, 0, 0, 0);
323
324         hprintf("Content-type: text/plain\r\n"
325                 "Server: %s\r\n"
326                 "Connection: close\r\n",
327                 PACKAGE_STRING);
328         begin_burst();
329
330         serv_printf("MSG2 %ld|3", msgnum);
331         serv_getln(buf, sizeof buf);
332         if (buf[0] == '1') {
333                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
334                         wprintf("%s\n", buf);
335                 }
336         }
337
338         wDumpContent(0);
339 }
340
341
342 message_summary *ReadOneMessageSummary(StrBuf *RawMessage, const char *DefaultSubject, long MsgNum) 
343 {
344         void                 *vEval;
345         MsgPartEvaluatorStruct  *Eval;
346         message_summary      *Msg;
347         StrBuf *Buf;
348         const char *buf;
349         const char *ebuf;
350         int nBuf;
351         long len;
352         
353         Buf = NewStrBuf();
354
355         serv_printf("MSG0 %ld|1", MsgNum);      /* ask for headers only */
356         
357         StrBuf_ServGetln(Buf);
358         if (GetServerStatus(Buf, NULL) == 1) {
359                 FreeStrBuf(&Buf);
360                 return NULL;
361         }
362
363         Msg = (message_summary*)malloc(sizeof(message_summary));
364         memset(Msg, 0, sizeof(message_summary));
365         while (len = StrBuf_ServGetln(Buf),
366                ((len != 3)  ||
367                 strcmp(ChrPtr(Buf), "000")== 0)){
368                 buf = ChrPtr(Buf);
369                 ebuf = strchr(ChrPtr(Buf), '=');
370                 nBuf = ebuf - buf;
371                 if (GetHash(MsgEvaluators, buf, nBuf, &vEval) && vEval != NULL) {
372                         Eval = (MsgPartEvaluatorStruct*) vEval;
373                         StrBufCutLeft(Buf, nBuf + 1);
374                         Eval->f(Msg, Buf);
375                 }
376                 else lprintf(1, "Don't know how to handle Message Headerline [%s]", ChrPtr(Buf));
377         }
378         return Msg;
379 }
380
381
382
383
384
385 /*
386  * load message pointers from the server for a "read messages" operation
387  *
388  * servcmd:             the citadel command to send to the citserver
389  * with_headers:        also include some of the headers with the message numbers (more expensive)
390  */
391 int load_msg_ptrs(char *servcmd, int with_headers)
392 {
393         StrBuf* FoundCharset = NULL;
394         wcsession *WCC = WC;
395         message_summary *Msg;
396         StrBuf *Buf, *Buf2;
397         int nummsgs = 0;
398         int maxload = 0;
399         long len;
400         int n;
401         int skipit;
402
403         if (WCC->summ != NULL) {
404                 DeleteHash(&WCC->summ);
405         }
406         WCC->summ = NewHash(1, Flathash);
407         maxload = 10000;
408         
409         Buf = NewStrBuf();
410         serv_puts(servcmd);
411         StrBuf_ServGetln(Buf);
412         if (GetServerStatus(Buf, NULL) != 1) {
413                 FreeStrBuf(&Buf);
414                 return (nummsgs);
415         }
416         Buf2 = NewStrBuf();
417         while (len = StrBuf_ServGetln(Buf),
418                ((len != 3)  ||
419                 strcmp(ChrPtr(Buf), "000")!= 0))
420         {
421                 if (nummsgs < maxload) {
422                         skipit = 0;
423                         Msg = (message_summary*)malloc(sizeof(message_summary));
424                         memset(Msg, 0, sizeof(message_summary));
425
426                         Msg->msgnum = StrBufExtract_long(Buf, 0, '|');
427                         Msg->date = StrBufExtract_long(Buf, 1, '|');
428                         /* 
429                          * as citserver probably gives us messages in forward date sorting
430                          * nummsgs should be the same order as the message date.
431                          */
432                         if (Msg->date == 0) {
433                                 Msg->date = nummsgs;
434                                 if (StrLength(Buf) < 32) 
435                                         skipit = 1;
436                         }
437                         if (!skipit) {
438                                 Msg->from = NewStrBufPlain(NULL, StrLength(Buf));
439                                 StrBufExtract_token(Buf2, Buf, 2, '|');
440                                 if (StrLength(Buf2) != 0) {
441                                         /** Handle senders with RFC2047 encoding */
442                                         StrBuf_RFC822_to_Utf8(Msg->from, Buf2, WCC->DefaultCharset, FoundCharset);
443                                 }
444                         
445                                 /** Nodename */
446                                 StrBufExtract_token(Buf2, Buf, 3, '|');
447                                 if ((StrLength(Buf2) !=0 ) &&
448                                     ( ((WCC->room_flags & QR_NETWORK)
449                                        || ((strcasecmp(ChrPtr(Buf2), ChrPtr(WCC->serv_info->serv_nodename))
450                                             && (strcasecmp(ChrPtr(Buf2), ChrPtr(WCC->serv_info->serv_fqdn))))))))
451                                 {
452                                         StrBufAppendBufPlain(Msg->from, HKEY(" @ "), 0);
453                                         StrBufAppendBuf(Msg->from, Buf2, 0);
454                                 }
455
456                                 /** Not used:
457                                     StrBufExtract_token(Msg->inetaddr, Buf, 4, '|');
458                                 */
459
460                                 Msg->subj = NewStrBufPlain(NULL, StrLength(Buf));
461                                 StrBufExtract_token(Buf2,  Buf, 5, '|');
462                                 if (StrLength(Buf2) == 0)
463                                         StrBufAppendBufPlain(Msg->subj, _("(no subject)"), -1,0);
464                                 else {
465                                         StrBuf_RFC822_to_Utf8(Msg->subj, Buf2, WCC->DefaultCharset, FoundCharset);
466                                         if ((StrLength(Msg->subj) > 75) && 
467                                             (StrBuf_Utf8StrLen(Msg->subj) > 75)) {
468                                                 StrBuf_Utf8StrCut(Msg->subj, 72);
469                                                 StrBufAppendBufPlain(Msg->subj, HKEY("..."), 0);
470                                         }
471                                 }
472
473
474                                 if ((StrLength(Msg->from) > 25) && 
475                                     (StrBuf_Utf8StrLen(Msg->from) > 25)) {
476                                         StrBuf_Utf8StrCut(Msg->from, 23);
477                                         StrBufAppendBufPlain(Msg->from, HKEY("..."), 0);
478                                 }
479                         }
480                         n = Msg->msgnum;
481                         Put(WCC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
482                 }
483                 nummsgs++;
484         }
485         FreeStrBuf(&Buf2);
486         FreeStrBuf(&Buf);
487         return (nummsgs);
488 }
489
490
491 inline message_summary* GetMessagePtrAt(int n, HashList *Summ)
492 {
493         const char *Key;
494         long HKLen;
495         void *vMsg;
496
497         if (Summ == NULL)
498                 return NULL;
499         GetHashAt(Summ, n, &HKLen, &Key, &vMsg);
500         return (message_summary*) vMsg;
501 }
502
503
504 long DrawMessageDropdown(StrBuf *Selector, long maxmsgs, long startmsg, int nMessages)
505 {
506         StrBuf *TmpBuf;
507         wcsession *WCC = WC;
508         void *vMsg;
509         int lo, hi;
510         long ret;
511         long hklen;
512         const char *key;
513         int done = 0;
514         int nItems;
515         HashPos *At;
516         long vector[16];
517         WCTemplputParams SubTP;
518
519         memset(&SubTP, 0, sizeof(WCTemplputParams));
520         SubTP.Filter.ContextType = CTX_LONGVECTOR;
521         SubTP.Context = &vector;
522         TmpBuf = NewStrBuf();
523         At = GetNewHashPos(WCC->summ, nMessages);
524         nItems = GetCount(WCC->summ);
525         ret = nMessages;
526         vector[0] = 7;
527         vector[2] = 1;
528         vector[1] = startmsg;
529         vector[3] = 0;
530
531         while (!done) {
532                 vector[3] = abs(nMessages);
533                 lo = GetHashPosCounter(At);
534                 if (nMessages > 0) {
535                         if (lo + nMessages >= nItems) {
536                                 hi = nItems - 1;
537                                 vector[3] = nItems - lo;
538                                 if (startmsg == lo) 
539                                         ret = vector[3];
540                         }
541                         else {
542                                 hi = lo + nMessages - 1;
543                         }
544                 } else {
545                         if (lo + nMessages < -1) {
546                                 hi = 0;
547                         }
548                         else {
549                                 if ((lo % abs(nMessages)) != 0) {
550                                         int offset = (lo % abs(nMessages) *
551                                                       (nMessages / abs(nMessages)));
552                                         hi = lo + offset;
553                                         vector[3] = abs(offset);
554                                         if (startmsg == lo)
555                                                  ret = offset;
556                                 }
557                                 else
558                                         hi = lo + nMessages;
559                         }
560                 }
561                 done = !GetNextHashPos(WCC->summ, At, &hklen, &key, &vMsg);
562                 
563                 /**
564                  * Bump these because although we're thinking in zero base, the user
565                  * is a drooling idiot and is thinking in one base.
566                  */
567                 vector[4] = lo + 1;
568                 vector[5] = hi + 1;
569                 vector[6] = lo;
570                 FlushStrBuf(TmpBuf);
571                 dbg_print_longvector(vector);
572                 DoTemplate(HKEY("select_messageindex"), TmpBuf, &SubTP);
573                 StrBufAppendBuf(Selector, TmpBuf, 0);
574         }
575         vector[6] = 0;
576         FlushStrBuf(TmpBuf);
577         if (maxmsgs == 9999999) {
578                 vector[1] = 1;
579                 ret = maxmsgs;
580         }
581         else
582                 vector[1] = 0;          
583         vector[2] = 0;
584         dbg_print_longvector(vector);
585         DoTemplate(HKEY("select_messageindex_all"), TmpBuf, &SubTP);
586         StrBufAppendBuf(Selector, TmpBuf, 0);
587         FreeStrBuf(&TmpBuf);
588         DeleteHashPos(&At);
589         return ret;
590 }
591
592 void load_seen_flags(void)
593 {
594         message_summary *Msg;
595         const char *HashKey;
596         long HKLen;
597         HashPos *at;
598         void *vMsg;
599         StrBuf *OldMsg;
600         wcsession *WCC = WC;
601
602         OldMsg = NewStrBuf();
603         serv_puts("GTSN");
604         StrBuf_ServGetln(OldMsg);
605         if (GetServerStatus(OldMsg, NULL) == 2) {
606                 StrBufCutLeft(OldMsg, 4);
607         }
608         else {
609                 FreeStrBuf(&OldMsg);
610                 return;
611         }
612         at = GetNewHashPos(WCC->summ, 0);
613         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
614                 /** Are you a new message, or an old message? */
615                 Msg = (message_summary*) vMsg;
616                 if (is_msg_in_mset(ChrPtr(OldMsg), Msg->msgnum)) {
617                         Msg->is_new = 0;
618                 }
619                 else {
620                         Msg->is_new = 1;
621                 }
622         }
623         FreeStrBuf(&OldMsg);
624         DeleteHashPos(&at);
625 }
626
627 extern readloop_struct rlid[];
628
629 /*
630  * command loop for reading messages
631  *
632  * Set oper to "readnew" or "readold" or "readfwd" or "headers"
633  */
634 void readloop(long oper)
635 {
636         StrBuf *MessageDropdown = NULL;
637         StrBuf *BBViewToolBar = NULL;
638         void *vMsg;
639         message_summary *Msg;
640         char cmd[256] = "";
641         char buf[SIZ];
642         int a = 0;
643         int with_headers = 0;
644         int nummsgs;
645         long startmsg = 0;
646         int maxmsgs = 0;
647         long *displayed_msgs = NULL;
648         int num_displayed = 0;
649         int is_singlecard = 0;
650         struct calview calv;
651         int i;
652         int lowest_displayed = (-1);
653         int highest_displayed = 0;
654         addrbookent *addrbook = NULL;
655         int num_ab = 0;
656         int bbs_reverse = 0;
657         wcsession *WCC = WC;
658         HashPos *at;
659         const char *HashKey;
660         long HKLen;
661         int care_for_empty_list = 0;
662         int load_seen = 0;
663         int sortit = 0;
664         int defaultsortorder = 0;
665         WCTemplputParams SubTP;
666         char *ab_name;
667
668         if (havebstr("is_summary") && (1 == (ibstr("is_summary"))))
669                 WCC->wc_view = VIEW_MAILBOX;
670
671         if (!WCC->is_ajax) {
672         output_headers(1, 1, 1, 0, 0, 0);
673         } else if (WCC->wc_view == VIEW_MAILBOX) {
674           jsonMessageListHdr();
675         }
676
677         switch (WCC->wc_view) {
678         case VIEW_WIKI:
679                 sprintf(buf, "wiki?room=%s&page=home", ChrPtr(WCC->wc_roomname));
680                 http_redirect(buf);
681                 return;
682         case VIEW_CALBRIEF:
683         case VIEW_CALENDAR:
684                 load_seen = 1;
685                 strcpy(cmd, "MSGS ALL|||1");
686                 maxmsgs = 32767;
687                 parse_calendar_view_request(&calv);
688                 break;
689         case VIEW_TASKS:
690                 strcpy(cmd, "MSGS ALL");
691                 maxmsgs = 32767;
692                 break;
693         case VIEW_NOTES:
694                 strcpy(cmd, "MSGS ALL");
695                 maxmsgs = 32767;
696                 wprintf("<div id=\"new_notes_here\"></div>\n");
697                 break;
698         case VIEW_ADDRESSBOOK:
699                 is_singlecard = ibstr("is_singlecard");
700                 if (is_singlecard != 1) {
701                         if (oper == do_search) {
702                                 snprintf(cmd, sizeof(cmd), "MSGS SEARCH|%s", bstr("query"));
703                         }
704                         else {
705                                 strcpy(cmd, "MSGS ALL");
706                         }
707                         maxmsgs = 9999999;
708                         break;
709                 }
710                 break;
711         case VIEW_MAILBOX: 
712           if (!WCC->is_ajax) {
713             new_summary_view();
714             return;
715           } else {
716                 defaultsortorder = 2;
717                 sortit = 1;
718                 load_seen = 1;
719                 care_for_empty_list = 0;
720                 with_headers = 1;
721                 /* Generally using maxmsgs|startmsg is not required
722                    in mailbox view, but we have a 'safemode' for clients
723                    (*cough* Exploder) that simply can't handle too many */
724                 if (havebstr("maxmsgs")) maxmsgs = ibstr("maxmsgs");
725                 else maxmsgs = 9999999;
726                 if (havebstr("startmsg")) startmsg = lbstr("startmsg");
727                 snprintf(cmd, sizeof(cmd), "MSGS %s|%s||1",
728                          (oper == do_search) ? "SEARCH" : "ALL",
729                          (oper == do_search) ? bstr("query") : ""
730                         );
731           }
732                 break;
733         case VIEW_BBS:
734         default:
735                 defaultsortorder = 1;
736                 startmsg = -1;
737                 sortit = 1;
738                 care_for_empty_list = 1;
739
740                 rlid[oper].cmd(cmd, sizeof(cmd));
741                 SetAccessCommand(oper);
742
743                 if (havebstr("maxmsgs"))
744                         maxmsgs = ibstr("maxmsgs");
745                 if (maxmsgs == 0) maxmsgs = DEFAULT_MAXMSGS;
746
747                 if (havebstr("startmsg")) {
748                         startmsg = lbstr("startmsg");
749                 }
750                 
751         }
752
753         nummsgs = load_msg_ptrs(cmd, with_headers);
754         if (nummsgs == 0) {
755                 if (care_for_empty_list) {
756                         wprintf("<div class=\"nomsgs\"><br><em>");
757                         switch (oper) {
758                         case readnew:
759                                 wprintf(_("No new messages."));
760                                 break;
761                         case readold:
762                                 wprintf(_("No old messages."));
763                                 break;
764                         default:
765                                 wprintf(_("No messages here."));
766                         }
767                         wprintf("</em><br></div>\n");
768                         goto DONE;
769                 }
770
771         }
772
773         if (sortit) {
774                 CompareFunc SortIt;
775                 memset(&SubTP, 0, sizeof(WCTemplputParams));
776                 SubTP.Filter.ContextType = CTX_NONE;
777                 SubTP.Context = NULL;
778                 SortIt =  RetrieveSort(&SubTP, NULL, 0,
779                                        HKEY("date"), defaultsortorder);
780                 if (SortIt != NULL)
781                         SortByPayload(WCC->summ, SortIt);
782                 if (WCC->wc_view == VIEW_BBS) {
783                         if (lbstr("SortOrder") == 2) {
784                                 bbs_reverse = 1;
785                                 num_displayed = -DEFAULT_MAXMSGS;
786                         }
787                         else {
788                                 bbs_reverse = 0;
789                                 num_displayed = DEFAULT_MAXMSGS;
790                         }
791                 }
792         }
793         if (startmsg < 0) startmsg = (bbs_reverse) ? nummsgs - 1 : 0;
794
795         if (load_seen) load_seen_flags();
796         
797         /**
798          * If we're to print s.th. above the message list...
799          */
800         switch (WCC->wc_view) {
801         case VIEW_BBS:
802                 BBViewToolBar = NewStrBuf();
803                 MessageDropdown = NewStrBuf();
804
805                 maxmsgs = DrawMessageDropdown(MessageDropdown, maxmsgs, startmsg, num_displayed);
806                 if (num_displayed < 0) {
807                         startmsg += maxmsgs;
808                         if (num_displayed != maxmsgs)                           
809                                 maxmsgs = abs(maxmsgs) + 1;
810                         else
811                                 maxmsgs = abs(maxmsgs);
812
813                 }
814                 memset(&SubTP, 0, sizeof(WCTemplputParams));
815                 SubTP.Filter.ContextType = CTX_STRBUF;
816                 SubTP.Context = MessageDropdown;
817                 DoTemplate(HKEY("msg_listselector_top"), BBViewToolBar, &SubTP);
818                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
819                 FlushStrBuf(BBViewToolBar);
820                 break;
821         }
822         WCC->startmsg =  startmsg;
823         WCC->maxmsgs = maxmsgs;
824         WCC->num_displayed = 0;
825
826         /* Put some helpful data in vars for mailsummary_json */
827         svputlong("READLOOP:TOTALMSGS", nummsgs);
828         svputlong("READLOOP:STARTMSG", startmsg);
829         svputlong("WCVIEW", WCC->wc_view);
830         /*
831          * iterate over each message. if we need to load an attachment, do it here. 
832          */
833         if (WCC->wc_view == VIEW_MAILBOX) goto NO_MSG_LOOP;
834         /*
835          * iterate over each message. if we need to load an attachment, do it here. 
836          */
837         at = GetNewHashPos(WCC->summ, 0);
838         num_displayed = i = 0;
839         while (GetNextHashPos(WCC->summ, at, &HKLen, &HashKey, &vMsg)) {
840                 Msg = (message_summary*) vMsg;          
841                 if ((Msg->msgnum >= startmsg) && (num_displayed <= maxmsgs)) {                  
842                         switch (WCC->wc_view) {
843                         case VIEW_WIKI:
844                                 break;
845                         case VIEW_CALBRIEF: /* load the mime attachments for special tasks... */
846                         case VIEW_CALENDAR:
847                                 load_calendar_item(Msg, Msg->is_new, &calv);
848                                 break;
849                         case VIEW_TASKS:
850                                 display_task(Msg, Msg->is_new);
851                                 break;
852                         case VIEW_NOTES:
853                                 display_note(Msg, Msg->is_new);
854                                 break;
855                         case VIEW_ADDRESSBOOK:
856                                 ab_name = NULL;
857                                 fetch_ab_name(Msg, &ab_name);
858                                 ++num_ab;
859                                 addrbook = realloc(addrbook,
860                                                    (sizeof(addrbookent) * num_ab) );
861                                 safestrncpy(addrbook[num_ab-1].ab_name, ab_name,
862                                             sizeof(addrbook[num_ab-1].ab_name));
863                                 addrbook[num_ab-1].ab_msgnum = Msg->msgnum;
864                                 free(ab_name);
865                                 break;
866                         case VIEW_BBS: /* Tag the mails we want to show in bbview... */
867                         default:
868                                 if (displayed_msgs == NULL) {
869                                         displayed_msgs = malloc(sizeof(long) *
870                                                                 (maxmsgs<nummsgs ? maxmsgs + 1 : nummsgs + 1));
871                                 }
872                                 if ((i >= startmsg) && (i < startmsg + maxmsgs)) {
873                                         displayed_msgs[num_displayed] = Msg->msgnum;
874                                         if (lowest_displayed < 0) lowest_displayed = a;
875                                         highest_displayed = a;
876                         
877                                         num_displayed++;
878                                 }
879                         }
880                 } 
881                 i++;
882         }
883         DeleteHashPos(&at);
884
885  NO_MSG_LOOP:   
886         /*
887          * Done iterating the message list. now tasks we want to do after.
888          */
889         switch (WCC->wc_view) {
890         case VIEW_MAILBOX:
891           DoTemplate(HKEY("mailsummary_json"),NULL, &SubTP);
892           break;
893         case VIEW_BBS:
894                 if (displayed_msgs != NULL) {
895                         /** if we do a split bbview in the future, begin messages div here */
896                         
897                         for (a=0; a<num_displayed; ++a) {
898                                 read_message(WCC->WBuf, HKEY("view_message"), displayed_msgs[a], 0, NULL);
899                         }
900                         
901                         /** if we do a split bbview in the future, end messages div here */
902                         
903                         free(displayed_msgs);
904                         displayed_msgs = NULL;
905                 }
906                 memset(&SubTP, 0, sizeof(WCTemplputParams));
907                 SubTP.Filter.ContextType = CTX_STRBUF;
908                 SubTP.Context = MessageDropdown;
909                 DoTemplate(HKEY("msg_listselector_bottom"), BBViewToolBar, &SubTP);
910                 StrBufAppendBuf(WCC->WBuf, BBViewToolBar, 0);
911
912                 FreeStrBuf(&BBViewToolBar);
913                 FreeStrBuf(&MessageDropdown);
914         }
915
916         
917 DONE:
918         switch (WCC->wc_view) {
919         case VIEW_WIKI:
920                 break;
921         case VIEW_CALBRIEF:
922         case VIEW_CALENDAR:
923                 render_calendar_view(&calv);
924                 break;
925         case VIEW_TASKS:
926                 do_tasks_view();        /** Render the task list */
927                 break;
928         case VIEW_NOTES:
929                 break;
930         case VIEW_ADDRESSBOOK:
931                 if (is_singlecard)
932                         read_message(WC->WBuf, HKEY("view_message"), lbstr("startmsg"), 0, NULL);
933                 else
934                         do_addrbook_view(addrbook, num_ab);     /** Render the address book */
935                 break;
936         case VIEW_MAILBOX: 
937         case VIEW_BBS:
938         default:
939                 break;
940         }
941         /** Note: wDumpContent() will output one additional </div> tag. */
942         if (WCC->wc_view != VIEW_MAILBOX) {
943                 /* We ought to move this out into template */
944                 wDumpContent(1);
945         } else {
946                 end_burst();
947         }
948         WCC->startmsg = 0;
949         WCC->maxmsgs = 0;
950         if (WCC->summ != NULL) {
951                 DeleteHash(&WCC->summ);
952         }
953         if (addrbook != NULL) free(addrbook);
954         FreeStrBuf(&BBViewToolBar);
955 }
956
957
958 /*
959  * Back end for post_message()
960  * ... this is where the actual message gets transmitted to the server.
961  */
962 void post_mime_to_server(void) {
963         wcsession *WCC = WC;
964         char top_boundary[SIZ];
965         char alt_boundary[SIZ];
966         int is_multipart = 0;
967         static int seq = 0;
968         wc_mime_attachment *att;
969         char *encoded;
970         size_t encoded_length;
971         size_t encoded_strlen;
972         char *txtmail = NULL;
973
974         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
975                 ChrPtr(WCC->serv_info->serv_fqdn),
976                 getpid(),
977                 ++seq
978         );
979         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
980                 ChrPtr(WCC->serv_info->serv_fqdn),
981                 getpid(),
982                 ++seq
983         );
984
985         /* RFC2045 requires this, and some clients look for it... */
986         serv_puts("MIME-Version: 1.0");
987         serv_puts("X-Mailer: " PACKAGE_STRING);
988
989         /* If there are attachments, we have to do multipart/mixed */
990         if (GetCount(WCC->attachments) > 0) {
991                 is_multipart = 1;
992         }
993
994         if (is_multipart) {
995                 /* Remember, serv_printf() appends an extra newline */
996                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
997                 serv_printf("This is a multipart message in MIME format.\n");
998                 serv_printf("--%s", top_boundary);
999         }
1000
1001         /* Remember, serv_printf() appends an extra newline */
1002         serv_printf("Content-type: multipart/alternative; "
1003                 "boundary=\"%s\"\n", alt_boundary);
1004         serv_printf("This is a multipart message in MIME format.\n");
1005         serv_printf("--%s", alt_boundary);
1006
1007         serv_puts("Content-type: text/plain; charset=utf-8");
1008         serv_puts("Content-Transfer-Encoding: quoted-printable");
1009         serv_puts("");
1010         txtmail = html_to_ascii(bstr("msgtext"), 0, 80, 0);
1011         text_to_server_qp(txtmail);     /* Transmit message in quoted-printable encoding */
1012         free(txtmail);
1013
1014         serv_printf("--%s", alt_boundary);
1015
1016         serv_puts("Content-type: text/html; charset=utf-8");
1017         serv_puts("Content-Transfer-Encoding: quoted-printable");
1018         serv_puts("");
1019         serv_puts("<html><body>\r\n");
1020         text_to_server_qp(bstr("msgtext"));     /* Transmit message in quoted-printable encoding */
1021         serv_puts("</body></html>\r\n");
1022
1023         serv_printf("--%s--", alt_boundary);
1024         
1025         if (is_multipart) {
1026                 long len;
1027                 const char *Key; 
1028                 void *vAtt;
1029                 HashPos  *it;
1030
1031                 /* Add in the attachments */
1032                 it = GetNewHashPos(WCC->attachments, 0);
1033                 while (GetNextHashPos(WCC->attachments, it, &len, &Key, &vAtt)) {
1034                         att = (wc_mime_attachment *)vAtt;
1035                         encoded_length = ((att->length * 150) / 100);
1036                         encoded = malloc(encoded_length);
1037                         if (encoded == NULL) break;
1038                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
1039
1040                         serv_printf("--%s", top_boundary);
1041                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
1042                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
1043                         serv_puts("Content-transfer-encoding: base64");
1044                         serv_puts("");
1045                         serv_write(encoded, encoded_strlen);
1046                         serv_puts("");
1047                         serv_puts("");
1048                         free(encoded);
1049                 }
1050                 serv_printf("--%s--", top_boundary);
1051                 DeleteHashPos(&it);
1052         }
1053
1054         serv_puts("000");
1055 }
1056
1057
1058 /*
1059  * Post message (or don't post message)
1060  *
1061  * Note regarding the "dont_post" variable:
1062  * A random value (actually, it's just a timestamp) is inserted as a hidden
1063  * field called "postseq" when the display_enter page is generated.  This
1064  * value is checked when posting, using the static variable dont_post.  If a
1065  * user attempts to post twice using the same dont_post value, the message is
1066  * discarded.  This prevents the accidental double-saving of the same message
1067  * if the user happens to click the browser "back" button.
1068  */
1069 void post_message(void)
1070 {
1071         char buf[1024];
1072         StrBuf *encoded_subject = NULL;
1073         static long dont_post = (-1L);
1074         wc_mime_attachment  *att;
1075         int is_anonymous = 0;
1076         const StrBuf *display_name = NULL;
1077         wcsession *WCC = WC;
1078         
1079         if (havebstr("force_room")) {
1080                 gotoroom(sbstr("force_room"));
1081         }
1082
1083         if (havebstr("display_name")) {
1084                 display_name = sbstr("display_name");
1085                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1086                         display_name = NULL;
1087                         is_anonymous = 1;
1088                 }
1089         }
1090
1091         if (WCC->upload_length > 0) {
1092                 const char *pch;
1093                 int n;
1094                 char N[64];
1095
1096                 lprintf(9, "%s:%d: we are uploading %d bytes\n", __FILE__, __LINE__, WCC->upload_length);
1097                 /** There's an attachment.  Save it to this struct... */
1098                 att = malloc(sizeof(wc_mime_attachment));
1099                 memset(att, 0, sizeof(wc_mime_attachment ));
1100                 att->length = WCC->upload_length;
1101                 att->ContentType = NewStrBufPlain(WCC->upload_content_type, -1);
1102                 att->FileName = NewStrBufPlain(WCC->upload_filename, -1);
1103                 
1104                 
1105                 if (WCC->attachments == NULL)
1106                         WCC->attachments = NewHash(1, NULL);
1107                 /* And add it to the list. */
1108                 n = snprintf(N, sizeof N, "%d", GetCount(WCC->attachments) + 1);
1109                 Put(WCC->attachments, N, n, att, DestroyMime);
1110
1111                 /**
1112                  * Mozilla sends a simple filename, which is what we want,
1113                  * but Satan's Browser sends an entire pathname.  Reduce
1114                  * the path to just a filename if we need to.
1115                  */
1116                 pch = strrchr(ChrPtr(att->FileName), '/');
1117                 if (pch != NULL) {
1118                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1119                 }
1120                 pch = strrchr(ChrPtr(att->FileName), '\\');
1121                 if (pch != NULL) {
1122                         StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1123                 }
1124
1125                 /**
1126                  * Transfer control of this memory from the upload struct
1127                  * to the attachment struct.
1128                  */
1129                 att->Data = NewStrBufPlain(WCC->upload, WCC->upload_length);
1130                 free(WCC->upload);
1131                 WCC->upload_length = 0;
1132                 WCC->upload = NULL;
1133                 display_enter();
1134                 return;
1135         }
1136
1137         if (havebstr("cancel_button")) {
1138                 sprintf(WCC->ImportantMessage, 
1139                         _("Cancelled.  Message was not posted."));
1140         } else if (havebstr("attach_button")) {
1141                 display_enter();
1142                 return;
1143         } else if (lbstr("postseq") == dont_post) {
1144                 sprintf(WCC->ImportantMessage, 
1145                         _("Automatically cancelled because you have already "
1146                         "saved this message."));
1147         } else {
1148                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1149                 const StrBuf *Recp = NULL; 
1150                 const StrBuf *Cc = NULL;
1151                 const StrBuf *Bcc = NULL;
1152                 const StrBuf *Wikipage = NULL;
1153                 const StrBuf *my_email_addr = NULL;
1154                 StrBuf *CmdBuf = NULL;
1155                 StrBuf *references = NULL;
1156
1157                 if (havebstr("references"))
1158                 {
1159                         const StrBuf *ref = sbstr("references");
1160                         references = NewStrBufPlain(ChrPtr(ref), StrLength(ref));
1161                         lprintf(9, "Converting: %s\n", ChrPtr(references));
1162                         StrBufReplaceChars(references, '|', '!');
1163                         lprintf(9, "Converted: %s\n", ChrPtr(references));
1164                 }
1165                 if (havebstr("subject")) {
1166                         const StrBuf *Subj;
1167                         /*
1168                          * make enough room for the encoded string; 
1169                          * plus the QP header 
1170                          */
1171                         Subj = sbstr("subject");
1172                         
1173                         StrBufRFC2047encode(&encoded_subject, Subj);
1174                 }
1175                 Recp = sbstr("recp");
1176                 Cc = sbstr("cc");
1177                 Bcc = sbstr("bcc");
1178                 Wikipage = sbstr("wikipage");
1179                 my_email_addr = sbstr("my_email_addr");
1180                 
1181                 CmdBuf = NewStrBufPlain(NULL, 
1182                                         sizeof (CMD) + 
1183                                         StrLength(Recp) + 
1184                                         StrLength(encoded_subject) +
1185                                         StrLength(Cc) +
1186                                         StrLength(Bcc) + 
1187                                         StrLength(Wikipage) +
1188                                         StrLength(my_email_addr) + 
1189                                         StrLength(references));
1190
1191                 StrBufPrintf(CmdBuf, 
1192                              CMD,
1193                              ChrPtr(Recp),
1194                              is_anonymous,
1195                              ChrPtr(encoded_subject),
1196                              ChrPtr(display_name),
1197                              ChrPtr(Cc),
1198                              ChrPtr(Bcc),
1199                              ChrPtr(Wikipage),
1200                              ChrPtr(my_email_addr),
1201                              ChrPtr(references));
1202                 FreeStrBuf(&references);
1203
1204                 lprintf(9, "%s\n", ChrPtr(CmdBuf));
1205                 serv_puts(ChrPtr(CmdBuf));
1206                 serv_getln(buf, sizeof buf);
1207                 FreeStrBuf(&CmdBuf);
1208                 FreeStrBuf(&encoded_subject);
1209                 if (buf[0] == '4') {
1210                         post_mime_to_server();
1211                         if (  (havebstr("recp"))
1212                            || (havebstr("cc"  ))
1213                            || (havebstr("bcc" ))
1214                         ) {
1215                                 sprintf(WCC->ImportantMessage, _("Message has been sent.\n"));
1216                         }
1217                         else {
1218                                 sprintf(WC->ImportantMessage, _("Message has been posted.\n"));
1219                         }
1220                         dont_post = lbstr("postseq");
1221                 } else {
1222                         lprintf(9, "%s:%d: server post error: %s\n", __FILE__, __LINE__, buf);
1223                         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1224                         display_enter();
1225                         return;
1226                 }
1227         }
1228
1229         DeleteHash(&WCC->attachments);
1230
1231         /**
1232          *  We may have been supplied with instructions regarding the location
1233          *  to which we must return after posting.  If found, go there.
1234          */
1235         if (havebstr("return_to")) {
1236                 http_redirect(bstr("return_to"));
1237         }
1238         /**
1239          *  If we were editing a page in a wiki room, go to that page now.
1240          */
1241         else if (havebstr("wikipage")) {
1242                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("wikipage"));
1243                 http_redirect(buf);
1244         }
1245         /**
1246          *  Otherwise, just go to the "read messages" loop.
1247          */
1248         else {
1249                 readloop(readnew);
1250         }
1251 }
1252
1253
1254
1255
1256 /**
1257  * \brief display the message entry screen
1258  */
1259 void display_enter(void)
1260 {
1261         char buf[SIZ];
1262         long now;
1263         const StrBuf *display_name = NULL;
1264         int recipient_required = 0;
1265         int subject_required = 0;
1266         int recipient_bad = 0;
1267         int is_anonymous = 0;
1268         wcsession *WCC = WC;
1269
1270         now = time(NULL);
1271
1272         if (havebstr("force_room")) {
1273                 gotoroom(sbstr("force_room"));
1274         }
1275
1276         display_name = sbstr("display_name");
1277         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1278                 display_name = NULL;
1279                 is_anonymous = 1;
1280         }
1281
1282         /** First test to see whether this is a room that requires recipients to be entered */
1283         serv_puts("ENT0 0");
1284         serv_getln(buf, sizeof buf);
1285
1286         if (!strncmp(buf, "570", 3)) {          /** 570 means that we need a recipient here */
1287                 recipient_required = 1;
1288         }
1289         else if (buf[0] != '2') {               /** Any other error means that we cannot continue */
1290                 sprintf(WCC->ImportantMessage, "%s", &buf[4]);
1291                 readloop(readnew);
1292                 return;
1293         }
1294
1295         /* Is the server strongly recommending that the user enter a message subject? */
1296         if ((buf[3] != '\0') && (buf[4] != '\0')) {
1297                 subject_required = extract_int(&buf[4], 1);
1298         }
1299
1300         /**
1301          * Are we perhaps in an address book view?  If so, then an "enter
1302          * message" command really means "add new entry."
1303          */
1304         if (WCC->wc_default_view == VIEW_ADDRESSBOOK) {
1305                 do_edit_vcard(-1, "", "", ChrPtr(WCC->wc_roomname));
1306                 return;
1307         }
1308
1309         /*
1310          * Are we perhaps in a calendar room?  If so, then an "enter
1311          * message" command really means "add new calendar item."
1312          */
1313         if (WCC->wc_default_view == VIEW_CALENDAR) {
1314                 display_edit_event();
1315                 return;
1316         }
1317
1318         /*
1319          * Are we perhaps in a tasks view?  If so, then an "enter
1320          * message" command really means "add new task."
1321          */
1322         if (WCC->wc_default_view == VIEW_TASKS) {
1323                 display_edit_task();
1324                 return;
1325         }
1326
1327         /*
1328          * Otherwise proceed normally.
1329          * Do a custom room banner with no navbar...
1330          */
1331
1332         if (recipient_required) {
1333                 const StrBuf *Recp = NULL; 
1334                 const StrBuf *Cc = NULL;
1335                 const StrBuf *Bcc = NULL;
1336                 const StrBuf *Wikipage = NULL;
1337                 StrBuf *CmdBuf = NULL;
1338                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1339                 
1340                 Recp = sbstr("recp");
1341                 Cc = sbstr("cc");
1342                 Bcc = sbstr("bcc");
1343                 Wikipage = sbstr("wikipage");
1344                 
1345                 CmdBuf = NewStrBufPlain(NULL, 
1346                                         sizeof (CMD) + 
1347                                         StrLength(Recp) + 
1348                                         StrLength(display_name) +
1349                                         StrLength(Cc) +
1350                                         StrLength(Bcc) + 
1351                                         StrLength(Wikipage));
1352
1353                 StrBufPrintf(CmdBuf, 
1354                              CMD,
1355                              ChrPtr(Recp), 
1356                              is_anonymous,
1357                              ChrPtr(display_name),
1358                              ChrPtr(Cc), 
1359                              ChrPtr(Bcc), 
1360                              ChrPtr(Wikipage));
1361                 serv_puts(ChrPtr(CmdBuf));
1362                 serv_getln(buf, sizeof buf);
1363                 FreeStrBuf(&CmdBuf);
1364
1365                 if (!strncmp(buf, "570", 3)) {  /** 570 means we have an invalid recipient listed */
1366                         if (havebstr("recp") && 
1367                             havebstr("cc"  ) && 
1368                             havebstr("bcc" )) {
1369                                 recipient_bad = 1;
1370                         }
1371                 }
1372                 else if (buf[0] != '2') {       /** Any other error means that we cannot continue */
1373                         wprintf("<em>%s</em><br />\n", &buf[4]);/*TODO -> important message */
1374                         return;
1375                 }
1376         }
1377         svputlong("RCPTREQUIRED", recipient_required);
1378         svputlong("SUBJREQUIRED", recipient_required || subject_required);
1379
1380         begin_burst();
1381         output_headers(1, 0, 0, 0, 1, 0);
1382         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1383         end_burst();
1384
1385         return;
1386 }
1387
1388 /**
1389  * \brief delete a message
1390  */
1391 void delete_msg(void)
1392 {
1393         long msgid;
1394         char buf[SIZ];
1395
1396         msgid = lbstr("msgid");
1397
1398         if (WC->wc_is_trash) {  /** Delete from Trash is a real delete */
1399                 serv_printf("DELE %ld", msgid); 
1400         }
1401         else {                  /** Otherwise move it to Trash */
1402                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1403         }
1404
1405         serv_getln(buf, sizeof buf);
1406         sprintf(WC->ImportantMessage, "%s", &buf[4]);
1407
1408         readloop(readnew);
1409 }
1410
1411
1412 /**
1413  * \brief move a message to another folder
1414  */
1415 void move_msg(void)
1416 {
1417         long msgid;
1418         char buf[SIZ];
1419
1420         msgid = lbstr("msgid");
1421
1422         if (havebstr("move_button")) {
1423                 sprintf(buf, "MOVE %ld|%s", msgid, bstr("target_room"));
1424                 serv_puts(buf);
1425                 serv_getln(buf, sizeof buf);
1426                 sprintf(WC->ImportantMessage, "%s", &buf[4]);
1427         } else {
1428                 sprintf(WC->ImportantMessage, (_("The message was not moved.")));
1429         }
1430
1431         readloop(readnew);
1432 }
1433
1434
1435
1436
1437
1438 /*
1439  * Confirm move of a message
1440  */
1441 void confirm_move_msg(void)
1442 {
1443         long msgid;
1444         char buf[SIZ];
1445         char targ[SIZ];
1446
1447         msgid = lbstr("msgid");
1448
1449
1450         output_headers(1, 1, 2, 0, 0, 0);
1451         wprintf("<div id=\"banner\">\n");
1452         wprintf("<h1>");
1453         wprintf(_("Confirm move of message"));
1454         wprintf("</h1>");
1455         wprintf("</div>\n");
1456
1457         wprintf("<div id=\"content\" class=\"service\">\n");
1458
1459         wprintf("<CENTER>");
1460
1461         wprintf(_("Move this message to:"));
1462         wprintf("<br />\n");
1463
1464         wprintf("<form METHOD=\"POST\" action=\"move_msg\">\n");
1465         wprintf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
1466         wprintf("<INPUT TYPE=\"hidden\" NAME=\"msgid\" VALUE=\"%s\">\n", bstr("msgid"));
1467
1468         wprintf("<SELECT NAME=\"target_room\" SIZE=5>\n");
1469         serv_puts("LKRA");
1470         serv_getln(buf, sizeof buf);
1471         if (buf[0] == '1') {
1472                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
1473                         extract_token(targ, buf, 0, '|', sizeof targ);
1474                         wprintf("<OPTION>");
1475                         escputs(targ);
1476                         wprintf("\n");
1477                 }
1478         }
1479         wprintf("</SELECT>\n");
1480         wprintf("<br />\n");
1481
1482         wprintf("<INPUT TYPE=\"submit\" NAME=\"move_button\" VALUE=\"%s\">", _("Move"));
1483         wprintf("&nbsp;");
1484         wprintf("<INPUT TYPE=\"submit\" NAME=\"cancel_button\" VALUE=\"%s\">", _("Cancel"));
1485         wprintf("</form></CENTER>\n");
1486
1487         wprintf("</CENTER>\n");
1488         wDumpContent(1);
1489 }
1490
1491
1492 /*
1493  * Generic function to output an arbitrary MIME attachment from
1494  * message being composed
1495  *
1496  * partnum              The MIME part to be output
1497  * filename             Fake filename to give
1498  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1499  */
1500 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
1501 {
1502         void *vPart;
1503         StrBuf *content_type;
1504         wc_mime_attachment *part;
1505         
1506         if (GetHash(WC->attachments, SKEY(partnum), &vPart) &&
1507             (vPart != NULL)) {
1508                 part = (wc_mime_attachment*) vPart;
1509                 if (force_download) {
1510                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1511                 }
1512                 else {
1513                         content_type = NewStrBufDup(part->ContentType);
1514                 }
1515                 output_headers(0, 0, 0, 0, 0, 0);
1516                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1517                 http_transmit_thing(ChrPtr(content_type), 0);
1518         } else {
1519                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1520                 output_headers(0, 0, 0, 0, 0, 0);
1521                 hprintf("Content-Type: text/plain\r\n");
1522                 wprintf(_("An error occurred while retrieving this part: %s/%s\n"), 
1523                         ChrPtr(partnum), ChrPtr(filename));
1524                 end_burst();
1525         }
1526         FreeStrBuf(&content_type);
1527 }
1528
1529
1530 /*
1531  * Generic function to output an arbitrary MIME part from an arbitrary
1532  * message number on the server.
1533  *
1534  * msgnum               Number of the item on the citadel server
1535  * partnum              The MIME part to be output
1536  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1537  */
1538 void mimepart(int force_download)
1539 {
1540         wcsession *WCC = WC;
1541
1542         char buf[256];
1543         off_t bytes;
1544         char content_type[256];
1545         const char *ContentType = &content_type[0];
1546
1547         serv_printf("OPNA %s|%s", ChrPtr(WCC->UrlFragment2), ChrPtr(WCC->UrlFragment3));
1548         serv_getln(buf, sizeof buf);
1549         if (buf[0] == '2') {
1550                 bytes = extract_long(&buf[4], 0);
1551                 if (force_download) {
1552                         strcpy(content_type, "application/octet-stream");
1553                 }
1554                 else {
1555                         extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1556                 }
1557
1558                 read_server_binary(WCC->WBuf, bytes);
1559                 serv_puts("CLOS");
1560                 serv_getln(buf, sizeof buf);
1561
1562                 if (!force_download) {
1563                         if (!strcasecmp(ContentType, "application/octet-stream")) {
1564                                 ContentType = GuessMimeByFilename(SKEY(WCC->UrlFragment4));
1565                         }
1566                         if (!strcasecmp(ContentType, "application/octet-stream")) {
1567                                 ContentType = GuessMimeType(SKEY(WCC->WBuf));
1568                         }
1569                 }
1570                 output_headers(0, 0, 0, 0, 0, 0);
1571                 http_transmit_thing(ContentType, 0);
1572         } else {
1573                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
1574                 output_headers(0, 0, 0, 0, 0, 0);
1575                 hprintf("Content-Type: text/plain\r\n");
1576                 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
1577                 end_burst();
1578         }
1579 }
1580
1581
1582 /*
1583  * Read any MIME part of a message, from the server, into memory.
1584  */
1585 char *load_mimepart(long msgnum, char *partnum)
1586 {
1587         char buf[SIZ];
1588         off_t bytes;
1589         char content_type[SIZ];
1590         char *content;
1591         
1592         serv_printf("DLAT %ld|%s", msgnum, partnum);
1593         serv_getln(buf, sizeof buf);
1594         if (buf[0] == '6') {
1595                 bytes = extract_long(&buf[4], 0);
1596                 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1597
1598                 content = malloc(bytes + 2);
1599                 serv_read(content, bytes);
1600
1601                 content[bytes] = 0;     /* null terminate for good measure */
1602                 return(content);
1603         }
1604         else {
1605                 return(NULL);
1606         }
1607 }
1608
1609 /*
1610  * Read any MIME part of a message, from the server, into memory.
1611  */
1612 void MimeLoadData(wc_mime_attachment *Mime)
1613 {
1614         char buf[SIZ];
1615         off_t bytes;
1616 /* TODO: is there a chance the contenttype is different  to the one we know?     */
1617         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1618         serv_getln(buf, sizeof buf);
1619         if (buf[0] == '6') {
1620                 bytes = extract_long(&buf[4], 0);
1621
1622                 if (Mime->Data == NULL)
1623                         Mime->Data = NewStrBufPlain(NULL, bytes);
1624                 StrBuf_ServGetBLOB(Mime->Data, bytes);
1625
1626         }
1627         else {
1628                 FlushStrBuf(Mime->Data);
1629                 /* TODO XImportant message */
1630         }
1631 }
1632
1633
1634
1635
1636 void view_mimepart(void) {
1637         mimepart(0);
1638 }
1639
1640 void download_mimepart(void) {
1641         mimepart(1);
1642 }
1643
1644 void view_postpart(void) {
1645         postpart(WC->UrlFragment2,
1646                  WC->UrlFragment3,
1647                  0);
1648 }
1649
1650 void download_postpart(void) {
1651         postpart(WC->UrlFragment2,
1652                  WC->UrlFragment3,
1653                  1);
1654 }
1655
1656 void h_readnew(void) { readloop(readnew);}
1657 void h_readold(void) { readloop(readold);}
1658 void h_readfwd(void) { readloop(readfwd);}
1659 void h_headers(void) { readloop(headers);}
1660 void h_do_search(void) { readloop(do_search);}
1661
1662 void jsonMessageListHdr(void) 
1663 {
1664         /* TODO: make a generic function */
1665   hprintf("HTTP/1.1 200 OK\r\n");
1666   hprintf("Content-type: application/json; charset=utf-8\r\n");
1667   hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
1668   hprintf("Connection: close\r\n");
1669   hprintf("Pragma: no-cache\r\nCache-Control: no-store\r\nExpires:-1\r\n");
1670   begin_burst();
1671 }
1672 /* Spit out the new summary view. This is basically a static page, so clients can cache the layout, all the dirty work is javascript :) */
1673 void new_summary_view(void) {
1674   begin_burst();
1675   DoTemplate(HKEY("msg_listview"),NULL,&NoCtx);
1676   DoTemplate(HKEY("trailing"),NULL,&NoCtx);
1677   end_burst();
1678 }
1679 /** Output message list in JSON-format */
1680 void jsonMessageList(void) {
1681   const StrBuf *room = sbstr("room");
1682   long oper = (havebstr("query")) ? do_search : readnew;
1683   WC->is_ajax = 1; 
1684   gotoroom(room);
1685   readloop(oper);
1686   WC->is_ajax = 0;
1687 }
1688
1689 void 
1690 InitModule_MSG
1691 (void)
1692 {
1693         RegisterPreference("use_sig",
1694                            _("Attach signature to email messages?"), 
1695                            PRF_YESNO, 
1696                            NULL);
1697         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
1698         RegisterPreference("default_header_charset", 
1699                            _("Default character set for email headers:"), 
1700                            PRF_STRING, 
1701                            NULL);
1702         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
1703         RegisterPreference("defaultname", 
1704                            _("Preferred display name for email messages"), 
1705                            PRF_STRING, 
1706                            NULL);
1707         RegisterPreference("defaulthandle", 
1708                            _("Preferred display name for bulletin board posts"), 
1709                            PRF_STRING, 
1710                            NULL);
1711         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
1712
1713         WebcitAddUrlHandler(HKEY("readnew"), h_readnew, NEED_URL);
1714         WebcitAddUrlHandler(HKEY("readold"), h_readold, NEED_URL);
1715         WebcitAddUrlHandler(HKEY("readfwd"), h_readfwd, NEED_URL);
1716         WebcitAddUrlHandler(HKEY("headers"), h_headers, NEED_URL);
1717         WebcitAddUrlHandler(HKEY("do_search"), h_do_search, 0);
1718         WebcitAddUrlHandler(HKEY("display_enter"), display_enter, 0);
1719         WebcitAddUrlHandler(HKEY("post"), post_message, 0);
1720         WebcitAddUrlHandler(HKEY("move_msg"), move_msg, 0);
1721         WebcitAddUrlHandler(HKEY("delete_msg"), delete_msg, 0);
1722         WebcitAddUrlHandler(HKEY("confirm_move_msg"), confirm_move_msg, 0);
1723         WebcitAddUrlHandler(HKEY("msg"), embed_message, NEED_URL|AJAX);
1724         WebcitAddUrlHandler(HKEY("printmsg"), print_message, NEED_URL);
1725         WebcitAddUrlHandler(HKEY("mobilemsg"), mobile_message_view, NEED_URL);
1726         WebcitAddUrlHandler(HKEY("msgheaders"), display_headers, NEED_URL);
1727
1728         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1729         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1730         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
1731         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
1732
1733         /* json */
1734         WebcitAddUrlHandler(HKEY("roommsgs"), jsonMessageList,0);
1735         return ;
1736 }