* Fixes NB#86199, added support to message/rfc822 messages as attachments
[modest] / src / modest-tny-msg.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <string.h>
31 #include <gtkhtml/gtkhtml.h>
32 #include <tny-gtk-text-buffer-stream.h>
33 #include <tny-simple-list.h>
34 #include <tny-folder.h>
35 #include <modest-runtime.h>
36 #include "modest-formatter.h"
37 #include <tny-camel-mem-stream.h>
38 #include <tny-camel-mime-part.h>
39 #include <glib/gprintf.h>
40 #include <modest-tny-folder.h>
41 #include "modest-tny-mime-part.h"
42 #include <modest-error.h>
43
44
45 #ifdef HAVE_CONFIG_H
46 #include <config.h>
47 #endif /*HAVE_CONFIG_H */
48
49 #include <modest-tny-msg.h>
50 #include "modest-text-utils.h"
51
52 static TnyMimePart * add_body_part (TnyMsg *msg, const gchar *body,
53                                     const gchar *content_type);
54 static TnyMimePart * add_html_body_part (TnyMsg *msg, const gchar *body);
55 static gint add_attachments (TnyMimePart *part, GList *attachments_list, gboolean add_inline, GError **err);
56 static void add_images (TnyMsg *msg, GList *attachments_list, GError **err);
57 static char * get_content_type(const gchar *s);
58 static gboolean is_ascii(const gchar *s);
59
60
61 TnyMsg*
62 modest_tny_msg_new (const gchar* mailto, const gchar* from, const gchar *cc,
63                     const gchar *bcc, const gchar* subject, const gchar *body,
64                     GList *attachments, gint *attached, GError **err)
65 {
66         TnyMsg *new_msg;
67         TnyHeader *header;
68         gchar *content_type;
69         gint tmp_attached = 0;
70         
71         /* Create new msg */
72         new_msg = modest_formatter_create_message (NULL, TRUE, (attachments != NULL), FALSE);
73         header  = tny_msg_get_header (new_msg);
74         
75         if ((from != NULL) && (strlen(from) > 0)) {
76                 tny_header_set_from (TNY_HEADER (header), from);
77                 tny_header_set_replyto (TNY_HEADER (header), from);
78         }
79         if ((mailto != NULL) && (strlen(mailto) > 0)) 
80                 tny_header_set_to (TNY_HEADER (header), mailto);
81         if ((cc != NULL) && (strlen(cc) > 0)) 
82                 tny_header_set_cc (TNY_HEADER (header), cc);
83         if ((bcc != NULL) && (strlen(bcc) > 0)) 
84                 tny_header_set_bcc (TNY_HEADER (header), bcc);
85         
86         if ((subject != NULL) && (strlen(subject) > 0)) 
87                 tny_header_set_subject (TNY_HEADER (header), subject);
88
89         content_type = get_content_type(body);
90
91         /* set modest as the X-Mailer
92          * we could this in the platform factory, but then the header
93          * would show up before all the others.
94          */
95         tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "X-Mailer", "Modest "
96                                        VERSION);
97         
98         /* Add the body of the new mail */
99         /* This is needed even if body is NULL or empty. */
100         add_body_part (new_msg, body, content_type);
101         g_free (content_type);
102                        
103         /* Add attachments */
104         if (attachments)
105                 tmp_attached = add_attachments (TNY_MIME_PART (new_msg), attachments, FALSE, err);
106         if (attached)
107                 *attached = tmp_attached;
108         if (header)
109                 g_object_unref(header);
110
111         return new_msg;
112 }
113
114 TnyMsg*
115 modest_tny_msg_new_html_plain (const gchar* mailto, const gchar* from, const gchar *cc,
116                                const gchar *bcc, const gchar* subject, 
117                                const gchar *html_body, const gchar *plain_body,
118                                GList *attachments, GList *images, gint *attached, GError **err)
119 {
120         TnyMsg *new_msg;
121         TnyHeader *header;
122         gchar *content_type;
123         gint tmp_attached;
124         
125         /* Create new msg */
126         new_msg = modest_formatter_create_message (NULL, FALSE, (attachments != NULL), (images != NULL));
127         header  = tny_msg_get_header (new_msg);
128         
129         if ((from != NULL) && (strlen(from) > 0)) {
130                 tny_header_set_from (TNY_HEADER (header), from);
131                 tny_header_set_replyto (TNY_HEADER (header), from);
132         }
133         if ((mailto != NULL) && (strlen(mailto) > 0)) 
134                 tny_header_set_to (TNY_HEADER (header), mailto);
135         if ((cc != NULL) && (strlen(cc) > 0)) 
136                 tny_header_set_cc (TNY_HEADER (header), cc);
137         if ((bcc != NULL) && (strlen(bcc) > 0)) 
138                 tny_header_set_bcc (TNY_HEADER (header), bcc);
139         
140         if ((subject != NULL) && (strlen(subject) > 0)) 
141                 tny_header_set_subject (TNY_HEADER (header), subject);
142
143         content_type = get_content_type(plain_body);
144         
145         /* set modest as the X-Mailer
146          * we could this in the platform factory, but then the header
147          * would show up before all the others.
148          */
149         tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "X-Mailer", "Modest "
150                                        VERSION);
151
152         /* Add the body of the new mail */      
153         add_body_part (new_msg, plain_body, content_type);
154         add_html_body_part (new_msg, html_body);
155         g_free (content_type);
156                        
157         /* Add attachments */
158         tmp_attached = add_attachments (TNY_MIME_PART (new_msg), attachments, FALSE, err);
159         if (attached)
160                 *attached = tmp_attached;
161         add_images (new_msg, images, err);
162         if (header)
163                 g_object_unref(header);
164
165         return new_msg;
166 }
167
168
169 /* FIXME: this func copy from modest-mail-operation: refactor */
170 static TnyMimePart *
171 add_body_part (TnyMsg *msg, 
172                const gchar *body,
173                const gchar *content_type)
174 {
175         TnyMimePart *text_body_part = NULL;
176         TnyStream *text_body_stream;
177
178         /* Create the stream */
179         text_body_stream = TNY_STREAM (tny_camel_mem_stream_new_with_buffer
180                                         (body, (body ? strlen(body) : 0)));
181
182         text_body_part = modest_formatter_create_body_part (NULL, msg);
183
184         /* Construct MIME part */
185         tny_stream_reset (text_body_stream);
186         tny_mime_part_construct (text_body_part,
187                                  text_body_stream,
188                                  content_type, "7bit");
189         tny_stream_reset (text_body_stream);
190
191         g_object_unref (G_OBJECT(text_body_part));
192
193         /* Clean */
194         g_object_unref (text_body_stream);
195
196         return text_body_part;
197 }
198
199 static TnyMimePart *
200 add_html_body_part (TnyMsg *msg, 
201                     const gchar *body)
202 {
203         TnyMimePart *html_body_part = NULL;
204         TnyStream *html_body_stream;
205
206         /* Create the stream */
207         html_body_stream = TNY_STREAM (tny_camel_mem_stream_new_with_buffer
208                                         (body, strlen(body)));
209
210         /* Create body part if needed */
211         html_body_part = modest_formatter_create_body_part (NULL, msg);
212
213         /* Construct MIME part */
214         tny_stream_reset (html_body_stream);
215         tny_mime_part_construct (html_body_part,
216                                  html_body_stream,
217                                  "text/html; charset=utf-8", 
218                                  "7bit"); /* Sometimes it might be needed 
219                                              to make this one a 8bit! */
220         tny_stream_reset (html_body_stream);
221
222         g_object_unref (G_OBJECT(html_body_part));
223
224         /* Clean */
225         g_object_unref (html_body_stream);
226
227         return html_body_part;
228 }
229
230 static TnyMimePart *
231 copy_mime_part (TnyMimePart *part, GError **err)
232 {
233         TnyMimePart *result = NULL;
234         const gchar *attachment_content_type;
235         const gchar *attachment_filename;
236         const gchar *attachment_cid;
237         TnyList *parts;
238         TnyIterator *iterator;
239         TnyStream *attachment_stream;
240         const gchar *enc;
241         gint ret;
242         
243         if (TNY_IS_MSG (part)) {
244                 g_object_ref (part);
245                 return part;
246         }
247
248         result = tny_platform_factory_new_mime_part (
249                 modest_runtime_get_platform_factory());
250
251         attachment_content_type = tny_mime_part_get_content_type (part);
252
253         /* get mime part headers */
254         attachment_filename = tny_mime_part_get_filename (part);
255         attachment_cid = tny_mime_part_get_content_id (part);
256         
257         /* fill the stream */
258         attachment_stream = tny_mime_part_get_decoded_stream (part);
259         enc = tny_mime_part_get_transfer_encoding (part);
260         if (attachment_stream == NULL) {
261                 if (err != NULL && *err == NULL)
262                         g_set_error (err, MODEST_MAIL_OPERATION_ERROR, MODEST_MAIL_OPERATION_ERROR_FILE_IO, _("TODO: couldn't retrieve attachment"));
263                 g_object_unref (result);
264                 return NULL;
265         } else {
266                 ret = tny_stream_reset (attachment_stream);
267                 ret = tny_mime_part_construct (result,
268                                                attachment_stream,
269                                                attachment_content_type, 
270                                                enc);
271                 ret = tny_stream_reset (attachment_stream);
272         }
273         
274         /* set other mime part fields */
275         tny_mime_part_set_filename (result, attachment_filename);
276         tny_mime_part_set_content_id (result, attachment_cid);
277
278         /* copy subparts */
279         parts = tny_simple_list_new ();
280         tny_mime_part_get_parts (part, parts);
281         iterator = tny_list_create_iterator (parts);
282         while (!tny_iterator_is_done (iterator)) {
283                 TnyMimePart *subpart = TNY_MIME_PART (tny_iterator_get_current (iterator));
284                 if (subpart) {
285                         const gchar *subpart_cid;
286                         TnyMimePart *subpart_copy = copy_mime_part (subpart, err);
287                         if (subpart_copy != NULL) {
288                                 subpart_cid = tny_mime_part_get_content_id (subpart);
289                                 tny_mime_part_add_part (result, subpart_copy);
290                                 if (subpart_cid)
291                                         tny_mime_part_set_content_id (result, subpart_cid);
292                                 g_object_unref (subpart_copy);
293                         }
294                         g_object_unref (subpart);
295                 }
296
297                 tny_iterator_next (iterator);
298         }
299         g_object_unref (iterator);
300         g_object_unref (parts);
301         g_object_unref (attachment_stream);
302
303         return result;
304 }
305
306 static gint
307 add_attachments (TnyMimePart *part, GList *attachments_list, gboolean add_inline, GError **err)
308 {
309         GList *pos;
310         TnyMimePart *attachment_part, *old_attachment;
311         gint ret;
312         gint attached = 0;
313
314         for (pos = (GList *)attachments_list; pos; pos = pos->next) {
315
316                 old_attachment = pos->data;
317                 if (!tny_mime_part_is_purged (old_attachment)) {
318                         const gchar *old_cid;
319                         old_cid = tny_mime_part_get_content_id (old_attachment);
320                         attachment_part = copy_mime_part (old_attachment, err);
321                         if (attachment_part != NULL) {
322                                 if (add_inline) {
323                                         tny_mime_part_set_header_pair (attachment_part, "Content-Disposition",
324                                                                        "inline");
325                                 } else {
326                                         const gchar *filename;
327                                         filename = tny_mime_part_get_filename (old_attachment);
328                                         if (filename)
329                                                 tny_mime_part_set_filename (attachment_part, filename);
330                                         else
331                                                 tny_mime_part_set_header_pair (attachment_part, "Content-Disposition",
332                                                                                "attachment");
333                                 }
334                                 tny_mime_part_set_transfer_encoding (TNY_MIME_PART (attachment_part), "base64");
335                                 ret = tny_mime_part_add_part (TNY_MIME_PART (part), attachment_part);
336                                 attached++;
337                                 if (old_cid)
338                                         tny_mime_part_set_content_id (attachment_part, old_cid);
339                                 g_object_unref (attachment_part);
340                         }
341                 }
342         }
343         return attached;
344 }
345
346 static void
347 add_images (TnyMsg *msg, GList *images_list, GError **err)
348 {
349         TnyMimePart *related_part = NULL;
350         const gchar *content_type;
351
352         content_type = tny_mime_part_get_content_type (TNY_MIME_PART (msg));
353
354         if ((content_type != NULL) && !strcasecmp (content_type, "multipart/related")) {
355                 related_part = g_object_ref (msg);
356         } else if ((content_type != NULL) && !strcasecmp (content_type, "multipart/mixed")) {
357                 TnyList *parts = TNY_LIST (tny_simple_list_new ());
358                 TnyIterator *iter = NULL;
359                 tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
360                 iter = tny_list_create_iterator (parts);
361
362                 while (!tny_iterator_is_done (iter)) {
363                         TnyMimePart *part = TNY_MIME_PART (tny_iterator_get_current (iter));
364                         if (part && !g_strcasecmp (tny_mime_part_get_content_type (part), "multipart/related")) {
365                                 related_part = part;
366                                 break;
367                         } else {
368                                 g_object_unref (part);
369                         }
370                         tny_iterator_next (iter);
371                 }
372                 g_object_unref (iter);
373                 g_object_unref (parts);
374         }
375
376         if (related_part != NULL) {
377                 /* TODO: attach images in their proper place */
378                 add_attachments (related_part, images_list, TRUE, err);
379                 g_object_unref (related_part);
380         }
381 }
382
383
384 gchar * 
385 modest_tny_msg_get_body (TnyMsg *msg, gboolean want_html, gboolean *is_html)
386 {
387         TnyStream *stream;
388         TnyMimePart *body;
389         GtkTextBuffer *buf;
390         GtkTextIter start, end;
391         gchar *to_quote;
392         gboolean result_was_html = TRUE;
393
394         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
395         
396         body = modest_tny_msg_find_body_part(msg, want_html);
397         if (!body)
398                 return NULL;
399
400         buf = gtk_text_buffer_new (NULL);
401         stream = TNY_STREAM (tny_gtk_text_buffer_stream_new (buf));
402         tny_stream_reset (stream);
403         tny_mime_part_decode_to_stream (body, stream, NULL);
404         tny_stream_reset (stream);
405         
406         gtk_text_buffer_get_bounds (buf, &start, &end);
407         to_quote = gtk_text_buffer_get_text (buf, &start, &end, FALSE);
408         if (tny_mime_part_content_type_is (body, "text/plain")) {
409                 gchar *to_quote_converted = modest_text_utils_convert_to_html (to_quote);
410                 g_free (to_quote);
411                 to_quote = to_quote_converted;
412                 result_was_html = FALSE;
413         }
414
415         g_object_unref (buf);
416         g_object_unref (G_OBJECT(stream));
417         g_object_unref (G_OBJECT(body));
418
419         if (is_html != NULL)
420                 *is_html = result_was_html;
421
422         return to_quote;
423 }
424
425
426 TnyMimePart*
427 modest_tny_msg_find_body_part_from_mime_part (TnyMimePart *msg, gboolean want_html)
428 {
429         const gchar *desired_mime_type = want_html ? "text/html" : "text/plain";
430         TnyMimePart *part = NULL;
431         TnyList *parts = NULL;
432         TnyIterator *iter = NULL;
433         gchar *header_content_type;
434         gchar *header_content_type_lower = NULL;
435         
436         if (!msg)
437                 return NULL;
438
439         /* If it's an application multipart, then we don't get into as we don't
440          * support them (for example application/sml or wap messages */
441         header_content_type = modest_tny_mime_part_get_header_value (msg, "Content-Type");
442         if (header_content_type) {
443                 header_content_type = g_strstrip (header_content_type);
444                 header_content_type_lower = g_ascii_strdown (header_content_type, -1);
445         }
446         if (header_content_type_lower && 
447             g_str_has_prefix (header_content_type_lower, "multipart/") &&
448             !g_str_has_prefix (header_content_type_lower, "multipart/signed") &&
449             strstr (header_content_type_lower, "application/")) {
450                 g_free (header_content_type_lower);
451                 g_free (header_content_type);
452                 return NULL;
453         }       
454         g_free (header_content_type_lower);
455         g_free (header_content_type);
456
457         parts = TNY_LIST (tny_simple_list_new());
458         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
459
460         iter  = tny_list_create_iterator(parts);
461
462         /* no parts? assume it's single-part message */
463         if (tny_iterator_is_done(iter)) {
464                 gchar *content_type;
465                 gchar *content_type_lower;
466                 gboolean is_text_part;
467                 g_object_unref (G_OBJECT(iter));
468                 content_type = g_strdup (tny_mime_part_get_content_type (msg));
469                 if (content_type == NULL)
470                         return NULL;
471                 content_type = g_strstrip (content_type);
472                 content_type_lower = g_ascii_strdown (content_type, -1);
473                 g_free (content_type);
474                 is_text_part = 
475                         g_str_has_prefix (content_type_lower, "text/") ||
476                         g_str_has_prefix (content_type_lower, "message/rfc822");
477                 g_free (content_type_lower);
478                 /* if this part cannot be a supported body return NULL */
479                 if (!is_text_part) {
480                         return NULL;
481                 } else {
482                         return TNY_MIME_PART (g_object_ref(G_OBJECT(msg)));
483                 }
484         } else {
485                 do {
486                         gchar *tmp, *content_type = NULL;
487                         gboolean has_content_disp_name = FALSE;
488
489                         part = TNY_MIME_PART(tny_iterator_get_current (iter));
490
491                         if (!part) {
492                                 g_warning ("%s: not a valid mime part", __FUNCTION__);
493                                 continue;
494                         }
495
496                         /* it's a message --> ignore */
497                         if (part && TNY_IS_MSG (part)) {
498                                 g_object_unref (part);
499                                 tny_iterator_next (iter);
500                                 continue;
501                         }                       
502
503                         /* we need to strdown the content type, because
504                          * tny_mime_part_has_content_type does not do it...
505                          */
506                         content_type = g_ascii_strdown (tny_mime_part_get_content_type (part), -1);
507                         
508                         /* mime-parts with a content-disposition header (either 'inline' or 'attachment')
509                          * and a 'name=' thingy cannot be body parts
510                          */
511                                 
512                         tmp = modest_tny_mime_part_get_header_value (part, "Content-Disposition");
513                         if (tmp) {
514                                 gchar *content_disp = g_ascii_strdown(tmp, -1);
515                                 g_free (tmp);
516                                 has_content_disp_name = g_strstr_len (content_disp, strlen(content_disp), "name=") != NULL;
517                                 g_free (content_disp);
518                         }
519                         
520                         if (g_str_has_prefix (content_type, desired_mime_type) && 
521                             !has_content_disp_name &&
522                             !modest_tny_mime_part_is_attachment_for_modest (part)) {
523                                 /* we found the desired mime-type! */
524                                 g_free (content_type);
525                                 break;
526
527                         } else  if (g_str_has_prefix(content_type, "multipart")) {
528
529                                 /* multipart? recurse! */
530                                 g_object_unref (part);
531                                 g_free (content_type);
532                                 part = modest_tny_msg_find_body_part_from_mime_part (part, want_html);
533                                 if (part)
534                                         break;
535                         } else
536                                 g_free (content_type);
537                         
538                         if (part) {
539                                 g_object_unref (G_OBJECT(part));
540                                 part = NULL;
541                         }
542                         
543                         tny_iterator_next (iter);
544                         
545                 } while (!tny_iterator_is_done(iter));
546         }
547         
548         g_object_unref (G_OBJECT(iter));
549         g_object_unref (G_OBJECT(parts));
550
551         /* if were trying to find an HTML part and couldn't find it,
552          * try to find a text/plain part instead
553          */
554         if (!part && want_html) 
555                 return modest_tny_msg_find_body_part_from_mime_part (msg, FALSE);
556         else
557                 return part; /* this maybe NULL, this is not an error; some message just don't have a body
558                               * part */
559 }
560
561
562 TnyMimePart*
563 modest_tny_msg_find_body_part (TnyMsg *msg, gboolean want_html)
564 {
565         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
566         
567         return modest_tny_msg_find_body_part_from_mime_part (TNY_MIME_PART(msg),
568                                                              want_html);
569 }
570
571
572 #define MODEST_TNY_MSG_PARENT_UID "parent-uid"
573
574 static TnyMsg *
575 create_reply_forward_mail (TnyMsg *msg, TnyHeader *header, const gchar *from,
576                            const gchar *signature, gboolean is_reply,
577                            guint type /*ignored*/, GList *attachments)
578 {
579         TnyMsg *new_msg;
580         TnyHeader *new_header;
581         gchar *old_subject;
582         gchar *new_subject;
583         TnyMimePart *body = NULL;
584         ModestFormatter *formatter;
585         gchar *subject_prefix;
586         gboolean no_text_part;
587         
588         if (header)
589                 g_object_ref (header);
590         else
591                 header = tny_msg_get_header (msg);
592
593         /* Get body from original msg. Always look for the text/plain
594            part of the message to create the reply/forwarded mail */
595         if (msg != NULL)
596                 body   = modest_tny_msg_find_body_part (msg, FALSE);
597         
598         if (modest_conf_get_bool (modest_runtime_get_conf (), MODEST_CONF_PREFER_FORMATTED_TEXT,
599                                   NULL))
600                 formatter = modest_formatter_new ("text/html", signature);
601         else
602                 formatter = modest_formatter_new ("text/plain", signature);
603         
604
605         /* if we don't have a text-part */
606         no_text_part = (!body) || (strcmp (tny_mime_part_get_content_type (body), "text/html")==0);
607         
608         /* when we're reply, include the text part if we have it, or nothing otherwise. */
609         if (is_reply)
610                 new_msg = modest_formatter_quote  (formatter, no_text_part ? NULL: body, header,
611                                                     attachments);
612         else {
613                 /* for attachements; inline if there is a text part, and include the
614                  * full old mail if there was none */
615                 if (no_text_part) {
616                         new_msg = modest_formatter_attach (formatter, msg, header);
617                 } else { 
618                         new_msg = modest_formatter_inline  (formatter, body, header,
619                                                             attachments);
620                 }
621         }
622         
623         g_object_unref (G_OBJECT(formatter));
624         if (body)
625                 g_object_unref (G_OBJECT(body));
626         
627         /* Fill the header */
628         new_header = tny_msg_get_header (new_msg);      
629         tny_header_set_from (new_header, from);
630         tny_header_set_replyto (new_header, from);
631
632         /* Change the subject */
633         if (is_reply)
634                 subject_prefix = g_strconcat (_("mail_va_re"), ":", NULL);
635         else
636                 subject_prefix = g_strconcat (_("mail_va_fw"), ":", NULL);
637         old_subject = tny_header_dup_subject (header);
638         new_subject =
639                 (gchar *) modest_text_utils_derived_subject (old_subject,
640                                                              subject_prefix);
641         g_free (old_subject);
642         g_free (subject_prefix);
643         tny_header_set_subject (new_header, (const gchar *) new_subject);
644         g_free (new_subject);
645         
646         /* get the parent uid, and set it as a gobject property on the new msg */
647         if (new_msg) {
648                 gchar* parent_uid = modest_tny_folder_get_header_unique_id (header);
649                 g_object_set_data_full (G_OBJECT(new_msg), MODEST_TNY_MSG_PARENT_UID,
650                                         parent_uid, g_free);
651         }
652
653         /* set modest as the X-Mailer
654          * we could this in the platform factory, but then the header
655          * would show up before all the others.
656          */
657         tny_mime_part_set_header_pair (TNY_MIME_PART (msg), "X-Mailer", "Modest "
658                                        VERSION);
659
660         /* Clean */
661         g_object_unref (G_OBJECT (new_header));
662         g_object_unref (G_OBJECT (header));
663         /* ugly to unref it here instead of in the calling func */
664
665         if (!is_reply & !no_text_part) {
666                 add_attachments (TNY_MIME_PART (new_msg), attachments, FALSE, NULL);
667         }
668
669         return new_msg;
670 }
671
672 const gchar*
673 modest_tny_msg_get_parent_uid (TnyMsg *msg)
674 {
675         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
676         
677         return g_object_get_data (G_OBJECT(msg), MODEST_TNY_MSG_PARENT_UID);
678 }
679
680
681
682 static void
683 add_if_attachment (gpointer data, gpointer user_data)
684 {
685         TnyMimePart *part;
686         GList **attachments_list;
687
688         part = TNY_MIME_PART (data);
689         attachments_list = ((GList **) user_data);
690
691         if ((tny_mime_part_is_attachment (part))||(TNY_IS_MSG (part))) {
692                 *attachments_list = g_list_prepend (*attachments_list, part);
693                 g_object_ref (part);
694         }
695 }
696
697 TnyMsg* 
698 modest_tny_msg_create_forward_msg (TnyMsg *msg, 
699                                    const gchar *from,
700                                    const gchar *signature,
701                                    ModestTnyMsgForwardType forward_type)
702 {
703         TnyMsg *new_msg;
704         TnyList *parts = NULL;
705         GList *attachments_list = NULL;
706
707         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
708         
709         /* Add attachments */
710         parts = TNY_LIST (tny_simple_list_new());
711         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
712         tny_list_foreach (parts, add_if_attachment, &attachments_list);
713
714         new_msg = create_reply_forward_mail (msg, NULL, from, signature, FALSE, forward_type,
715                                              attachments_list);
716
717         /* Clean */
718         if (attachments_list) {
719                 g_list_foreach (attachments_list, (GFunc) g_object_unref, NULL);
720                 g_list_free (attachments_list);
721         }
722         g_object_unref (G_OBJECT (parts));
723
724         return new_msg;
725 }
726
727
728
729 static gint
730 count_addresses (const gchar* addresses)
731 {
732         gint count = 1;
733
734         if (!addresses)
735                 return 0;
736         
737         while (*addresses) {
738                 if (*addresses == ',' || *addresses == ';')
739                         ++count;
740                 ++addresses;
741         }
742         
743         return count;
744 }
745
746
747 /* get the new To:, based on the old header,
748  * result is newly allocated or NULL in case of error
749  * */
750 static gchar*
751 get_new_to (TnyMsg *msg, TnyHeader *header, const gchar* from,
752             ModestTnyMsgReplyMode reply_mode)
753 {
754         const gchar* old_reply_to;
755         gchar* old_from;
756         gchar* new_to;
757         
758         /* according to RFC2369 (http://www.faqs.org/rfcs/rfc2369.html), we
759          * can identify Mailing-List posts by the List-Help header.
760          * for mailing lists, both the Reply-To: and From: should be included
761          * in the new To:; for now, we're ignoring List-Post
762          */
763         gchar* list_help = modest_tny_mime_part_get_header_value (TNY_MIME_PART(msg), 
764                                                                   "List-Help");
765         gboolean is_mailing_list = (list_help != NULL);
766         g_free (list_help);
767
768
769         /* reply to sender, use ReplyTo or From */
770         //old_reply_to = tny_header_get_replyto (header);
771         old_reply_to = modest_tny_mime_part_get_header_value (TNY_MIME_PART(msg), 
772                                                               "Reply-To"); 
773         old_from     = tny_header_dup_from (header);
774         
775         if (!old_from &&  !old_reply_to) {
776                 g_warning ("%s: failed to get either Reply-To: or From: from header",
777                            __FUNCTION__);
778                 return NULL;
779         }
780         
781         /* for mailing lists, use both Reply-To and From if we did a
782          * 'Reply All:'
783          * */
784         if (is_mailing_list && reply_mode == MODEST_TNY_MSG_REPLY_MODE_ALL &&
785             old_reply_to && old_from && strcmp (old_from, old_reply_to) != 0)
786                 new_to = g_strjoin (",", old_reply_to, old_from, NULL);
787         else
788                 /* otherwise use either Reply-To: (preferred) or From: */
789                 new_to = g_strdup (old_reply_to ? old_reply_to : old_from);
790         g_free (old_from);
791
792         /* in case of ReplyAll, we need to add the Recipients in the old To: */
793         if (reply_mode == MODEST_TNY_MSG_REPLY_MODE_ALL) {
794                 gchar *old_to = tny_header_dup_to (header);
795                 if (!old_to) 
796                         g_warning ("%s: no To: address found in source mail",
797                                    __FUNCTION__);
798                 else {
799                         /* append the old To: */
800                         gchar *tmp = g_strjoin (",", new_to, old_to, NULL);
801                         g_free (new_to);
802                         new_to = tmp;
803                         g_free (old_to);
804                 }
805
806                 /* remove duplicate entries */
807                 gchar *tmp = modest_text_utils_remove_duplicate_addresses (new_to);
808                 g_free (new_to);
809                 new_to = tmp;
810                 
811                 /* now, strip me (the new From:) from the new_to, but only if
812                  * there are >1 addresses there */
813                 if (count_addresses (new_to) > 1) {
814                         gchar *tmp = modest_text_utils_remove_address (new_to, from);
815                         g_free (new_to);
816                         new_to = tmp;
817                 }
818         }
819
820         return new_to;
821 }
822
823
824 /* get the new Cc:, based on the old header,
825  * result is newly allocated or NULL in case of error */
826 static gchar*
827 get_new_cc (TnyHeader *header, const gchar* from)
828 {
829         gchar *old_cc;
830         gchar *result;
831
832         old_cc = tny_header_dup_cc (header);
833         if (!old_cc)
834                 return NULL;
835
836         /* remove me (the new From:) from the Cc: list */
837         result =  modest_text_utils_remove_address (old_cc, from);
838         g_free (old_cc);
839         return result;
840 }
841
842
843 TnyMsg* 
844 modest_tny_msg_create_reply_msg (TnyMsg *msg,
845                                  TnyHeader *header,
846                                  const gchar *from,
847                                  const gchar *signature,
848                                  ModestTnyMsgReplyType reply_type,
849                                  ModestTnyMsgReplyMode reply_mode)
850 {
851         TnyMsg *new_msg = NULL;
852         TnyHeader *new_header;
853         gchar *new_to = NULL;
854         TnyList *parts = NULL;
855         GList *attachments_list = NULL;
856
857         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
858         
859         parts = TNY_LIST (tny_simple_list_new());
860         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
861         tny_list_foreach (parts, add_if_attachment, &attachments_list);
862
863         new_msg = create_reply_forward_mail (msg, header, from, signature, TRUE, reply_type,
864                                              attachments_list);
865         if (attachments_list != NULL) {
866                 g_list_foreach (attachments_list, (GFunc) g_object_unref, NULL);
867                 g_list_free (attachments_list);
868         }
869         if (parts)
870                 g_object_unref (G_OBJECT (parts));
871
872         /* Fill the header */
873         if (header)
874                 g_object_ref (header);
875         else
876                 header = tny_msg_get_header (msg);
877
878         
879         new_header = tny_msg_get_header(new_msg);
880         new_to = get_new_to (msg, header, from, reply_mode);
881         if (!new_to)
882                 g_warning ("%s: failed to get new To:", __FUNCTION__);
883         else {
884                 tny_header_set_to (new_header, new_to);
885                 g_free (new_to);
886         }       
887         
888         if (reply_mode == MODEST_TNY_MSG_REPLY_MODE_ALL) {
889                 gchar *new_cc = get_new_cc (header, from);
890                 if (new_cc) { 
891                         tny_header_set_cc (new_header, new_cc);
892                         g_free (new_cc);
893                 }
894         }
895         
896         /* Clean */
897         g_object_unref (G_OBJECT (new_header));
898         g_object_unref (G_OBJECT (header));
899
900         return new_msg;
901 }
902
903
904 static gboolean
905 is_ascii(const gchar *s)
906 {
907         if (!s)
908                 return TRUE;
909         while (s[0]) {
910                 if (s[0] & 128 || s[0] < 32)
911                         return FALSE;
912                 s++;
913         }
914         return TRUE;
915 }
916
917 static char *
918 get_content_type(const gchar *s)
919 {
920         GString *type;
921         
922         type = g_string_new("text/plain");
923         if (!is_ascii(s)) {
924                 if (g_utf8_validate(s, -1, NULL)) {
925                         g_string_append(type, "; charset=\"utf-8\"");
926                 } else {
927                         /* it should be impossible to reach this, but better safe than sorry */
928                         g_warning("invalid utf8 in message");
929                         g_string_append(type, "; charset=\"latin1\"");
930                 }
931         }
932         return g_string_free(type, FALSE);
933 }
934
935 guint64
936 modest_tny_msg_estimate_size (const gchar *plain_body, const gchar *html_body,
937                               guint64 parts_count,
938                               guint64 parts_size)
939 {
940         guint64 result;
941
942         /* estimation of headers size */
943         result = 1024;
944
945         /* We add a 20% of size due to the increase in 7bit encoding */
946         if (plain_body) {
947                 result += strlen (plain_body) * 120 / 100;
948         }
949         if (html_body) {
950                 result += strlen (html_body) * 120 / 100;
951         }
952
953         /* 256 bytes per additional part because of their headers */
954         result += parts_count * 256;
955
956         /* 150% of increase per encoding */
957         result += parts_size * 3 / 2;
958
959         return result;
960 }