f27c5eac2559b0983fedcc9ed16ec6f9e3b62fd0
[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-defs.h>
37 #include "modest-formatter.h"
38 #include <tny-camel-mem-stream.h>
39 #include <tny-camel-mime-part.h>
40 #include <glib/gprintf.h>
41 #include <modest-tny-folder.h>
42 #include "modest-tny-mime-part.h"
43 #include <modest-error.h>
44
45
46 #ifdef HAVE_CONFIG_H
47 #include <config.h>
48 #endif /*HAVE_CONFIG_H */
49
50 #include <modest-tny-msg.h>
51 #include "modest-text-utils.h"
52
53 static TnyMimePart * add_body_part (TnyMsg *msg, const gchar *body,
54                                     const gchar *content_type);
55 static TnyMimePart * add_html_body_part (TnyMsg *msg, const gchar *body);
56 static gint add_attachments (TnyMimePart *part, GList *attachments_list, gboolean add_inline, GError **err);
57 static void add_images (TnyMsg *msg, GList *attachments_list, GError **err);
58 static char * get_content_type(const gchar *s);
59 static gboolean is_ascii(const gchar *s);
60
61
62 TnyMsg*
63 modest_tny_msg_new (const gchar* mailto, const gchar* from, const gchar *cc,
64                     const gchar *bcc, const gchar* subject, 
65                     const gchar *references, const gchar *in_reply_to,
66                     const gchar *body,
67                     GList *attachments, gint *attached, GError **err)
68 {
69         TnyMsg *new_msg;
70         TnyHeader *header;
71         gchar *content_type;
72         gint tmp_attached = 0;
73         
74         /* Create new msg */
75         new_msg = modest_formatter_create_message (NULL, TRUE, (attachments != NULL), FALSE);
76         header  = tny_msg_get_header (new_msg);
77         
78         if ((from != NULL) && (strlen(from) > 0)) {
79                 tny_header_set_from (TNY_HEADER (header), from);
80                 tny_header_set_replyto (TNY_HEADER (header), from);
81         }
82         if ((mailto != NULL) && (strlen(mailto) > 0)) {
83                 gchar *removed_to = modest_text_utils_remove_duplicate_addresses (mailto);
84                 tny_header_set_to (TNY_HEADER (header), removed_to);
85                 g_free (removed_to);
86         }
87         if ((cc != NULL) && (strlen(cc) > 0)) 
88                 tny_header_set_cc (TNY_HEADER (header), cc);
89         if ((bcc != NULL) && (strlen(bcc) > 0)) 
90                 tny_header_set_bcc (TNY_HEADER (header), bcc);
91         
92         if ((subject != NULL) && (strlen(subject) > 0)) 
93                 tny_header_set_subject (TNY_HEADER (header), subject);
94
95         content_type = get_content_type(body);
96
97         /* set modest as the X-Mailer
98          * we could this in the platform factory, but then the header
99          * would show up before all the others.
100          */
101         tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "X-Mailer", "Modest "
102                                        VERSION);
103
104         if (references)
105                 tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "References", references);
106
107         if (in_reply_to)
108                 tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "In-Reply-To", in_reply_to);
109         
110         /* Add the body of the new mail */
111         /* This is needed even if body is NULL or empty. */
112         add_body_part (new_msg, body, content_type);
113         g_free (content_type);
114                        
115         /* Add attachments */
116         if (attachments)
117                 tmp_attached = add_attachments (TNY_MIME_PART (new_msg), attachments, FALSE, err);
118         if (attached)
119                 *attached = tmp_attached;
120         if (header)
121                 g_object_unref(header);
122
123         return new_msg;
124 }
125
126 TnyMsg*
127 modest_tny_msg_new_html_plain (const gchar* mailto, const gchar* from, const gchar *cc,
128                                const gchar *bcc, const gchar* subject, 
129                                const gchar *references, const gchar *in_reply_to,
130                                const gchar *html_body, const gchar *plain_body,
131                                GList *attachments, GList *images, gint *attached, GError **err)
132 {
133         TnyMsg *new_msg;
134         TnyHeader *header;
135         gchar *content_type;
136         gint tmp_attached;
137         
138         /* Create new msg */
139         new_msg = modest_formatter_create_message (NULL, FALSE, (attachments != NULL), (images != NULL));
140         header  = tny_msg_get_header (new_msg);
141         
142         if ((from != NULL) && (strlen(from) > 0)) {
143                 tny_header_set_from (TNY_HEADER (header), from);
144                 tny_header_set_replyto (TNY_HEADER (header), from);
145         }
146         if ((mailto != NULL) && (strlen(mailto) > 0)) 
147                 tny_header_set_to (TNY_HEADER (header), mailto);
148         if ((cc != NULL) && (strlen(cc) > 0)) 
149                 tny_header_set_cc (TNY_HEADER (header), cc);
150         if ((bcc != NULL) && (strlen(bcc) > 0)) 
151                 tny_header_set_bcc (TNY_HEADER (header), bcc);
152         
153         if ((subject != NULL) && (strlen(subject) > 0)) 
154                 tny_header_set_subject (TNY_HEADER (header), subject);
155
156         content_type = get_content_type(plain_body);
157         
158         /* set modest as the X-Mailer
159          * we could this in the platform factory, but then the header
160          * would show up before all the others.
161          */
162         tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "X-Mailer", "Modest "
163                                        VERSION);
164
165         if (references)
166                 tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "References", references);
167
168         if (in_reply_to)
169                 tny_mime_part_set_header_pair (TNY_MIME_PART (new_msg), "In-Reply-To", in_reply_to);
170         
171         /* Add the body of the new mail */      
172         add_body_part (new_msg, plain_body, content_type);
173         add_html_body_part (new_msg, html_body);
174         g_free (content_type);
175                        
176         /* Add attachments */
177         tmp_attached = add_attachments (TNY_MIME_PART (new_msg), attachments, FALSE, err);
178         if (attached)
179                 *attached = tmp_attached;
180         add_images (new_msg, images, err);
181         if (header)
182                 g_object_unref(header);
183
184         return new_msg;
185 }
186
187
188 /* FIXME: this func copy from modest-mail-operation: refactor */
189 static TnyMimePart *
190 add_body_part (TnyMsg *msg, 
191                const gchar *body,
192                const gchar *content_type)
193 {
194         TnyMimePart *text_body_part = NULL;
195         TnyStream *text_body_stream;
196
197         /* Create the stream */
198         text_body_stream = TNY_STREAM (tny_camel_mem_stream_new_with_buffer
199                                         (body, (body ? strlen(body) : 0)));
200
201         text_body_part = modest_formatter_create_body_part (NULL, msg);
202
203         /* Construct MIME part */
204         tny_stream_reset (text_body_stream);
205         tny_mime_part_construct (text_body_part,
206                                  text_body_stream,
207                                  content_type, "7bit");
208         tny_stream_reset (text_body_stream);
209
210         g_object_unref (G_OBJECT(text_body_part));
211
212         /* Clean */
213         g_object_unref (text_body_stream);
214
215         return text_body_part;
216 }
217
218 static TnyMimePart *
219 add_html_body_part (TnyMsg *msg, 
220                     const gchar *body)
221 {
222         TnyMimePart *html_body_part = NULL;
223         TnyStream *html_body_stream;
224
225         /* Create the stream */
226         html_body_stream = TNY_STREAM (tny_camel_mem_stream_new_with_buffer
227                                         (body, strlen(body)));
228
229         /* Create body part if needed */
230         html_body_part = modest_formatter_create_body_part (NULL, msg);
231
232         /* Construct MIME part */
233         tny_stream_reset (html_body_stream);
234         tny_mime_part_construct (html_body_part,
235                                  html_body_stream,
236                                  "text/html; charset=utf-8", 
237                                  "7bit"); /* Sometimes it might be needed 
238                                              to make this one a 8bit! */
239         tny_stream_reset (html_body_stream);
240
241         g_object_unref (G_OBJECT(html_body_part));
242
243         /* Clean */
244         g_object_unref (html_body_stream);
245
246         return html_body_part;
247 }
248
249 static TnyMimePart *
250 copy_mime_part (TnyMimePart *part, GError **err)
251 {
252         TnyMimePart *result = NULL;
253         const gchar *attachment_content_type;
254         const gchar *attachment_filename;
255         const gchar *attachment_cid;
256         TnyList *parts;
257         TnyIterator *iterator;
258         TnyStream *attachment_stream;
259         const gchar *enc;
260         gint ret;
261         
262         if (TNY_IS_MSG (part)) {
263                 g_object_ref (part);
264                 return part;
265         }
266
267         result = tny_platform_factory_new_mime_part (
268                 modest_runtime_get_platform_factory());
269
270         attachment_content_type = tny_mime_part_get_content_type (part);
271
272         /* get mime part headers */
273         attachment_filename = tny_mime_part_get_filename (part);
274         attachment_cid = tny_mime_part_get_content_id (part);
275         
276         /* fill the stream */
277         attachment_stream = tny_mime_part_get_decoded_stream (part);
278         enc = tny_mime_part_get_transfer_encoding (part);
279         if (attachment_stream == NULL) {
280                 if (err != NULL && *err == NULL)
281                         g_set_error (err, MODEST_MAIL_OPERATION_ERROR, MODEST_MAIL_OPERATION_ERROR_FILE_IO, _("TODO: couldn't retrieve attachment"));
282                 g_object_unref (result);
283                 return NULL;
284         } else {
285                 ret = tny_stream_reset (attachment_stream);
286                 ret = tny_mime_part_construct (result,
287                                                attachment_stream,
288                                                attachment_content_type, 
289                                                enc);
290                 ret = tny_stream_reset (attachment_stream);
291         }
292         
293         /* set other mime part fields */
294         tny_mime_part_set_filename (result, attachment_filename);
295         tny_mime_part_set_content_id (result, attachment_cid);
296
297         /* copy subparts */
298         parts = tny_simple_list_new ();
299         tny_mime_part_get_parts (part, parts);
300         iterator = tny_list_create_iterator (parts);
301         while (!tny_iterator_is_done (iterator)) {
302                 TnyMimePart *subpart = TNY_MIME_PART (tny_iterator_get_current (iterator));
303                 if (subpart) {
304                         const gchar *subpart_cid;
305                         TnyMimePart *subpart_copy = copy_mime_part (subpart, err);
306                         if (subpart_copy != NULL) {
307                                 subpart_cid = tny_mime_part_get_content_id (subpart);
308                                 tny_mime_part_add_part (result, subpart_copy);
309                                 if (subpart_cid)
310                                         tny_mime_part_set_content_id (result, subpart_cid);
311                                 g_object_unref (subpart_copy);
312                         }
313                         g_object_unref (subpart);
314                 }
315
316                 tny_iterator_next (iterator);
317         }
318         g_object_unref (iterator);
319         g_object_unref (parts);
320         g_object_unref (attachment_stream);
321
322         return result;
323 }
324
325 static gint
326 add_attachments (TnyMimePart *part, GList *attachments_list, gboolean add_inline, GError **err)
327 {
328         GList *pos;
329         TnyMimePart *attachment_part, *old_attachment;
330         gint ret;
331         gint attached = 0;
332
333         for (pos = (GList *)attachments_list; pos; pos = pos->next) {
334
335                 old_attachment = pos->data;
336                 if (!tny_mime_part_is_purged (old_attachment)) {
337                         const gchar *old_cid;
338                         old_cid = tny_mime_part_get_content_id (old_attachment);
339                         attachment_part = copy_mime_part (old_attachment, err);
340                         if (attachment_part != NULL) {
341                                 if (add_inline) {
342                                         tny_mime_part_set_header_pair (attachment_part, "Content-Disposition",
343                                                                        "inline");
344                                 } else {
345                                         const gchar *filename;
346                                         filename = tny_mime_part_get_filename (old_attachment);
347                                         if (filename)
348                                                 tny_mime_part_set_filename (attachment_part, filename);
349                                         else
350                                                 tny_mime_part_set_header_pair (attachment_part, "Content-Disposition",
351                                                                                "attachment");
352                                 }
353                                 tny_mime_part_set_transfer_encoding (TNY_MIME_PART (attachment_part), "base64");
354                                 ret = tny_mime_part_add_part (TNY_MIME_PART (part), attachment_part);
355                                 attached++;
356                                 if (old_cid)
357                                         tny_mime_part_set_content_id (attachment_part, old_cid);
358                                 g_object_unref (attachment_part);
359                         }
360                 }
361         }
362         return attached;
363 }
364
365 static void
366 add_images (TnyMsg *msg, GList *images_list, GError **err)
367 {
368         TnyMimePart *related_part = NULL;
369         const gchar *content_type;
370
371         content_type = tny_mime_part_get_content_type (TNY_MIME_PART (msg));
372
373         if ((content_type != NULL) && !strcasecmp (content_type, "multipart/related")) {
374                 related_part = g_object_ref (msg);
375         } else if ((content_type != NULL) && !strcasecmp (content_type, "multipart/mixed")) {
376                 TnyList *parts = TNY_LIST (tny_simple_list_new ());
377                 TnyIterator *iter = NULL;
378                 tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
379                 iter = tny_list_create_iterator (parts);
380
381                 while (!tny_iterator_is_done (iter)) {
382                         TnyMimePart *part = TNY_MIME_PART (tny_iterator_get_current (iter));
383                         if (part && !g_strcasecmp (tny_mime_part_get_content_type (part), "multipart/related")) {
384                                 related_part = part;
385                                 break;
386                         }
387                         if (part)
388                                 g_object_unref (part);
389                         tny_iterator_next (iter);
390                 }
391                 g_object_unref (iter);
392                 g_object_unref (parts);
393         }
394
395         if (related_part != NULL) {
396                 /* TODO: attach images in their proper place */
397                 add_attachments (related_part, images_list, TRUE, err);
398                 g_object_unref (related_part);
399         }
400 }
401
402
403 gchar * 
404 modest_tny_msg_get_body (TnyMsg *msg, gboolean want_html, gboolean *is_html)
405 {
406         TnyStream *stream;
407         TnyMimePart *body;
408         GtkTextBuffer *buf;
409         GtkTextIter start, end;
410         gchar *to_quote;
411         gboolean result_was_html = TRUE;
412
413         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
414         
415         body = modest_tny_msg_find_body_part(msg, want_html);
416         if (!body)
417                 return NULL;
418
419         buf = gtk_text_buffer_new (NULL);
420         stream = TNY_STREAM (tny_gtk_text_buffer_stream_new (buf));
421         tny_stream_reset (stream);
422         tny_mime_part_decode_to_stream (body, stream, NULL);
423         tny_stream_reset (stream);
424         
425         gtk_text_buffer_get_bounds (buf, &start, &end);
426         to_quote = gtk_text_buffer_get_text (buf, &start, &end, FALSE);
427         if (tny_mime_part_content_type_is (body, "text/plain")) {
428                 gchar *to_quote_converted = modest_text_utils_convert_to_html (to_quote);
429                 g_free (to_quote);
430                 to_quote = to_quote_converted;
431                 result_was_html = FALSE;
432         }
433
434         g_object_unref (buf);
435         g_object_unref (G_OBJECT(stream));
436         g_object_unref (G_OBJECT(body));
437
438         if (is_html != NULL)
439                 *is_html = result_was_html;
440
441         return to_quote;
442 }
443
444
445 static TnyMimePart*
446 modest_tny_msg_find_body_part_in_alternative (TnyMimePart *msg, gboolean want_html)
447 {
448         TnyList *parts;
449         TnyIterator *iter;
450         TnyMimePart *part = NULL;
451         TnyMimePart *first_part = NULL;
452         const gchar *desired_mime_type = want_html ? "text/html" : "text/plain";
453
454         parts = TNY_LIST (tny_simple_list_new());
455         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
456
457         for (iter  = tny_list_create_iterator(parts); 
458              !tny_iterator_is_done (iter);
459              tny_iterator_next (iter)) {
460                 gchar *content_type;
461                 gboolean is_body;
462
463                 part = TNY_MIME_PART (tny_iterator_get_current (iter));
464
465                 if (first_part == NULL) {
466                         g_object_ref (part);
467                         first_part = part;
468                 }
469
470                 is_body = FALSE;
471                 content_type = g_ascii_strdown (tny_mime_part_get_content_type (part), -1);
472                 is_body = g_str_has_prefix (content_type, desired_mime_type);
473                 if (is_body)
474                         break;
475
476                 g_object_unref (part);
477                 part = NULL;
478
479         }
480         g_object_unref (iter);
481         g_object_unref (parts);
482
483         if (part == NULL) {
484                 return first_part;
485         } else {
486                 if (first_part) g_object_unref (first_part);
487                 return part;
488         }
489 }
490
491 TnyMimePart*
492 modest_tny_msg_find_body_part_from_mime_part (TnyMimePart *msg, gboolean want_html)
493 {
494         TnyMimePart *part = NULL;
495         TnyList *parts = NULL;
496         TnyIterator *iter = NULL;
497         gchar *header_content_type;
498         gchar *header_content_type_lower = NULL;
499         
500         if (!msg)
501                 return NULL;
502
503         /* If it's an application multipart, then we don't get into as we don't
504          * support them (for example application/sml or wap messages */
505         header_content_type = modest_tny_mime_part_get_header_value (msg, "Content-Type");
506         if (header_content_type) {
507                 header_content_type = g_strstrip (header_content_type);
508                 header_content_type_lower = g_ascii_strdown (header_content_type, -1);
509         }
510         if (header_content_type_lower && 
511             g_str_has_prefix (header_content_type_lower, "multipart/") &&
512             !g_str_has_prefix (header_content_type_lower, "multipart/signed") &&
513             strstr (header_content_type_lower, "application/")) {
514                 g_free (header_content_type_lower);
515                 g_free (header_content_type);
516                 return NULL;
517         }       
518         if (header_content_type_lower && 
519             g_str_has_prefix (header_content_type_lower, "multipart/alternative")) {
520                 g_free (header_content_type_lower);
521                 g_free (header_content_type);
522                 return modest_tny_msg_find_body_part_in_alternative (msg, want_html);
523         }       
524         g_free (header_content_type_lower);
525         g_free (header_content_type);
526
527         parts = TNY_LIST (tny_simple_list_new());
528         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
529
530         iter  = tny_list_create_iterator(parts);
531
532         /* no parts? assume it's single-part message */
533         if (tny_iterator_is_done(iter)) {
534                 gchar *content_type;
535                 gboolean is_text_part;
536                 g_object_unref (G_OBJECT(iter));
537                 content_type = modest_tny_mime_part_get_content_type (msg);
538                 if (content_type == NULL)
539                         return NULL;
540                 is_text_part = 
541                         g_str_has_prefix (content_type, "text/");
542                 g_free (content_type);
543                 /* if this part cannot be a supported body return NULL */
544                 if (!is_text_part) {
545                         return NULL;
546                 } else {
547                         return TNY_MIME_PART (g_object_ref(G_OBJECT(msg)));
548                 }
549         } else {
550                 do {
551                         gchar *tmp, *content_type = NULL;
552                         gboolean has_content_disp_name = FALSE;
553
554                         part = TNY_MIME_PART(tny_iterator_get_current (iter));
555
556                         if (!part) {
557                                 g_warning ("%s: not a valid mime part", __FUNCTION__);
558                                 tny_iterator_next (iter);
559                                 continue;
560                         }
561
562                         /* it's a message --> ignore */
563                         if (part && TNY_IS_MSG (part)) {
564                                 g_object_unref (part);
565                                 part = NULL;
566                                 tny_iterator_next (iter);
567                                 continue;
568                         }                       
569
570                         /* we need to strdown the content type, because
571                          * tny_mime_part_has_content_type does not do it...
572                          */
573                         content_type = g_ascii_strdown (tny_mime_part_get_content_type (part), -1);
574                         
575                         /* mime-parts with a content-disposition header (either 'inline' or 'attachment')
576                          * and a 'name=' thingy cannot be body parts
577                          */
578                                 
579                         tmp = modest_tny_mime_part_get_header_value (part, "Content-Disposition");
580                         if (tmp) {
581                                 gchar *content_disp = g_ascii_strdown(tmp, -1);
582                                 g_free (tmp);
583                                 has_content_disp_name = g_strstr_len (content_disp, strlen(content_disp), "name=") != NULL;
584                                 g_free (content_disp);
585                         }
586                         
587                         if (g_str_has_prefix (content_type, "text/") && 
588                             !has_content_disp_name &&
589                             !modest_tny_mime_part_is_attachment_for_modest (part)) {
590                                 /* we found the body. Doesn't have to be the desired mime part, first
591                                    text/ part in a mixed is the body */
592                                 g_free (content_type);
593                                 break;
594
595                         } else if (g_str_has_prefix(content_type, "multipart/alternative")) {
596
597                                 /* multipart? recurse! */
598                                 g_object_unref (part);
599                                 g_free (content_type);
600                                 part = modest_tny_msg_find_body_part_in_alternative (part, want_html);
601                                 if (part)
602                                         break;
603
604                         } else  if (g_str_has_prefix(content_type, "multipart")) {
605
606                                 /* multipart? recurse! */
607                                 g_object_unref (part);
608                                 g_free (content_type);
609                                 part = modest_tny_msg_find_body_part_from_mime_part (part, want_html);
610                                 if (part)
611                                         break;
612                         } else
613                                 g_free (content_type);
614                         
615                         if (part) {
616                                 g_object_unref (G_OBJECT(part));
617                                 part = NULL;
618                         }
619                         
620                         tny_iterator_next (iter);
621                         
622                 } while (!tny_iterator_is_done(iter));
623         }
624         
625         g_object_unref (G_OBJECT(iter));
626         g_object_unref (G_OBJECT(parts));
627
628         return part; /* this maybe NULL, this is not an error; some message just don't have a body
629                       * part */
630 }
631
632
633 TnyMimePart*
634 modest_tny_msg_find_body_part (TnyMsg *msg, gboolean want_html)
635 {
636         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
637         
638         return modest_tny_msg_find_body_part_from_mime_part (TNY_MIME_PART(msg),
639                                                              want_html);
640 }
641
642
643 #define MODEST_TNY_MSG_PARENT_UID "parent-uid"
644
645 static TnyMsg *
646 create_reply_forward_mail (TnyMsg *msg, TnyHeader *header, const gchar *from,
647                            const gchar *signature, gboolean is_reply,
648                            guint type /*ignored*/, GList *attachments)
649 {
650         TnyMsg *new_msg;
651         TnyHeader *new_header;
652         gchar *old_subject;
653         gchar *new_subject;
654         TnyMimePart *body = NULL;
655         ModestFormatter *formatter;
656         gchar *subject_prefix;
657         gboolean no_text_part;
658         gchar *parent_uid;
659
660         if (header)
661                 g_object_ref (header);
662         else
663                 header = tny_msg_get_header (msg);
664
665         /* Get body from original msg. Always look for the text/plain
666            part of the message to create the reply/forwarded mail */
667         if (msg != NULL)
668                 body   = modest_tny_msg_find_body_part (msg, FALSE);
669
670         if (modest_conf_get_bool (modest_runtime_get_conf (), MODEST_CONF_PREFER_FORMATTED_TEXT,
671                                   NULL))
672                 formatter = modest_formatter_new ("text/html", signature);
673         else
674                 formatter = modest_formatter_new ("text/plain", signature);
675
676
677         /* if we don't have a text-part */
678         no_text_part = (!body) || (strcmp (tny_mime_part_get_content_type (body), "text/html")==0);
679
680         /* when we're reply, include the text part if we have it, or nothing otherwise. */
681         if (is_reply)
682                 new_msg = modest_formatter_quote  (formatter, no_text_part ? NULL: body, header,
683                                                     attachments);
684         else {
685                 /* for attachements; inline if there is a text part, and include the
686                  * full old mail if there was none */
687                 if (no_text_part) {
688                         new_msg = modest_formatter_attach (formatter, msg, header);
689                 } else { 
690                         new_msg = modest_formatter_inline  (formatter, body, header,
691                                                             attachments);
692                 }
693         }
694
695         g_object_unref (G_OBJECT(formatter));
696         if (body)
697                 g_object_unref (G_OBJECT(body));
698
699         /* Fill the header */
700         new_header = tny_msg_get_header (new_msg);
701         tny_header_set_from (new_header, from);
702         tny_header_set_replyto (new_header, from);
703
704         /* Change the subject */
705         if (is_reply)
706                 subject_prefix = g_strconcat (_("mail_va_re"), ":", NULL);
707         else
708                 subject_prefix = g_strconcat (_("mail_va_fw"), ":", NULL);
709         old_subject = tny_header_dup_subject (header);
710         new_subject =
711                 (gchar *) modest_text_utils_derived_subject (old_subject,
712                                                              subject_prefix);
713         g_free (old_subject);
714         g_free (subject_prefix);
715         tny_header_set_subject (new_header, (const gchar *) new_subject);
716         g_free (new_subject);
717
718         /* get the parent uid, and set it as a gobject property on the new msg */
719         parent_uid = modest_tny_folder_get_header_unique_id (header);
720         g_object_set_data_full (G_OBJECT(new_msg), MODEST_TNY_MSG_PARENT_UID,
721                                 parent_uid, g_free);
722
723         /* set modest as the X-Mailer
724          * we could this in the platform factory, but then the header
725          * would show up before all the others.
726          */
727         tny_mime_part_set_header_pair (TNY_MIME_PART (msg), "X-Mailer", "Modest "
728                                        VERSION);
729
730         /* Clean */
731         g_object_unref (G_OBJECT (new_header));
732         g_object_unref (G_OBJECT (header));
733         /* ugly to unref it here instead of in the calling func */
734
735         if (!is_reply & !no_text_part) {
736                 add_attachments (TNY_MIME_PART (new_msg), attachments, FALSE, NULL);
737         }
738
739         return new_msg;
740 }
741
742 const gchar*
743 modest_tny_msg_get_parent_uid (TnyMsg *msg)
744 {
745         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
746         
747         return g_object_get_data (G_OBJECT(msg), MODEST_TNY_MSG_PARENT_UID);
748 }
749
750 static gchar *get_signed_protocol (TnyMimePart *part)
751 {
752         TnyList *header_pairs;
753         TnyIterator *iterator;
754         gchar *result = NULL;
755
756         header_pairs = TNY_LIST (tny_simple_list_new ());
757         tny_mime_part_get_header_pairs (part, header_pairs);
758         iterator = tny_list_create_iterator (header_pairs);
759
760         while (!result && !tny_iterator_is_done (iterator)) {
761                 TnyPair *pair;
762                 const gchar *name;
763
764                 pair = TNY_PAIR (tny_iterator_get_current (iterator));
765                 name = tny_pair_get_name (pair);
766                 if (name && !g_ascii_strcasecmp (name, "Content-Type")) {
767                         const gchar *s;
768                         s = tny_pair_get_value (pair);
769                         if (s) {
770                                 s = strstr (s, "protocol=");
771                                 if (s) {
772                                         const gchar *t;
773                                         s += 9;
774                                         if (*s == '\"') {
775                                                 s++;
776                                                 t = strstr (s, "\"");
777                                         } else {
778                                                 t = strstr (s, ";");
779                                         }
780                                         result = g_strndup (s, t - s);
781                                 }
782                         }
783                 }
784
785                 g_object_unref (pair);
786                 tny_iterator_next (iterator);
787         }
788
789         g_object_unref (iterator);
790         g_object_unref (header_pairs);
791
792         return result;
793 }
794
795 TnyMimePart *
796 modest_tny_msg_get_attachments_parent (TnyMsg *msg)
797 {
798         TnyMimePart *result;
799         const gchar *content_type;
800
801         result = NULL;
802
803         content_type = tny_mime_part_get_content_type (TNY_MIME_PART (msg));
804         if (content_type && !strcmp (content_type, "multipart/signed")) {
805                 TnyList *msg_children;
806                 TnyIterator *iterator;
807                 gchar *signed_protocol;
808
809                 msg_children = TNY_LIST (tny_simple_list_new ());
810                 tny_mime_part_get_parts (TNY_MIME_PART (msg), msg_children);
811
812                 iterator = tny_list_create_iterator (msg_children);
813                 signed_protocol = get_signed_protocol (TNY_MIME_PART (msg));
814                         
815                 while (!result && !tny_iterator_is_done (iterator)) {
816                         TnyMimePart *part;
817
818                         part = TNY_MIME_PART (tny_iterator_get_current (iterator));
819                         if (signed_protocol) {
820                                 const gchar *part_content_type;
821
822                                 part_content_type = tny_mime_part_get_content_type (part);
823                                 if (part_content_type && g_ascii_strcasecmp (part_content_type, signed_protocol)) {
824                                         result = g_object_ref (part);
825                                 }
826                         } else {
827                                 result = g_object_ref (part);
828                         }
829
830                         g_object_unref (part);
831                         tny_iterator_next (iterator);
832                 }
833
834                 g_object_unref (iterator);
835                 g_free (signed_protocol);
836                 g_object_unref (msg_children);
837         }
838         if (result == NULL) {
839                 result = g_object_ref (msg);
840         }
841
842         return result;
843 }
844
845
846
847 static void
848 add_if_attachment (gpointer data, gpointer user_data)
849 {
850         TnyMimePart *part;
851         GList **attachments_list;
852
853         part = TNY_MIME_PART (data);
854         attachments_list = ((GList **) user_data);
855
856         if ((tny_mime_part_is_attachment (part))||(TNY_IS_MSG (part))) {
857                 *attachments_list = g_list_prepend (*attachments_list, part);
858                 g_object_ref (part);
859         }
860 }
861
862 TnyMsg* 
863 modest_tny_msg_create_forward_msg (TnyMsg *msg, 
864                                    const gchar *from,
865                                    const gchar *signature,
866                                    ModestTnyMsgForwardType forward_type)
867 {
868         TnyMsg *new_msg;
869         TnyList *parts = NULL;
870         GList *attachments_list = NULL;
871         TnyMimePart *part_to_check = NULL;
872
873         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
874
875         part_to_check = modest_tny_msg_get_attachments_parent (TNY_MSG (msg));
876         
877         /* Add attachments */
878         parts = TNY_LIST (tny_simple_list_new());
879         tny_mime_part_get_parts (TNY_MIME_PART (part_to_check), parts);
880         tny_list_foreach (parts, add_if_attachment, &attachments_list);
881
882         new_msg = create_reply_forward_mail (msg, NULL, from, signature, FALSE, forward_type,
883                                              attachments_list);
884
885         /* Clean */
886         if (attachments_list) {
887                 g_list_foreach (attachments_list, (GFunc) g_object_unref, NULL);
888                 g_list_free (attachments_list);
889         }
890         g_object_unref (G_OBJECT (parts));
891         g_object_unref (part_to_check);
892
893         return new_msg;
894 }
895
896
897
898 static gint
899 count_addresses (const gchar* addresses)
900 {
901         gint count = 1;
902
903         if (!addresses)
904                 return 0;
905         
906         while (*addresses) {
907                 if (*addresses == ',' || *addresses == ';')
908                         ++count;
909                 ++addresses;
910         }
911         
912         return count;
913 }
914
915
916 /* get the new To:, based on the old header,
917  * result is newly allocated or NULL in case of error
918  * */
919 static gchar*
920 get_new_to (TnyMsg *msg, TnyHeader *header, const gchar* from,
921             ModestTnyMsgReplyMode reply_mode)
922 {
923         gchar* old_reply_to;
924         gchar* old_from;
925         gchar* new_to;
926         gchar* tmp;
927         
928         /* according to RFC2369 (http://www.faqs.org/rfcs/rfc2369.html), we
929          * can identify Mailing-List posts by the List-Help header.
930          * for mailing lists, both the Reply-To: and From: should be included
931          * in the new To:; for now, we're ignoring List-Post
932          */
933         gchar* list_help = modest_tny_mime_part_get_header_value (TNY_MIME_PART(msg), 
934                                                                   "List-Help");
935         gboolean is_mailing_list = (list_help != NULL);
936         g_free (list_help);
937
938
939         /* reply to sender, use ReplyTo or From */
940         old_reply_to = modest_tny_mime_part_get_header_value (TNY_MIME_PART(msg), 
941                                                               "Reply-To"); 
942         old_from     = tny_header_dup_from (header);
943         
944         if (!old_from && !old_reply_to) {
945                 g_debug ("%s: failed to get either Reply-To: or From: from header",
946                            __FUNCTION__);
947                 return NULL;
948         }
949         
950         /* for mailing lists, use both Reply-To and From if we did a
951          * 'Reply All:'
952          * */
953         if (is_mailing_list && reply_mode == MODEST_TNY_MSG_REPLY_MODE_ALL &&
954             old_reply_to && old_from && strcmp (old_from, old_reply_to) != 0)
955                 new_to = g_strjoin (",", old_reply_to, old_from, NULL);
956         else
957                 /* otherwise use either Reply-To: (preferred) or From: */
958                 new_to = g_strdup (old_reply_to ? old_reply_to : old_from);
959         g_free (old_from);
960         g_free (old_reply_to);
961
962         /* in case of ReplyAll, we need to add the Recipients in the old To: */
963         if (reply_mode == MODEST_TNY_MSG_REPLY_MODE_ALL) {
964                 gchar *old_to = tny_header_dup_to (header);
965                 if (!old_to) 
966                         g_debug ("%s: no To: address found in source mail",
967                                    __FUNCTION__);
968                 else {
969                         /* append the old To: */
970                         gchar *tmp = g_strjoin (",", new_to, old_to, NULL);
971                         g_free (new_to);
972                         new_to = tmp;
973                         g_free (old_to);
974                 }
975
976                 /* remove duplicate entries */
977                 gchar *tmp = modest_text_utils_remove_duplicate_addresses (new_to);
978                 g_free (new_to);
979                 new_to = tmp;
980                 
981                 /* now, strip me (the new From:) from the new_to, but only if
982                  * there are >1 addresses there */
983                 if (count_addresses (new_to) > 1) {
984                         gchar *tmp = modest_text_utils_remove_address (new_to, from);
985                         g_free (new_to);
986                         new_to = tmp;
987                 }
988         }
989
990         tmp = modest_text_utils_simplify_recipients (new_to);
991         g_free (new_to);
992         new_to = tmp;
993
994         return new_to;
995 }
996
997
998 /* get the new Cc:, based on the old header,
999  * result is newly allocated or NULL in case of error */
1000 static gchar*
1001 get_new_cc (TnyHeader *header, const gchar* from)
1002 {
1003         gchar *old_cc, *result, *dup;
1004
1005         old_cc = tny_header_dup_cc (header);
1006         if (!old_cc)
1007                 return NULL;
1008
1009         /* remove me (the new From:) from the Cc: list */
1010         dup =  modest_text_utils_remove_address (old_cc, from);
1011         result = modest_text_utils_remove_duplicate_addresses (dup);
1012         g_free (dup);
1013         g_free (old_cc);
1014         return result;
1015 }
1016
1017 void 
1018 modest_tny_msg_get_references (TnyMsg *msg, gchar **message_id, gchar **references, gchar **in_reply_to)
1019 {
1020         TnyList *headers;
1021         TnyIterator *iterator;
1022         gchar *l_message_id;
1023         gchar *l_references;
1024         gchar *l_in_reply_to;
1025
1026         g_return_if_fail (TNY_IS_MSG (msg));
1027
1028         l_message_id = NULL;
1029         l_references = NULL;
1030         l_in_reply_to = NULL;
1031
1032         headers = TNY_LIST (tny_simple_list_new ());
1033         tny_mime_part_get_header_pairs (TNY_MIME_PART (msg), headers);
1034
1035         iterator = tny_list_create_iterator (headers);
1036         while (!tny_iterator_is_done (iterator)) {
1037                 TnyPair *pair;
1038                 const gchar *name;
1039
1040                 pair = TNY_PAIR (tny_iterator_get_current (iterator));
1041                 name = tny_pair_get_name (pair);
1042                 if (!g_strcasecmp (name, "References")) {
1043                         if (l_references) g_free (l_references);
1044                         l_references = g_strdup (tny_pair_get_value (pair));
1045                 } else if (!g_strcasecmp (name, "In-Reply-To")) {
1046                         if (l_in_reply_to) g_free (l_in_reply_to);
1047                         l_in_reply_to = g_strdup (tny_pair_get_value (pair));
1048                 } else if (!g_strcasecmp (name, "Message-ID")) {
1049                         if (l_message_id) g_free (l_message_id);
1050                         l_message_id = g_strdup (tny_pair_get_value (pair));
1051                 }
1052
1053                 g_object_unref (pair);
1054                 tny_iterator_next (iterator);
1055         }
1056
1057         g_object_unref (iterator);
1058         g_object_unref (headers);
1059
1060         if (message_id) {
1061                 *message_id = l_message_id;
1062         } else {
1063                 g_free (l_message_id);
1064         }
1065
1066         if (in_reply_to) {
1067                 *in_reply_to = l_in_reply_to;
1068         } else {
1069                 g_free (l_in_reply_to);
1070         }
1071
1072         if (references) {
1073                 *references = l_references;
1074         } else {
1075                 g_free (l_references);
1076         }
1077 }
1078
1079 static void 
1080 set_references (TnyMsg *reply_msg, TnyMsg *original_msg)
1081 {
1082         gchar *orig_references, *orig_in_reply_to, *orig_message_id;
1083         gchar *references, *in_reply_to;
1084
1085         modest_tny_msg_get_references (original_msg, &orig_message_id, &orig_references, &orig_in_reply_to);
1086
1087         references = NULL;
1088         in_reply_to = NULL;
1089
1090         if (orig_message_id)
1091                 in_reply_to = g_strdup (orig_message_id);
1092
1093         if (orig_references) {
1094                 if (orig_message_id)
1095                         references = g_strconcat (orig_references, "\n        ", orig_message_id, NULL);
1096                 else
1097                         references = g_strdup (orig_references);
1098
1099         } else if (orig_in_reply_to) {
1100                 if (orig_message_id)
1101                         references = g_strconcat (orig_in_reply_to, "\n        ", orig_message_id, NULL);
1102                 else
1103                         references = g_strdup (orig_in_reply_to);
1104         } else if (orig_message_id) {
1105                 references = g_strdup (orig_message_id);
1106         }
1107
1108         g_free (orig_references);
1109         g_free (orig_in_reply_to);
1110         g_free (orig_message_id);
1111
1112         if (in_reply_to) {
1113                 tny_mime_part_set_header_pair (TNY_MIME_PART (reply_msg), "In-Reply-To", in_reply_to);
1114         }
1115         if (references) {
1116                 tny_mime_part_set_header_pair (TNY_MIME_PART (reply_msg), "References", references);
1117         }
1118 }
1119
1120 TnyMsg* 
1121 modest_tny_msg_create_reply_msg (TnyMsg *msg,
1122                                  TnyHeader *header,
1123                                  const gchar *from,
1124                                  const gchar *signature,
1125                                  ModestTnyMsgReplyType reply_type,
1126                                  ModestTnyMsgReplyMode reply_mode)
1127 {
1128         TnyMsg *new_msg = NULL;
1129         TnyHeader *new_header;
1130         gchar *new_to = NULL;
1131         TnyList *parts = NULL;
1132         GList *attachments_list = NULL;
1133         TnyMimePart *part_to_check = NULL;
1134
1135         g_return_val_if_fail (msg && TNY_IS_MSG(msg), NULL);
1136
1137         part_to_check = modest_tny_msg_get_attachments_parent (TNY_MSG (msg));
1138
1139         parts = TNY_LIST (tny_simple_list_new());
1140         tny_mime_part_get_parts (TNY_MIME_PART (part_to_check), parts);
1141         tny_list_foreach (parts, add_if_attachment, &attachments_list);
1142
1143         new_msg = create_reply_forward_mail (msg, header, from, signature, TRUE, reply_type,
1144                                              attachments_list);
1145
1146         set_references (new_msg, msg);
1147         if (attachments_list != NULL) {
1148                 g_list_foreach (attachments_list, (GFunc) g_object_unref, NULL);
1149                 g_list_free (attachments_list);
1150         }
1151         g_object_unref (parts);
1152
1153         /* Fill the header */
1154         if (header)
1155                 g_object_ref (header);
1156         else
1157                 header = tny_msg_get_header (msg);
1158
1159         
1160         new_header = tny_msg_get_header(new_msg);
1161         new_to = get_new_to (msg, header, from, reply_mode);
1162         if (!new_to)
1163                 g_debug ("%s: failed to get new To:", __FUNCTION__);
1164         else {
1165                 tny_header_set_to (new_header, new_to);
1166                 g_free (new_to);
1167         }
1168
1169         if (reply_mode == MODEST_TNY_MSG_REPLY_MODE_ALL) {
1170                 gchar *new_cc = get_new_cc (header, from);
1171                 if (new_cc) { 
1172                         tny_header_set_cc (new_header, new_cc);
1173                         g_free (new_cc);
1174                 }
1175         }
1176
1177         /* Clean */
1178         g_object_unref (G_OBJECT (new_header));
1179         g_object_unref (G_OBJECT (header));
1180         g_object_unref (G_OBJECT (part_to_check));
1181
1182         return new_msg;
1183 }
1184
1185
1186 static gboolean
1187 is_ascii(const gchar *s)
1188 {
1189         if (!s)
1190                 return TRUE;
1191         while (s[0]) {
1192                 if (s[0] & 128 || s[0] < 32)
1193                         return FALSE;
1194                 s++;
1195         }
1196         return TRUE;
1197 }
1198
1199 static char *
1200 get_content_type(const gchar *s)
1201 {
1202         GString *type;
1203         
1204         type = g_string_new("text/plain");
1205         if (!is_ascii(s)) {
1206                 if (g_utf8_validate(s, -1, NULL)) {
1207                         g_string_append(type, "; charset=\"utf-8\"");
1208                 } else {
1209                         /* it should be impossible to reach this, but better safe than sorry */
1210                         g_debug("invalid utf8 in message");
1211                         g_string_append(type, "; charset=\"latin1\"");
1212                 }
1213         }
1214         return g_string_free(type, FALSE);
1215 }
1216
1217 guint64
1218 modest_tny_msg_estimate_size (const gchar *plain_body, const gchar *html_body,
1219                               guint64 parts_count,
1220                               guint64 parts_size)
1221 {
1222         guint64 result;
1223
1224         /* estimation of headers size */
1225         result = 1024;
1226
1227         /* We add a 20% of size due to the increase in 7bit encoding */
1228         if (plain_body) {
1229                 result += strlen (plain_body) * 120 / 100;
1230         }
1231         if (html_body) {
1232                 result += strlen (html_body) * 120 / 100;
1233         }
1234
1235         /* 256 bytes per additional part because of their headers */
1236         result += parts_count * 256;
1237
1238         /* 150% of increase per encoding */
1239         result += parts_size * 3 / 2;
1240
1241         return result;
1242 }
1243
1244 GSList *
1245 modest_tny_msg_header_get_all_recipients_list (TnyHeader *header)
1246 {
1247         GSList *recipients = NULL;
1248         gchar *from = NULL, *to = NULL, *cc = NULL, *bcc = NULL;
1249         gchar *tmp = NULL, *old_tmp = NULL;
1250
1251         if (header == NULL)
1252                 return NULL;
1253
1254         from = tny_header_dup_from (header);
1255         to = tny_header_dup_to (header);
1256         cc = tny_header_dup_cc (header);
1257         bcc = tny_header_dup_bcc (header);
1258
1259         recipients = NULL;
1260         if (from) {
1261                 tmp = g_strdup (from);
1262                 old_tmp = tmp;
1263                 g_free (from);
1264         }
1265         if (to) {
1266                 tmp = g_strjoin ("; ", old_tmp, to, NULL);
1267                 g_free (old_tmp);
1268                 old_tmp = tmp;
1269                 g_free (to);
1270         }
1271         if (cc) {
1272                 tmp = g_strjoin ("; ", old_tmp, cc, NULL);
1273                 g_free (old_tmp);
1274                 old_tmp = tmp;
1275                 g_free (cc);
1276         }
1277         if (bcc) {
1278                 tmp = g_strjoin ("; ", old_tmp, bcc, NULL);
1279                 g_free (old_tmp);
1280                 old_tmp = tmp;
1281                 g_free (bcc);
1282         }
1283
1284         old_tmp = modest_text_utils_remove_duplicate_addresses (tmp);
1285         recipients = modest_text_utils_split_addresses_list (old_tmp);
1286         g_free (tmp);
1287
1288         return recipients;
1289 }
1290
1291 GSList *
1292 modest_tny_msg_get_all_recipients_list (TnyMsg *msg)
1293 {
1294         TnyHeader *header = NULL;
1295         GSList *recipients = NULL;
1296
1297         if (msg == NULL)
1298                 return NULL;
1299
1300         header = tny_msg_get_header (msg);
1301         if (header == NULL)
1302                 return NULL;
1303
1304         recipients = modest_tny_msg_header_get_all_recipients_list (header);
1305         g_object_unref (header);
1306
1307         return recipients;
1308 }
1309