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