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