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