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