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