Now GetUnreadMessages dbus method tells also the number of unread messages
[modest] / src / modest-text-utils.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
31
32 #ifndef _GNU_SOURCE
33 #define _GNU_SOURCE
34 #endif /*_GNU_SOURCE*/
35 #include <string.h> /* for strcasestr */
36
37
38 #include <glib.h>
39 #include <stdlib.h>
40 #include <glib/gi18n.h>
41 #include <regex.h>
42 #include <modest-tny-platform-factory.h>
43 #include <modest-text-utils.h>
44 #include <modest-account-mgr-helpers.h>
45 #include <modest-runtime.h>
46 #include <ctype.h>
47
48 #ifdef HAVE_CONFIG_H
49 #include <config.h>
50 #endif /*HAVE_CONFIG_H */
51
52 /* defines */
53 #define FORWARD_STRING _("mcen_ia_editor_original_message")
54 #define FROM_STRING _("mail_va_from")
55 #define SENT_STRING _("mcen_fi_message_properties_sent")
56 #define TO_STRING _("mail_va_to")
57 #define SUBJECT_STRING _("mail_va_subject")
58 #define EMPTY_STRING ""
59
60 /*
61  * do the hyperlinkification only for texts < 50 Kb,
62  * as it's quite slow. Without this, e.g. mail with
63  * an uuencoded part (which is not recognized as attachment,
64  * will hang modest
65  */
66 #define HYPERLINKIFY_MAX_LENGTH (1024*50)
67
68 /*
69  * we need these regexps to find URLs in plain text e-mails
70  */
71 typedef struct _url_match_pattern_t url_match_pattern_t;
72 struct _url_match_pattern_t {
73         gchar   *regex;
74         regex_t *preg;
75         gchar   *prefix;
76 };
77
78 typedef struct _url_match_t url_match_t;
79 struct _url_match_t {
80         guint offset;
81         guint len;
82         const gchar* prefix;
83 };
84
85
86 /*
87  * we mark the ampersand with \007 when converting text->html
88  * because after text->html we do hyperlink detecting, which
89  * could be screwed up by the ampersand.
90  * ie. 1<3 ==> 1\007lt;3
91  */
92 #define MARK_AMP '\007'
93 #define MARK_AMP_STR "\007"
94
95 /* mark &amp; separately, because they are parts of urls.
96  * ie. a&b => a\006amp;b, but a>b => a\007gt;b
97  *
98  * we need to handle '&' separately, because it can be part of URIs
99  * (as in href="http://foo.bar?a=1&b=1"), so inside those URIs
100  * we need to re-replace \006amp; with '&' again, while outside uri's
101  * it will be '&amp;'
102  * 
103  * yes, it's messy, but a consequence of doing text->html first, then hyperlinkify
104  */
105 #define MARK_AMP_URI '\006'
106 #define MARK_AMP_URI_STR "\006"
107
108
109 /* note: match MARK_AMP_URI_STR as well, because after txt->html, a '&' will look like $(MARK_AMP_URI_STR)"amp;" */
110 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
111         { "(feed:|)(file|rtsp|http|ftp|https|mms|mmsh|webcal|feed|rtsp|rdp|lastfm|sip)://[-a-z0-9_$.+!*(),;:@%=\?/~#&" MARK_AMP_URI_STR \
112                         "]+[-a-z0-9_$%&" MARK_AMP_URI_STR "=?/~#]",     \
113           NULL, NULL },\
114         { "www\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
115                         NULL, "http://" },                              \
116         { "ftp\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
117           NULL, "ftp://" },\
118         { "(jabberto|voipto|sipto|sip|chatto|skype|xmpp):[-_a-z@0-9.+]+", \
119            NULL, NULL},                                             \
120         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
121           NULL, NULL},\
122         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
123           NULL, "mailto:"}\
124         }
125
126 const gchar account_title_forbidden_chars[] = {
127         '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
128 };
129 const gchar folder_name_forbidden_chars[] = {
130         '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$', '#', '&'
131 };
132 const gchar user_name_forbidden_chars[] = {
133         '<', '>'
134 };
135 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
136 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
137 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
138
139 /* private */
140 static gchar*   cite                    (const time_t sent_date, const gchar *from);
141 static void     hyperlinkify_plain_text (GString *txt, gint offset);
142 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
143 static GSList*  get_url_matches         (GString *txt, gint offset);
144
145 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
146 static int      get_indent_level        (const char *l);
147 static void     unquote_line            (GString * l, const gchar *quote_symbol);
148 static void     append_quoted           (GString * buf, const gchar *quote_symbol,
149                                          const int indent, const GString * str, 
150                                          const int cutpoint);
151 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
152 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
153 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
154
155 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
156                                                     const gchar *cite, 
157                                                     const gchar *signature,
158                                                     GList *attachments, 
159                                                     int limit);
160
161 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
162                                                     const gchar *cite,
163                                                     const gchar *signature,
164                                                     GList *attachments,
165                                                     int limit);
166 static gchar*   get_email_from_address (const gchar *address);
167 static void     remove_extra_spaces (gchar *string);
168
169
170
171 /* ******************************************************************* */
172 /* ************************* PUBLIC FUNCTIONS ************************ */
173 /* ******************************************************************* */
174
175 gchar *
176 modest_text_utils_quote (const gchar *text, 
177                          const gchar *content_type,
178                          const gchar *signature,
179                          const gchar *from,
180                          const time_t sent_date, 
181                          GList *attachments,
182                          int limit)
183 {
184         gchar *retval, *cited;
185
186         g_return_val_if_fail (text, NULL);
187         g_return_val_if_fail (content_type, NULL);
188
189         cited = cite (sent_date, from);
190         
191         if (content_type && strcmp (content_type, "text/html") == 0)
192                 /* TODO: extract the <body> of the HTML and pass it to
193                    the function */
194                 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
195         else
196                 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
197         
198         g_free (cited);
199         
200         return retval;
201 }
202
203
204 gchar *
205 modest_text_utils_cite (const gchar *text,
206                         const gchar *content_type,
207                         const gchar *signature,
208                         const gchar *from,
209                         time_t sent_date)
210 {
211         gchar *retval, *tmp;
212
213         g_return_val_if_fail (text, NULL);
214         g_return_val_if_fail (content_type, NULL);
215
216         if (strcmp (content_type, "text/html") == 0) {
217                 tmp = modest_text_utils_convert_to_html_body (text, -1, TRUE);
218                 if (signature) {
219                         gchar *colored_signature = modest_text_utils_create_colored_signature (signature);
220                         retval = g_strconcat (tmp, colored_signature, NULL);
221                         g_free (colored_signature);
222                         g_free (tmp);
223                 } else {
224                         retval = tmp;
225                 }
226         } else {
227                 if (signature)
228                         retval = g_strconcat (text, "\n", MODEST_TEXT_UTILS_SIGNATURE_MARKER, "\n", signature, NULL);
229                 else
230                         retval = g_strdup (text);
231         }
232
233         return retval;
234 }
235
236 static gchar *
237 forward_cite (const gchar *from,
238               const gchar *sent,
239               const gchar *to,
240               const gchar *subject)
241 {
242         g_return_val_if_fail (sent, NULL);
243         
244         return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n", 
245                                 FORWARD_STRING, 
246                                 FROM_STRING, (from)?from:"",
247                                 SENT_STRING, sent,
248                                 TO_STRING, (to)?to:"",
249                                 SUBJECT_STRING, (subject)?subject:"");
250 }
251
252 gchar * 
253 modest_text_utils_inline (const gchar *text,
254                           const gchar *content_type,
255                           const gchar *signature,
256                           const gchar *from,
257                           time_t sent_date,
258                           const gchar *to,
259                           const gchar *subject)
260 {
261         gchar sent_str[101];
262         gchar *cited;
263         gchar *retval;
264         
265         g_return_val_if_fail (text, NULL);
266         g_return_val_if_fail (content_type, NULL);
267         
268         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
269
270         cited = forward_cite (from, sent_str, to, subject);
271         
272         if (content_type && strcmp (content_type, "text/html") == 0)
273                 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
274         else
275                 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
276         
277         g_free (cited);
278         return retval;
279 }
280
281 /* just to prevent warnings:
282  * warning: `%x' yields only last 2 digits of year in some locales
283  */
284 gsize
285 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
286 {
287         struct tm tm;
288
289         /* To prevent possible problems in strftime that could leave
290            garbage in the s variable */
291         if (s)
292                 s[0] = '\0';
293         else
294                 return 0;
295
296         /* does not work on old maemo glib: 
297          *   g_date_set_time_t (&date, timet);
298          */
299         localtime_r (&timet, &tm);
300         return strftime(s, max, fmt, &tm);
301 }
302
303 gchar *
304 modest_text_utils_derived_subject (const gchar *subject, gboolean is_reply)
305 {
306         gchar *tmp, *subject_dup, *retval, *prefix;
307         const gchar *untranslated_prefix;
308         gint prefix_len, untranslated_prefix_len;
309         gboolean found = FALSE;
310
311         if (!subject || subject[0] == '\0')
312                 subject = _("mail_va_no_subject");
313
314         subject_dup = g_strdup (subject);
315         tmp = g_strchug (subject_dup);
316
317         prefix = (is_reply) ? _("mail_va_re") : _("mail_va_fw");
318         prefix = g_strconcat (prefix, ":", NULL);
319         prefix_len = g_utf8_strlen (prefix, -1);
320
321         untranslated_prefix =  (is_reply) ? "Re:" : "Fw:";
322         untranslated_prefix_len = 3;
323
324         if (g_str_has_prefix (tmp, prefix) ||
325             g_str_has_prefix (tmp, untranslated_prefix)) {
326                 found = TRUE;
327         } else {
328                 gchar *prefix_down, *tmp_down, *untranslated_down;
329
330                 prefix_down = g_utf8_strdown (prefix, -1);
331                 untranslated_down = g_utf8_strdown (untranslated_prefix, -1);
332                 tmp_down = g_utf8_strdown (tmp, -1);
333                 if (g_str_has_prefix (tmp_down, prefix_down) ||
334                     g_str_has_prefix (tmp_down, untranslated_down) ||
335                     (!is_reply && g_str_has_prefix (tmp_down, "fwd:")))
336                         found = TRUE;
337
338                 g_free (prefix_down);
339                 g_free (untranslated_down);
340                 g_free (tmp_down);
341         }
342
343         if (found) {
344                 /* If the prefix is already present do not touch the subject */
345                 retval = subject_dup;
346         } else {
347                 /* Normal case, add the prefix */
348                 retval = g_strdup_printf ("%s %s", untranslated_prefix, tmp);
349                 g_free (subject_dup);
350         }
351         g_free (prefix);
352
353         return retval;
354 }
355
356
357 /* Performs a case-insensitive strstr for ASCII strings */
358 static const gchar *
359 ascii_stristr(const gchar *haystack, const gchar *needle)
360 {
361         int needle_len;
362         int haystack_len;
363         const gchar *pos;
364         const gchar *max_pos;
365
366         if (haystack == NULL || needle == NULL) {
367                 return haystack;  /* as in strstr */
368         }
369
370         needle_len = strlen(needle);
371
372         if (needle_len == 0) {
373                 return haystack;  /* as in strstr */
374         }
375
376         haystack_len = strlen(haystack);
377         max_pos = haystack + haystack_len - needle_len;
378
379         for (pos = haystack; pos <= max_pos; pos++) {
380                 if (g_ascii_strncasecmp (pos, needle, needle_len) == 0) {
381                         return pos;
382                 }
383         }
384
385         return NULL;
386 }
387
388
389 gchar*
390 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
391 {
392         gchar *dup, *token, *ptr = NULL, *result;
393         GString *filtered_emails;
394         gchar *email_address;
395
396         g_return_val_if_fail (address_list, NULL);
397
398         if (!address)
399                 return g_strdup (address_list);
400
401         email_address = get_email_from_address (address);
402
403         /* search for substring */
404         if (!ascii_stristr ((const char *) address_list, (const char *) email_address)) {
405                 g_free (email_address);
406                 return g_strdup (address_list);
407         }
408
409         dup = g_strdup (address_list);
410         filtered_emails = g_string_new (NULL);
411
412         token = strtok_r (dup, ",", &ptr);
413
414         while (token != NULL) {
415                 /* Add to list if not found */
416                 if (!ascii_stristr ((const char *) token, (const char *) email_address)) {
417                         if (filtered_emails->len == 0)
418                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
419                         else
420                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
421                 }
422                 token = strtok_r (NULL, ",", &ptr);
423         }
424         result = filtered_emails->str;
425
426         /* Clean */
427         g_free (email_address);
428         g_free (dup);
429         g_string_free (filtered_emails, FALSE);
430
431         return result;
432 }
433
434
435 gchar*
436 modest_text_utils_remove_duplicate_addresses (const gchar *address_list)
437 {
438         GSList *addresses, *cursor;
439         GHashTable *table;
440         gchar *new_list = NULL;
441         
442         g_return_val_if_fail (address_list, NULL);
443
444         table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
445         addresses = modest_text_utils_split_addresses_list (address_list);
446
447         cursor = addresses;
448         while (cursor) {
449                 const gchar* address = (const gchar*)cursor->data;
450
451                 /* We need only the email to just compare it and not
452                    the full address which would make "a <a@a.com>"
453                    different from "a@a.com" */
454                 const gchar *email = get_email_from_address (address);
455
456                 /* ignore the address if already seen */
457                 if (g_hash_table_lookup (table, email) == 0) {
458                         gchar *tmp;
459
460                         /* Include the full address and not only the
461                            email in the returned list */
462                         if (!new_list) {
463                                 tmp = g_strdup (address);
464                         } else {
465                                 tmp = g_strjoin (",", new_list, address, NULL);
466                                 g_free (new_list);
467                         }
468                         new_list = tmp;
469                         
470                         g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
471                 }
472                 cursor = g_slist_next (cursor);
473         }
474
475         g_hash_table_unref (table);
476         g_slist_foreach (addresses, (GFunc)g_free, NULL);
477         g_slist_free (addresses);
478
479         if (new_list == NULL)
480                 new_list = g_strdup ("");
481
482         return new_list;
483 }
484
485
486 static void
487 modest_text_utils_convert_buffer_to_html_start (GString *html, const gchar *data, gssize n)
488 {
489         guint           i;
490         gboolean        space_seen = FALSE;
491         guint           break_dist = 0; /* distance since last break point */
492
493         if (n == -1)
494                 n = strlen (data);
495
496         /* replace with special html chars where needed*/
497         for (i = 0; i != n; ++i)  {
498                 guchar kar = data[i];
499                 
500                 if (space_seen && kar != ' ') {
501                         g_string_append (html, "&#32;");
502                         space_seen = FALSE;
503                 }
504                 
505                 /* we artificially insert a breakpoint (newline)
506                  * after 256, to make sure our lines are not so long
507                  * they will DOS the regexping later
508                  * Also, check that kar is ASCII to make sure that we
509                  * don't break a UTF8 char in two
510                  */
511                 if (++break_dist >= 256 && kar < 127) {
512                         g_string_append_c (html, '\n');
513                         break_dist = 0;
514                 }
515                 
516                 switch (kar) {
517                 case 0:
518                 case MARK_AMP:
519                 case MARK_AMP_URI:      
520                         /* this is a temp place holder for '&'; we can only
521                                 * set the real '&' after hyperlink translation, otherwise
522                                 * we might screw that up */
523                         break; /* ignore embedded \0s and MARK_AMP */   
524                 case '<'  : g_string_append (html, MARK_AMP_STR "lt;");   break;
525                 case '>'  : g_string_append (html, MARK_AMP_STR "gt;");   break;
526                 case '&'  : g_string_append (html, MARK_AMP_URI_STR "amp;");  break; /* special case */
527                 case '"'  : g_string_append (html, MARK_AMP_STR "quot;");  break;
528
529                 /* don't convert &apos; --> wpeditor will try to re-convert it... */    
530                 //case '\'' : g_string_append (html, "&apos;"); break;
531                 case '\n' : g_string_append (html, "<br>\n");break_dist= 0; break;
532                 case '\t' : g_string_append (html, MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp; ");
533                         break_dist=0; break; /* note the space at the end*/
534                 case ' ':
535                         break_dist = 0;
536                         if (space_seen) { /* second space in a row */
537                                 g_string_append (html, "&nbsp; ");
538                         } else
539                                 space_seen = TRUE;
540                         break;
541                 default:
542                         g_string_append_c (html, kar);
543                 }
544         }
545 }
546
547
548 static void
549 modest_text_utils_convert_buffer_to_html_finish (GString *html)
550 {
551         int i;
552         /* replace all our MARK_AMPs with real ones */
553         for (i = 0; i != html->len; ++i)
554                 if ((html->str)[i] == MARK_AMP || (html->str)[i] == MARK_AMP_URI)
555                         (html->str)[i] = '&';
556 }
557
558
559 gchar*
560 modest_text_utils_convert_to_html (const gchar *data)
561 {
562         GString         *html;      
563         gsize           len;
564
565         g_return_val_if_fail (data, NULL);
566         
567         if (!data)
568                 return NULL;
569
570         len = strlen (data);
571         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
572
573         g_string_append_printf (html,
574                                 "<html><head>"
575                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
576                                 "</head>"
577                                 "<body>");
578
579         modest_text_utils_convert_buffer_to_html_start (html, data, -1);
580         
581         g_string_append (html, "</body></html>");
582
583         if (len <= HYPERLINKIFY_MAX_LENGTH)
584                 hyperlinkify_plain_text (html, 0);
585
586         modest_text_utils_convert_buffer_to_html_finish (html);
587         
588         return g_string_free (html, FALSE);
589 }
590
591 gchar *
592 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
593 {
594         GString         *html;      
595
596         g_return_val_if_fail (data, NULL);
597
598         if (!data)
599                 return NULL;
600
601         if (n == -1) 
602                 n = strlen (data);
603         html = g_string_sized_new (1.5 * n);    /* just a  guess... */
604
605         modest_text_utils_convert_buffer_to_html_start (html, data, n);
606
607         if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
608                 hyperlinkify_plain_text (html, 0);
609
610         modest_text_utils_convert_buffer_to_html_finish (html);
611         
612         return g_string_free (html, FALSE);
613 }
614
615 void
616 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
617 {
618         GString *str;
619         gchar *start, *cur;
620
621         if (!addresses)
622                 return;
623
624         if (strlen (addresses) == 0)
625                 return;
626
627         str = g_string_new ("");
628         start = (gchar*) addresses;
629         cur = (gchar*) addresses;
630
631         for (cur = start; *cur != '\0'; cur = g_utf8_next_char (cur)) {
632                 if (*cur == ',' || *cur == ';') {
633                         gint *start_index, *end_index;
634                         gchar *next_char = g_utf8_next_char (cur);
635
636                         if (!g_utf8_strchr (start, (cur - start + 1), g_utf8_get_char ("@")) &&
637                             next_char && *next_char != '\n' && *next_char != '\0')
638                                 continue;
639
640                         start_index = g_new0 (gint, 1);
641                         end_index = g_new0 (gint, 1);
642                         *start_index = g_utf8_pointer_to_offset (addresses, start);
643                         *end_index = g_utf8_pointer_to_offset (addresses, cur);;
644                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
645                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
646                         start = g_utf8_next_char (cur);
647                 }
648         }
649
650         if (start != cur) {
651                 gint *start_index, *end_index;
652                 start_index = g_new0 (gint, 1);
653                 end_index = g_new0 (gint, 1);
654                 *start_index = g_utf8_pointer_to_offset (addresses, start);
655                 *end_index = g_utf8_pointer_to_offset (addresses, cur);;
656                 *start_indexes = g_slist_prepend (*start_indexes, start_index);
657                 *end_indexes = g_slist_prepend (*end_indexes, end_index);
658         }
659
660         if (*start_indexes)
661                 *start_indexes = g_slist_reverse (*start_indexes);
662         if (*end_indexes)
663                 *end_indexes = g_slist_reverse (*end_indexes);
664 }
665
666
667 GSList *
668 modest_text_utils_split_addresses_list (const gchar *addresses)
669 {
670         GSList *head;
671         const gchar *my_addrs = addresses;
672         const gchar *end;
673         gchar *addr;
674         gboolean after_at = FALSE;
675
676         g_return_val_if_fail (addresses, NULL);
677
678         /* skip any space, ',', ';' '\n' at the start */
679         while (my_addrs && (my_addrs[0] == ' ' || my_addrs[0] == ',' ||
680                             my_addrs[0] == ';' || my_addrs[0] == '\n'))
681                ++my_addrs;
682
683         /* are we at the end of addresses list? */
684         if (!my_addrs[0])
685                 return NULL;
686
687         /* nope, we are at the start of some address
688          * now, let's find the end of the address */
689         end = my_addrs + 1;
690         while (end[0] && end[0] != ';' && !(after_at && end[0] == ',')) {
691                 if (end[0] == '\"') {
692                         while (end[0] && end[0] != '\"')
693                                 ++end;
694                 }
695                 if (end[0] == '@') {
696                         after_at = TRUE;
697                 }
698                 if ((end[0] && end[0] == '>')&&(end[1] && end[1] == ',')) {
699                         ++end;
700                         break;
701                 }
702                 ++end;
703         }
704
705         /* we got the address; copy it and remove trailing whitespace */
706         addr = g_strndup (my_addrs, end - my_addrs);
707         g_strchomp (addr);
708
709         remove_extra_spaces (addr);
710
711         head = g_slist_append (NULL, addr);
712         head->next = modest_text_utils_split_addresses_list (end); /* recurse */
713
714         return head;
715 }
716
717 gchar *
718 modest_text_utils_join_addresses (const gchar *from,
719                                   const gchar *to,
720                                   const gchar *cc,
721                                   const gchar *bcc)
722 {
723         GString *buffer;
724         gboolean add_separator = FALSE;
725
726         buffer = g_string_new ("");
727
728         if (from && strlen (from)) {
729                 buffer = g_string_append (buffer, from);
730                 add_separator = TRUE;
731         }
732         if (to && strlen (to)) {
733                 if (add_separator)
734                         buffer = g_string_append (buffer, "; ");
735                 else
736                         add_separator = TRUE;
737
738                 buffer = g_string_append (buffer, to);
739         }
740         if (cc && strlen (cc)) {
741                 if (add_separator)
742                         buffer = g_string_append (buffer, "; ");
743                 else
744                         add_separator = TRUE;
745
746                 buffer = g_string_append (buffer, cc);
747         }
748         if (bcc && strlen (bcc)) {
749                 if (add_separator)
750                         buffer = g_string_append (buffer, "; ");
751                 else
752                         add_separator = TRUE;
753
754                 buffer = g_string_append (buffer, bcc);
755         }
756
757         return g_string_free (buffer, FALSE);
758 }
759
760 void
761 modest_text_utils_address_range_at_position (const gchar *recipients_list,
762                                              guint position,
763                                              guint *start,
764                                              guint *end)
765 {
766         gchar *current = NULL;
767         gint range_start = 0;
768         gint range_end = 0;
769         gint index;
770         gboolean is_quoted = FALSE;
771
772         g_return_if_fail (recipients_list);
773         g_return_if_fail (position < g_utf8_strlen(recipients_list, -1));
774                 
775         index = 0;
776         for (current = (gchar *) recipients_list; *current != '\0';
777              current = g_utf8_find_next_char (current, NULL)) {
778                 gunichar c = g_utf8_get_char (current);
779
780                 if ((c == ',') && (!is_quoted)) {
781                         if (index < position) {
782                                 range_start = index + 1;
783                         } else {
784                                 break;
785                         }
786                 } else if (c == '\"') {
787                         is_quoted = !is_quoted;
788                 } else if ((c == ' ') &&(range_start == index)) {
789                         range_start ++;
790                 }
791                 index ++;
792                 range_end = index;
793         }
794
795         if (start)
796                 *start = range_start;
797         if (end)
798                 *end = range_end;
799 }
800
801 gchar *
802 modest_text_utils_address_with_standard_length (const gchar *recipients_list)
803 {
804         gchar ** splitted;
805         gchar ** current;
806         GString *buffer = g_string_new ("");
807
808         splitted = g_strsplit (recipients_list, "\n", 0);
809         current = splitted;
810         while (*current) {
811                 gchar *line;
812                 if (current != splitted)
813                         buffer = g_string_append_c (buffer, '\n');
814                 line = g_strndup (*splitted, 1000);
815                 buffer = g_string_append (buffer, line);
816                 g_free (line);
817                 current++;
818         }
819
820         g_strfreev (splitted);
821
822         return g_string_free (buffer, FALSE);
823 }
824
825
826 /* ******************************************************************* */
827 /* ************************* UTILIY FUNCTIONS ************************ */
828 /* ******************************************************************* */
829
830 static GString *
831 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
832 {
833         GString *gs;
834         const gchar *i0;
835         
836         if (iter > b + blen)
837                 return g_string_new("");
838         
839         i0 = iter;
840         while (iter[0]) {
841                 if (iter[0] == '\n')
842                         break;
843                 iter++;
844         }
845         gs = g_string_new_len (i0, iter - i0);
846         return gs;
847 }
848 static int
849 get_indent_level (const char *l)
850 {
851         int indent = 0;
852
853         while (l[0]) {
854                 if (l[0] == '>') {
855                         indent++;
856                         if (l[1] == ' ') {
857                                 l++;
858                         }
859                 } else {
860                         break;
861                 }
862                 l++;
863
864         }
865
866         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
867          *      stops reformatting.
868          */
869         if (strcmp (l, MODEST_TEXT_UTILS_SIGNATURE_MARKER) == 0) {
870                 return -1 - indent;
871         } else {
872                 return indent;
873         }
874 }
875
876 static void
877 unquote_line (GString * l, const gchar *quote_symbol)
878 {
879         gchar *p;
880         gint quote_len;
881
882         p = l->str;
883         quote_len = strlen (quote_symbol);
884         while (p[0]) {
885                 if (g_str_has_prefix (p, quote_symbol)) {
886                         if (p[quote_len] == ' ') {
887                                 p += quote_len;
888                         }
889                 } else {
890                         break;
891                 }
892                 p++;
893         }
894         g_string_erase (l, 0, p - l->str);
895 }
896
897 static void
898 append_quoted (GString * buf, const gchar *quote_symbol,
899                int indent, const GString * str,
900                const int cutpoint)
901 {
902         int i;
903         gchar *quote_concat;
904
905         indent = indent < 0 ? abs (indent) - 1 : indent;
906         quote_concat = g_strconcat (quote_symbol, " ", NULL);
907         for (i = 0; i <= indent; i++) {
908                 g_string_append (buf, quote_concat);
909         }
910         g_free (quote_concat);
911         if (cutpoint > 0) {
912                 g_string_append_len (buf, str->str, cutpoint);
913         } else {
914                 g_string_append (buf, str->str);
915         }
916         g_string_append (buf, "\n");
917 }
918
919 static int
920 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
921 {
922         gint index = 0;
923         const gchar *pos, *last;
924         gunichar *uni;
925
926         if (2*indent >= limit)
927                 return strlen (s);
928
929         indent = indent < 0 ? abs (indent) - 1 : indent;
930
931         last = NULL;
932         pos = s;
933         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
934         while (pos[0]) {
935                 if ((index + 2 * indent > limit) && last) {
936                         g_free (uni);
937                         return last - s;
938                 }
939                 if (g_unichar_isspace (uni[index])) {
940                         last = pos;
941                 }
942                 pos = g_utf8_next_char (pos);
943                 index++;
944         }
945         g_free (uni);
946         return strlen (s);
947 }
948
949 static int
950 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
951 {
952         gint i, last;
953
954         last = strlen (s);
955         if (last + 2 * indent < limit)
956                 return last;
957
958         for (i = strlen (s); i > 0; i--) {
959                 if (s[i] == ' ') {
960                         if (i + 2 * indent <= limit) {
961                                 return i;
962                         } else {
963                                 last = i;
964                         }
965                 }
966         }
967         return last;
968 }
969
970 static int
971 get_breakpoint (const gchar * s, const gint indent, const gint limit)
972 {
973
974         if (g_utf8_validate (s, -1, NULL)) {
975                 return get_breakpoint_utf8 (s, indent, limit);
976         } else {                /* assume ASCII */
977                 //g_warning("invalid UTF-8 in msg");
978                 return get_breakpoint_ascii (s, indent, limit);
979         }
980 }
981
982 static gchar *
983 cite (const time_t sent_date, const gchar *from)
984 {
985         return g_strdup (_("mcen_ia_editor_original_message"));
986 }
987
988 static gchar *
989 quoted_attachments (GList *attachments)
990 {
991         GList *node = NULL;
992         GString *result = g_string_new ("");
993         for (node = attachments; node != NULL; node = g_list_next (node)) {
994                 gchar *filename = (gchar *) node->data;
995                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
996         }
997
998         return g_string_free (result, FALSE);
999
1000 }
1001
1002 static GString *
1003 modest_text_utils_quote_body (GString *output, const gchar *text,
1004                               const gchar *quote_symbol,
1005                               int limit)
1006 {
1007
1008         const gchar *iter;
1009         gsize len;
1010         gint indent = 0, breakpoint, rem_indent = 0;
1011         GString *l, *remaining;
1012         gchar *forced_wrap_append;
1013
1014         iter = text;
1015         len = strlen(text);
1016         remaining = g_string_new ("");
1017         forced_wrap_append = NULL;
1018         do {
1019
1020                 if (forced_wrap_append) {
1021                         gint next_line_indent;
1022                         gint l_len_with_indent;
1023
1024                         g_string_erase (remaining, 0, -1);
1025                         next_line_indent = get_indent_level (iter);
1026                         l = get_next_line (text, len, iter);
1027                         l_len_with_indent = l->len;
1028                         unquote_line (l, quote_symbol);
1029                         if ((l->str && l->str[0] == '\0') || (next_line_indent != indent)) {
1030                                 g_string_free (l, TRUE);
1031                                 l = g_string_new (forced_wrap_append);
1032                         } else {
1033                                 gunichar first_in_l;
1034                                 iter = iter + l_len_with_indent + 1;
1035                                 first_in_l = g_utf8_get_char_validated (l->str, l->len);
1036                                 if (!g_unichar_isspace (first_in_l)) 
1037                                         l = g_string_prepend (l, " ");
1038                                 l = g_string_prepend (l, forced_wrap_append);
1039                         }
1040                         g_free (forced_wrap_append);
1041                         forced_wrap_append = NULL;
1042                 } else {
1043                         l = get_next_line (text, len, iter);
1044                         iter = iter + l->len + 1;
1045                         indent = get_indent_level (l->str);
1046                         unquote_line (l, quote_symbol);
1047                 }
1048
1049                 if (remaining->len) {
1050                         if (l->len && indent == rem_indent) {
1051                                 g_string_prepend (l, " ");
1052                                 g_string_prepend (l, remaining->str);
1053                         } else {
1054                                 do {
1055                                         gunichar remaining_first;
1056                                         breakpoint =
1057                                                 get_breakpoint (remaining->str,
1058                                                                 rem_indent,
1059                                                                 limit);
1060                                         if (breakpoint < remaining->len) {
1061                                                 g_free (forced_wrap_append);
1062                                                 forced_wrap_append = g_strdup (remaining->str + breakpoint);
1063                                         } else {
1064                                                 if (!forced_wrap_append)
1065                                                         append_quoted (output, quote_symbol, rem_indent,
1066                                                                        remaining, breakpoint);
1067                                         }
1068                                         g_string_erase (remaining, 0,
1069                                                         breakpoint);
1070                                         remaining_first = g_utf8_get_char_validated (remaining->str, remaining->len);
1071                                         if (remaining_first != ((gunichar) -1)) {
1072                                                 if (g_unichar_isspace (remaining_first)) {
1073                                                         g_string_erase (remaining, 0, g_utf8_next_char (remaining->str) - remaining->str);
1074                                                 }
1075                                         }
1076                                 } while (remaining->len);
1077                         }
1078                 }
1079                 g_string_free (remaining, TRUE);
1080                 breakpoint = get_breakpoint (l->str, indent, limit);
1081                 remaining = g_string_new (l->str + breakpoint);
1082                 if (remaining->str[0] == ' ') {
1083                         g_string_erase (remaining, 0, 1);
1084                 }
1085                 rem_indent = indent;
1086                 if (remaining->len > 0) {
1087                         g_free (forced_wrap_append);
1088                         forced_wrap_append = g_strdup (remaining->str);
1089                 }
1090                 append_quoted (output, quote_symbol, indent, l, breakpoint);
1091                 g_string_free (l, TRUE);
1092         } while ((iter < text + len) || (remaining->str[0]) || forced_wrap_append);
1093
1094         return output;
1095 }
1096
1097 static gchar *
1098 modest_text_utils_quote_plain_text (const gchar *text, 
1099                                     const gchar *cite, 
1100                                     const gchar *signature,
1101                                     GList *attachments,
1102                                     int limit)
1103 {
1104         GString *q;
1105         gchar *attachments_string = NULL;
1106
1107         q = g_string_new ("");
1108
1109         if (signature != NULL) {
1110                 g_string_append_printf (q, "\n%s\n", MODEST_TEXT_UTILS_SIGNATURE_MARKER);
1111                 q = g_string_append (q, signature);
1112         }
1113
1114         q = g_string_append (q, "\n");
1115         q = g_string_append (q, cite);
1116         q = g_string_append_c (q, '\n');
1117
1118         q = modest_text_utils_quote_body (q, text, ">", limit);
1119
1120         attachments_string = quoted_attachments (attachments);
1121         q = g_string_append (q, attachments_string);
1122         g_free (attachments_string);
1123
1124         return g_string_free (q, FALSE);
1125 }
1126
1127 static void
1128 quote_html_add_to_gstring (GString *string,
1129                            const gchar *text)
1130 {
1131         if (text && strcmp (text, "")) {
1132                 gchar *html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
1133                 g_string_append_printf (string, "%s<br/>", html_text);
1134                 g_free (html_text);
1135         }
1136 }
1137
1138 static gchar*
1139 modest_text_utils_quote_html (const gchar *text, 
1140                               const gchar *cite, 
1141                               const gchar *signature,
1142                               GList *attachments,
1143                               int limit)
1144 {
1145         GString *result_string;
1146
1147         result_string =
1148                 g_string_new ( \
1149                               "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
1150                               "<html>\n"                                \
1151                               "<body>\n");
1152
1153         if (text || cite || signature) {
1154                 GString *quoted_text;
1155                 g_string_append (result_string, "<pre>\n");
1156                 if (signature) {
1157                         gchar *colored_signature = modest_text_utils_create_colored_signature (signature);
1158                         g_string_append_printf (result_string, "%s<br/>", colored_signature);
1159                         g_free (colored_signature);
1160                 }
1161                 quote_html_add_to_gstring (result_string, cite);
1162                 quoted_text = g_string_new ("");
1163                 quoted_text = modest_text_utils_quote_body (quoted_text, (text) ? text : "", ">", limit);
1164                 quote_html_add_to_gstring (result_string, quoted_text->str);
1165                 g_string_free (quoted_text, TRUE);
1166                 if (attachments) {
1167                         gchar *attachments_string = quoted_attachments (attachments);
1168                         quote_html_add_to_gstring (result_string, attachments_string);
1169                         g_free (attachments_string);
1170                 }
1171                 g_string_append (result_string, "</pre>");
1172         }
1173         g_string_append (result_string, "</body>");
1174         g_string_append (result_string, "</html>");
1175
1176         return g_string_free (result_string, FALSE);
1177 }
1178
1179 static gint 
1180 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
1181 {
1182         return match2->offset - match1->offset;
1183 }
1184
1185 static gint url_matches_block = 0;
1186 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
1187 static GMutex *url_patterns_mutex = NULL;
1188
1189
1190 static gboolean
1191 compile_patterns ()
1192 {
1193         guint i;
1194         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1195         for (i = 0; i != pattern_num; ++i) {
1196                 patterns[i].preg = g_slice_new0 (regex_t);
1197                 
1198                 /* this should not happen */
1199                 if (regcomp (patterns[i].preg, patterns[i].regex,
1200                              REG_ICASE|REG_EXTENDED|REG_NEWLINE) != 0) {
1201                         g_warning ("%s: error in regexp:\n%s\n", __FUNCTION__, patterns[i].regex);
1202                         return FALSE;
1203                 }
1204         }
1205         return TRUE;
1206 }
1207
1208 static void 
1209 free_patterns ()
1210 {
1211         guint i;
1212         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1213         for (i = 0; i != pattern_num; ++i) {
1214                 regfree (patterns[i].preg);
1215                 g_slice_free  (regex_t, patterns[i].preg);
1216         } /* don't free patterns itself -- it's static */
1217 }
1218
1219 void
1220 modest_text_utils_hyperlinkify_begin (void)
1221 {
1222
1223         if (url_patterns_mutex == NULL) {
1224                 url_patterns_mutex = g_mutex_new ();
1225         }
1226         g_mutex_lock (url_patterns_mutex);
1227         if (url_matches_block == 0)
1228                 compile_patterns ();
1229         url_matches_block ++;
1230         g_mutex_unlock (url_patterns_mutex);
1231 }
1232
1233 void
1234 modest_text_utils_hyperlinkify_end (void)
1235 {
1236         g_mutex_lock (url_patterns_mutex);
1237         url_matches_block--;
1238         if (url_matches_block <= 0)
1239                 free_patterns ();
1240         g_mutex_unlock (url_patterns_mutex);
1241 }
1242
1243
1244 static GSList*
1245 get_url_matches (GString *txt, gint offset)
1246 {
1247         regmatch_t rm;
1248         guint rv, i, tmp_offset = 0;
1249         GSList *match_list = NULL;
1250
1251         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1252
1253         /* initalize the regexps */
1254         modest_text_utils_hyperlinkify_begin ();
1255
1256         /* find all the matches */
1257         for (i = 0; i != pattern_num; ++i) {
1258                 tmp_offset     = offset;        
1259                 while (1) {
1260                         url_match_t *match;
1261                         gboolean is_submatch;
1262                         GSList *cursor;
1263                         
1264                         if ((rv = regexec (patterns[i].preg, txt->str + tmp_offset, 1, &rm, 0)) != 0) {
1265                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
1266                                 break; /* try next regexp */ 
1267                         }
1268                         if (rm.rm_so == -1)
1269                                 break;
1270                         
1271                         is_submatch = FALSE;
1272                         /* check  old matches to see if this has already been matched */
1273                         cursor = match_list;
1274                         while (cursor && !is_submatch) {
1275                                 const url_match_t *old_match =
1276                                         (const url_match_t *) cursor->data;
1277                                 guint new_offset = tmp_offset + rm.rm_so;
1278                                 is_submatch = (new_offset >  old_match->offset &&
1279                                                new_offset <  old_match->offset + old_match->len);
1280                                 cursor = g_slist_next (cursor);
1281                         }
1282
1283                         if (!is_submatch) {
1284                                 /* make a list of our matches (<offset, len, prefix> tupels)*/
1285                                 match = g_slice_new (url_match_t);
1286                                 match->offset = tmp_offset + rm.rm_so;
1287                                 match->len    = rm.rm_eo - rm.rm_so;
1288                                 match->prefix = patterns[i].prefix;
1289                                 match_list = g_slist_prepend (match_list, match);
1290                         }               
1291                         tmp_offset += rm.rm_eo;
1292                 }
1293         }
1294
1295         modest_text_utils_hyperlinkify_end ();
1296         
1297         /* now sort the list, so the matches are in reverse order of occurence.
1298          * that way, we can do the replacements starting from the end, so we don't need
1299          * to recalculate the offsets
1300          */
1301         match_list = g_slist_sort (match_list,
1302                                    (GCompareFunc)cmp_offsets_reverse); 
1303         return match_list;      
1304 }
1305
1306
1307
1308 /* replace all occurences of needle in haystack with repl*/
1309 static gchar*
1310 replace_string (const gchar *haystack, const gchar *needle, gchar repl)
1311 {
1312         gchar *str, *cursor;
1313
1314         if (!haystack || !needle || strlen(needle) == 0)
1315                 return haystack ? g_strdup(haystack) : NULL;
1316         
1317         str = g_strdup (haystack);
1318
1319         for (cursor = str; cursor && *cursor; ++cursor) {
1320                 if (g_str_has_prefix (cursor, needle)) {
1321                         cursor[0] = repl;
1322                         memmove (cursor + 1,
1323                                  cursor + strlen (needle),
1324                                  strlen (cursor + strlen (needle)) + 1);
1325                 }
1326         }
1327         
1328         return str;
1329 }
1330
1331 static void
1332 hyperlinkify_plain_text (GString *txt, gint offset)
1333 {
1334         GSList *cursor;
1335         GSList *match_list = get_url_matches (txt, offset);
1336
1337         /* we will work backwards, so the offsets stay valid */
1338         for (cursor = match_list; cursor; cursor = cursor->next) {
1339
1340                 url_match_t *match = (url_match_t*) cursor->data;
1341                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
1342                 gchar *repl = NULL; /* replacement  */
1343
1344                 /* the string still contains $(MARK_AMP_URI_STR)"amp;" for each
1345                  * '&' in the original, because of the text->html conversion.
1346                  * in the href-URL (and only there), we must convert that back to
1347                  * '&'
1348                  */
1349                 gchar *href_url = replace_string (url, MARK_AMP_URI_STR "amp;", '&');
1350                 
1351                 /* the prefix is NULL: use the one that is already there */
1352                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1353                                         match->prefix ? match->prefix : EMPTY_STRING, 
1354                                         href_url, url);
1355
1356                 /* replace the old thing with our hyperlink
1357                  * replacement thing */
1358                 g_string_erase  (txt, match->offset, match->len);
1359                 g_string_insert (txt, match->offset, repl);
1360                 
1361                 g_free (url);
1362                 g_free (repl);
1363                 g_free (href_url);
1364
1365                 g_slice_free (url_match_t, match);      
1366         }
1367         
1368         g_slist_free (match_list);
1369 }
1370
1371 void
1372 modest_text_utils_hyperlinkify (GString *string_buffer)
1373 {
1374         gchar *after_body;
1375         gint offset = 0;
1376
1377         after_body = strstr (string_buffer->str, "<body>");
1378         if (after_body != NULL)
1379                 offset = after_body - string_buffer->str;
1380         hyperlinkify_plain_text (string_buffer, offset);
1381 }
1382
1383
1384 /* for optimization reasons, we change the string in-place */
1385 void
1386 modest_text_utils_get_display_address (gchar *address)
1387 {
1388         int i;
1389
1390         g_return_if_fail (address);
1391         
1392         if (!address)
1393                 return;
1394         
1395         /* should not be needed, and otherwise, we probably won't screw up the address
1396          * more than it already is :) 
1397          * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1398          * */
1399         
1400         /* remove leading whitespace */
1401         if (address[0] == ' ')
1402                 g_strchug (address);
1403                 
1404         for (i = 0; address[i]; ++i) {
1405                 if (address[i] == '<') {
1406                         if (G_UNLIKELY(i == 0)) {
1407                                 break; /* there's nothing else, leave it */
1408                         }else {
1409                                 address[i] = '\0'; /* terminate the string here */
1410                                 break;
1411                         }
1412                 }
1413         }
1414
1415         g_strchomp (address);
1416 }
1417
1418
1419 gchar *
1420 modest_text_utils_get_display_addresses (const gchar *recipients)
1421 {
1422         gchar *addresses;
1423         GSList *recipient_list;
1424
1425         addresses = NULL;
1426         recipient_list = modest_text_utils_split_addresses_list (recipients);
1427         if (recipient_list) {
1428                 GString *add_string = g_string_sized_new (strlen (recipients));
1429                 GSList *iter = recipient_list;
1430                 gboolean first = TRUE;
1431
1432                 while (iter) {
1433                         /* Strings are changed in place */
1434                         modest_text_utils_get_display_address ((gchar *) iter->data);
1435                         if (G_UNLIKELY (first)) {
1436                                 g_string_append_printf (add_string, "%s", (gchar *) iter->data);
1437                                 first = FALSE;
1438                         } else {
1439                                 g_string_append_printf (add_string, ", %s", (gchar *) iter->data);
1440                         }
1441                         iter = g_slist_next (iter);
1442                 }
1443                 g_slist_foreach (recipient_list, (GFunc) g_free, NULL);
1444                 g_slist_free (recipient_list);
1445                 addresses = g_string_free (add_string, FALSE);
1446         }
1447
1448         return addresses;
1449 }
1450
1451
1452 gchar *
1453 modest_text_utils_get_email_address (const gchar *full_address)
1454 {
1455         const gchar *left, *right;
1456
1457         g_return_val_if_fail (full_address, NULL);
1458         
1459         if (!full_address)
1460                 return NULL;
1461         
1462         g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1463         
1464         left = g_strrstr_len (full_address, strlen(full_address), "<");
1465         if (left == NULL)
1466                 return g_strdup (full_address);
1467
1468         right = g_strstr_len (left, strlen(left), ">");
1469         if (right == NULL)
1470                 return g_strdup (full_address);
1471
1472         return g_strndup (left + 1, right - left - 1);
1473 }
1474
1475 gint 
1476 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1477 {
1478         gint prefix_len = 0;    
1479
1480         g_return_val_if_fail (sub, 0);
1481
1482         if (!sub)
1483                 return 0;
1484         
1485         /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1486         if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1487                 return 0;
1488         else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1489                 return 0;
1490
1491         prefix_len = 2;
1492         if (sub[2] == 'd')
1493                 ++prefix_len;
1494
1495         /* skip over a [...] block */
1496         if (sub[prefix_len] == '[') {
1497                 int c = prefix_len + 1;
1498                 while (sub[c] && sub[c] != ']')
1499                         ++c;
1500                 if (!sub[c])
1501                         return 0; /* no end to the ']' found */
1502                 else
1503                         prefix_len = c + 1;
1504         }
1505
1506         /* did we find the ':' ? */
1507         if (sub[prefix_len] == ':') {
1508                 ++prefix_len;
1509                 if (sub[prefix_len] == ' ')
1510                         ++prefix_len;
1511                 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1512 /*              g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1513                 return prefix_len;
1514         } else
1515                 return 0;
1516 }
1517
1518
1519 gint
1520 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1521 {
1522
1523 /* work even when s1 and/or s2 == NULL */
1524         if (G_UNLIKELY(s1 == s2))
1525                 return 0;
1526         if (G_UNLIKELY(!s1))
1527                 return -1;
1528         if (G_UNLIKELY(!s2))
1529                 return 1;
1530         
1531         /* if it's not case sensitive */
1532         if (!insensitive) {
1533
1534                 /* optimization: shortcut if first char is ascii */ 
1535                 if (((s1[0] & 0x80)== 0) && ((s2[0] & 0x80) == 0) &&
1536                     (s1[0] != s2[0])) 
1537                         return s1[0] - s2[0];
1538                 
1539                 return g_utf8_collate (s1, s2);
1540
1541         } else {
1542                 gint result;
1543                 gchar *n1, *n2;
1544
1545                 /* optimization: shortcut if first char is ascii */ 
1546                 if (((s1[0] & 0x80) == 0) && ((s2[0] & 0x80) == 0) &&
1547                     (tolower(s1[0]) != tolower (s2[0]))) 
1548                         return tolower(s1[0]) - tolower(s2[0]);
1549                 
1550                 n1 = g_utf8_strdown (s1, -1);
1551                 n2 = g_utf8_strdown (s2, -1);
1552                 
1553                 result = g_utf8_collate (n1, n2);
1554                 
1555                 g_free (n1);
1556                 g_free (n2);
1557         
1558                 return result;
1559         }
1560 }
1561
1562
1563 const gchar*
1564 modest_text_utils_get_display_date (time_t date)
1565 {
1566 #define DATE_BUF_SIZE 64 
1567         static gchar date_buf[DATE_BUF_SIZE];
1568         
1569         /* calculate the # of days since epoch for 
1570          * for today and for the date provided 
1571          * based on idea from pvanhoof */
1572         int day      = time(NULL) / (24 * 60 * 60);
1573         int date_day = date       / (24 * 60 * 60);
1574
1575         /* if it's today, show the time, if it's not today, show the date instead */
1576
1577         /* TODO: take into account the system config for 24/12h */
1578 #ifdef MODEST_TOOLKIT_HILDON2
1579         if (day == date_day) /* is the date today? */
1580                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_24h_time"), date);
1581         else 
1582                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_date"), date); 
1583 #else
1584         if (day == date_day) /* is the date today? */
1585                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%X", date);
1586         else 
1587                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%x", date); 
1588 #endif
1589
1590         return date_buf; /* this is a static buffer, don't free! */
1591 }
1592
1593
1594
1595 gboolean
1596 modest_text_utils_validate_folder_name (const gchar *folder_name)
1597 {
1598         /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1599          * with some extras */
1600         
1601         guint len;
1602         gint i;
1603         const gchar **cursor = NULL;
1604         const gchar *forbidden_names[] = { /* windows does not like these */
1605                 "CON", "PRN", "AUX", "NUL", ".", "..", "cur", "tmp", "new", 
1606                 NULL /* cur, tmp, new are reserved for Maildir */
1607         };
1608         
1609         /* cannot be NULL */
1610         if (!folder_name) 
1611                 return FALSE;
1612
1613         /* cannot be empty */
1614         len = strlen(folder_name);
1615         if (len == 0)
1616                 return FALSE;
1617         
1618         /* cannot start with a dot, vfat does not seem to like that */
1619         if (folder_name[0] == '.')
1620                 return FALSE;
1621
1622         /* cannot start or end with a space */
1623         if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1624                 return FALSE; 
1625
1626         /* cannot contain a forbidden char */   
1627         for (i = 0; i < len; i++)
1628                 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1629                         return FALSE;
1630
1631         /* Cannot contain Windows port numbers. I'd like to use GRegex
1632            but it's still not available in Maemo. sergio */
1633         if (!g_ascii_strncasecmp (folder_name, "LPT", 3) ||
1634             !g_ascii_strncasecmp (folder_name, "COM", 3)) {
1635                 glong val;
1636                 gchar *endptr;
1637
1638                 /* We skip the first 3 characters for the
1639                    comparison */
1640                 val = strtol(folder_name+3, &endptr, 10);
1641
1642                 /* If the conversion to long succeeded then the string
1643                    is not valid for us */
1644                 if (*endptr == '\0')
1645                         return FALSE;
1646                 else
1647                         return TRUE;
1648         }
1649         
1650         /* cannot contain a forbidden word */
1651         if (len <= 4) {
1652                 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1653                         if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1654                                 return FALSE;
1655                 }
1656         }
1657
1658         return TRUE; /* it's valid! */
1659 }
1660
1661
1662
1663 gboolean
1664 modest_text_utils_validate_domain_name (const gchar *domain)
1665 {
1666         gboolean valid = FALSE;
1667         regex_t rx;
1668         const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1669
1670         g_return_val_if_fail (domain, FALSE);
1671         
1672         if (!domain)
1673                 return FALSE;
1674         
1675         memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1676                 
1677         /* domain name: all alphanum or '-' or '.',
1678          * but beginning/ending in alphanum */  
1679         if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1680                 g_warning ("BUG: error in regexp");
1681                 return FALSE;
1682         }
1683         
1684         valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1685         regfree (&rx);
1686                 
1687         return valid;
1688 }
1689
1690
1691
1692 gboolean
1693 modest_text_utils_validate_email_address (const gchar *email_address,
1694                                           const gchar **invalid_char_position)
1695 {
1696         int count = 0;
1697         const gchar *c = NULL, *domain = NULL;
1698         static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1699         
1700         if (invalid_char_position)
1701                 *invalid_char_position = NULL;
1702         
1703         g_return_val_if_fail (email_address, FALSE);
1704         
1705         /* check that the email adress contains exactly one @ */
1706         if (!strstr(email_address, "@") || 
1707                         (strstr(email_address, "@") != g_strrstr(email_address, "@"))) 
1708                 return FALSE;
1709         
1710         /* first we validate the name portion (name@domain) */
1711         for (c = email_address;  *c;  c++) {
1712                 if (*c == '\"' && 
1713                     (c == email_address || 
1714                      *(c - 1) == '.' || 
1715                      *(c - 1) == '\"')) {
1716                         while (*++c) {
1717                                 if (*c == '\"') 
1718                                         break;
1719                                 if (*c == '\\' && (*++c == ' ')) 
1720                                         continue;
1721                                 if (*c <= ' ' || *c >= 127) 
1722                                         return FALSE;
1723                         }
1724                         if (!*c++) 
1725                                 return FALSE;
1726                         if (*c == '@') 
1727                                 break;
1728                         if (*c != '.') 
1729                                 return FALSE;
1730                         continue;
1731                 }
1732                 if (*c == '@') 
1733                         break;
1734                 if (*c <= ' ' || *c >= 127) 
1735                         return FALSE;
1736                 if (strchr(rfc822_specials, *c)) {
1737                         if (invalid_char_position)
1738                                 *invalid_char_position = c;
1739                         return FALSE;
1740                 }
1741         }
1742         if (c == email_address || *(c - 1) == '.') 
1743                 return FALSE;
1744
1745         /* next we validate the domain portion (name@domain) */
1746         if (!*(domain = ++c)) 
1747                 return FALSE;
1748         do {
1749                 if (*c == '.') {
1750                         if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0') 
1751                                 return FALSE;
1752                         count++;
1753                 }
1754                 if (*c <= ' ' || *c >= 127) 
1755                         return FALSE;
1756                 if (strchr(rfc822_specials, *c)) {
1757                         if (invalid_char_position)
1758                                 *invalid_char_position = c;
1759                         return FALSE;
1760                 }
1761         } while (*++c);
1762
1763         return (count >= 1) ? TRUE : FALSE;
1764 }
1765
1766 gboolean 
1767 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1768 {
1769         gchar *stripped, *current;
1770         gchar *right_part;
1771         gboolean has_error = FALSE;
1772
1773         if (invalid_char_position)
1774                 *invalid_char_position = NULL;
1775         
1776         g_return_val_if_fail (recipient, FALSE);
1777         
1778         if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1779                 return TRUE;
1780
1781         stripped = g_strdup (recipient);
1782         stripped = g_strstrip (stripped);
1783         current = stripped;
1784
1785         if (*current == '\0') {
1786                 g_free (stripped);
1787                 return FALSE;
1788         }
1789
1790         /* quoted string */
1791         if (*current == '\"') {
1792                 gchar *last_quote = NULL;
1793                 current = g_utf8_next_char (current);
1794                 has_error = TRUE;
1795                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1796                         if (*current == '\\') {
1797                                 /* TODO: This causes a warning, which breaks the build, 
1798                                  * because a gchar cannot be < 0.
1799                                  * murrayc. 
1800                                 if (current[1] <0) {
1801                                         has_error = TRUE;
1802                                         break;
1803                                 }
1804                                 */
1805                         } else if (*current == '\"') {
1806                                 has_error = FALSE;
1807                                 current = g_utf8_next_char (current);
1808                                 last_quote = current;
1809                         }
1810                 }
1811                 if (last_quote)
1812                         current = g_utf8_next_char (last_quote);
1813         } else {
1814                 has_error = TRUE;
1815                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1816                         if (*current == '<') {
1817                                 has_error = FALSE;
1818                                 break;
1819                         }
1820                 }
1821         }
1822                 
1823         if (has_error) {
1824                 g_free (stripped);
1825                 return FALSE;
1826         }
1827
1828         right_part = g_strdup (current);
1829         g_free (stripped);
1830         right_part = g_strstrip (right_part);
1831
1832         if (g_str_has_suffix (right_part, ",") || g_str_has_suffix (right_part, ";"))
1833                right_part [(strlen (right_part) - 1)] = '\0';
1834
1835         if (g_str_has_prefix (right_part, "<") &&
1836             g_str_has_suffix (right_part, ">")) {
1837                 gchar *address;
1838                 gboolean valid;
1839
1840                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1841                 g_free (right_part);
1842                 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1843                 g_free (address);
1844                 return valid;
1845         } else {
1846                 g_free (right_part);
1847                 return FALSE;
1848         }
1849 }
1850
1851
1852 gchar *
1853 modest_text_utils_get_display_size (guint64 size)
1854 {
1855         const guint KB=1024;
1856         const guint MB=1024 * KB;
1857         const guint GB=1024 * MB;
1858
1859         if (size == 0)
1860                 return g_strdup_printf (_FM("sfil_li_size_kb"), (int) 0);
1861         if (0 <= size && size < KB)
1862                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), (int) 1);
1863         else if (KB <= size && size < 100 * KB)
1864                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), (int) size / KB);
1865         else if (100*KB <= size && size < MB)
1866                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (int) size / KB);
1867         else if (MB <= size && size < 10*MB)
1868                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1869         else if (10*MB <= size && size < GB)
1870                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), (float) size / MB);
1871         else
1872                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB);
1873 }
1874
1875 static gchar *
1876 get_email_from_address (const gchar * address)
1877 {
1878         gchar *left_limit, *right_limit;
1879
1880         left_limit = strstr (address, "<");
1881         right_limit = g_strrstr (address, ">");
1882
1883         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1884                 return g_strdup (address);
1885         else
1886                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1887 }
1888
1889 gchar *
1890 modest_text_utils_get_color_string (GdkColor *color)
1891 {
1892         g_return_val_if_fail (color, NULL);
1893
1894         return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1895                                 (color->red >> 12)   & 0xf, (color->red >> 8)   & 0xf,
1896                                 (color->red >>  4)   & 0xf, (color->red)        & 0xf,
1897                                 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1898                                 (color->green >>  4) & 0xf, (color->green)      & 0xf,
1899                                 (color->blue >> 12)  & 0xf, (color->blue >> 8)  & 0xf,
1900                                 (color->blue >>  4)  & 0xf, (color->blue)       & 0xf);
1901 }
1902
1903 gchar *
1904 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1905 {
1906         GtkTextIter start, end;
1907         gchar *slice, *current;
1908         GString *result = g_string_new ("");
1909
1910         g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1911         
1912         gtk_text_buffer_get_start_iter (buffer, &start);
1913         gtk_text_buffer_get_end_iter (buffer, &end);
1914
1915         slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1916         current = slice;
1917
1918         while (current && current != '\0') {
1919                 if (g_utf8_get_char (current) == 0xFFFC) {
1920                         result = g_string_append_c (result, ' ');
1921                         current = g_utf8_next_char (current);
1922                 } else {
1923                         gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1924                         if (next == NULL) {
1925                                 result = g_string_append (result, current);
1926                         } else {
1927                                 result = g_string_append_len (result, current, next - current);
1928                         }
1929                         current = next;
1930                 }
1931         }
1932         g_free (slice);
1933
1934         return g_string_free (result, FALSE);
1935         
1936 }
1937
1938 gboolean
1939 modest_text_utils_is_forbidden_char (const gchar character,
1940                                      ModestTextUtilsForbiddenCharType type)
1941 {
1942         gint i, len;
1943         const gchar *forbidden_chars = NULL;
1944         
1945         /* We need to get the length in the switch because the
1946            compiler needs to know the size at compile time */
1947         switch (type) {
1948         case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1949                 forbidden_chars = account_title_forbidden_chars;
1950                 len = G_N_ELEMENTS (account_title_forbidden_chars);
1951                 break;
1952         case FOLDER_NAME_FORBIDDEN_CHARS:
1953                 forbidden_chars = folder_name_forbidden_chars;
1954                 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1955                 break;
1956         case USER_NAME_FORBIDDEN_NAMES:
1957                 forbidden_chars = user_name_forbidden_chars;
1958                 len = G_N_ELEMENTS (user_name_forbidden_chars);
1959                 break;
1960         default:
1961                 g_return_val_if_reached (TRUE);
1962         }
1963
1964         for (i = 0; i < len ; i++)
1965                 if (forbidden_chars[i] == character)
1966                         return TRUE;
1967
1968         return FALSE; /* it's valid! */
1969 }
1970
1971 gchar *      
1972 modest_text_utils_label_get_selection (GtkLabel *label)
1973 {
1974         gint start, end;
1975         gchar *selection;
1976
1977         if (gtk_label_get_selection_bounds (GTK_LABEL (label), &start, &end)) {
1978                 const gchar *start_offset;
1979                 const gchar *end_offset;
1980                 start_offset = gtk_label_get_text (GTK_LABEL (label));
1981                 start_offset = g_utf8_offset_to_pointer (start_offset, start);
1982                 end_offset = gtk_label_get_text (GTK_LABEL (label));
1983                 end_offset = g_utf8_offset_to_pointer (end_offset, end);
1984                 selection = g_strndup (start_offset, end_offset - start_offset);
1985                 return selection;
1986         } else {
1987                 return g_strdup ("");
1988         }
1989 }
1990
1991 static gboolean
1992 _forward_search_image_char (gunichar ch,
1993                             gpointer userdata)
1994 {
1995         return (ch == 0xFFFC);
1996 }
1997
1998 gboolean
1999 modest_text_utils_buffer_selection_is_valid (GtkTextBuffer *buffer)
2000 {
2001         gboolean result;
2002         GtkTextIter start, end;
2003
2004         g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2005
2006         result = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (buffer));
2007
2008         /* check there are no images in selection */
2009         if (result) {
2010                 gtk_text_buffer_get_selection_bounds (buffer, &start, &end);
2011                 if (gtk_text_iter_get_char (&start)== 0xFFFC)
2012                         result = FALSE;
2013                 else {
2014                         gtk_text_iter_backward_char (&end);
2015                         if (gtk_text_iter_forward_find_char (&start, _forward_search_image_char,
2016                                                              NULL, &end))
2017                                 result = FALSE;
2018                 }
2019                                     
2020         }
2021
2022         return result;
2023 }
2024
2025 static void
2026 remove_quotes (gchar **quotes)
2027 {
2028         if (g_str_has_prefix (*quotes, "\"") && g_str_has_suffix (*quotes, "\"")) {
2029                 gchar *result;
2030                 result = g_strndup ((*quotes)+1, strlen (*quotes) - 2);
2031                 g_free (*quotes);
2032                 *quotes = result;
2033         }
2034 }
2035
2036 static void
2037 remove_extra_spaces (gchar *string)
2038 {
2039         gchar *start;
2040
2041         start = string;
2042         while (start && start[0] != '\0') {
2043                 if ((start[0] == ' ') && (start[1] == ' ')) {
2044                         g_strchug (start+1);
2045                 }
2046                 start++;
2047         }
2048 }
2049
2050 gchar *
2051 modest_text_utils_escape_mnemonics (const gchar *text)
2052 {
2053         const gchar *p;
2054         GString *result = NULL;
2055
2056         if (text == NULL)
2057                 return NULL;
2058
2059         result = g_string_new ("");
2060         for (p = text; *p != '\0'; p++) {
2061                 if (*p == '_')
2062                         result = g_string_append (result, "__");
2063                 else
2064                         result = g_string_append_c (result, *p);
2065         }
2066         
2067         return g_string_free (result, FALSE);
2068 }
2069
2070 gchar *
2071 modest_text_utils_simplify_recipients (const gchar *recipients)
2072 {
2073         GSList *addresses, *node;
2074         GString *result;
2075         gboolean is_first = TRUE;
2076
2077         if (recipients == NULL)
2078                 return g_strdup ("");
2079
2080         addresses = modest_text_utils_split_addresses_list (recipients);
2081         result = g_string_new ("");
2082
2083         for (node = addresses; node != NULL; node = g_slist_next (node)) {
2084                 const gchar *address = (const gchar *) node->data;
2085                 gchar *left_limit, *right_limit;
2086
2087                 left_limit = strstr (address, "<");
2088                 right_limit = g_strrstr (address, ">");
2089
2090                 if (is_first)
2091                         is_first = FALSE;
2092                 else
2093                         result = g_string_append (result, ", ");
2094
2095                 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit)) {
2096                         result = g_string_append (result, address);
2097                 } else {
2098                         gchar *name_side;
2099                         gchar *email_side;
2100                         name_side = g_strndup (address, left_limit - address);
2101                         name_side = g_strstrip (name_side);
2102                         remove_quotes (&name_side);
2103                         email_side = get_email_from_address (address);
2104                         if (name_side && email_side && !strcmp (name_side, email_side)) {
2105                                 result = g_string_append (result, email_side);
2106                         } else {
2107                                 result = g_string_append (result, address);
2108                         }
2109                         g_free (name_side);
2110                         g_free (email_side);
2111                 }
2112
2113         }
2114         g_slist_foreach (addresses, (GFunc)g_free, NULL);
2115         g_slist_free (addresses);
2116
2117         return g_string_free (result, FALSE);
2118
2119 }
2120
2121 GSList *
2122 modest_text_utils_remove_duplicate_addresses_list (GSList *address_list)
2123 {
2124         GSList *new_list, *iter;
2125         GHashTable *table;
2126
2127         g_return_val_if_fail (address_list, NULL);
2128
2129         table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2130
2131         new_list = address_list;
2132         iter = address_list;
2133         while (iter) {
2134                 const gchar* address = (const gchar*)iter->data;
2135
2136                 /* We need only the email to just compare it and not
2137                    the full address which would make "a <a@a.com>"
2138                    different from "a@a.com" */
2139                 const gchar *email = get_email_from_address (address);
2140
2141                 /* ignore the address if already seen */
2142                 if (g_hash_table_lookup (table, email) == 0) {
2143                         g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
2144                         iter = g_slist_next (iter);
2145                 } else {
2146                         GSList *tmp = g_slist_next (iter);
2147                         new_list = g_slist_delete_link (new_list, iter);
2148                         iter = tmp;
2149                 }
2150         }
2151
2152         g_hash_table_unref (table);
2153
2154         return new_list;
2155 }
2156
2157 gchar *
2158 modest_text_utils_get_secure_header (const gchar *value,
2159                                      const gchar *header)
2160 {
2161         const gint max_len = 16384;
2162         gchar *new_value = NULL;
2163         gchar *needle = g_strrstr (value, header);
2164
2165         if (needle && value != needle)
2166                 new_value = g_strdup (needle + strlen (header));
2167
2168         if (!new_value)
2169                 new_value = g_strdup (value);
2170
2171         /* Do a max length check to prevent DoS attacks caused by huge
2172            malformed headers */
2173         if (g_utf8_validate (new_value, -1, NULL)) {
2174                 if (g_utf8_strlen (new_value, -1) > max_len) {
2175                         gchar *tmp = g_malloc0 (max_len * 4);
2176                         g_utf8_strncpy (tmp, (const gchar *) new_value, max_len);
2177                         g_free (new_value);
2178                         new_value = tmp;
2179                 }
2180         } else {
2181                 if (strlen (new_value) > max_len) {
2182                         gchar *tmp = g_malloc0 (max_len);
2183                         strncpy (new_value, tmp, max_len);
2184                         g_free (new_value);
2185                         new_value = tmp;
2186                 }
2187         }
2188
2189         return new_value;
2190 }
2191
2192 static gboolean
2193 is_quoted (const char *start, const gchar *end)
2194 {
2195         gchar *c;
2196
2197         c = (gchar *) start;
2198         while (*c == ' ')
2199                 c = g_utf8_next_char (c);
2200
2201         if (*c == '\0' || *c != '\"')
2202                 return FALSE;
2203
2204         c = (gchar *) end;
2205         while (*c == ' ' && c != start)
2206                 c = g_utf8_prev_char (c);
2207
2208         if (c == start || *c != '\"')
2209                 return FALSE;
2210
2211         return TRUE;
2212 }
2213
2214
2215 static void
2216 quote_name_part (GString **str, gchar **cur, gchar **start)
2217 {
2218         gchar *blank;
2219         gint str_len = *cur - *start;
2220
2221         while (**start == ' ') {
2222                 *start = g_utf8_next_char (*start);
2223                 str_len--;
2224         }
2225
2226         blank = g_utf8_strrchr (*start, str_len, g_utf8_get_char (" "));
2227         if (blank && (blank != *start)) {
2228                 if (is_quoted (*start, blank - 1)) {
2229                         *str = g_string_append_len (*str, *start, str_len);
2230                         *str = g_string_append (*str, ";");
2231                         *start = g_utf8_next_char (*cur);
2232                 } else {
2233                         *str = g_string_append_c (*str, '"');
2234                         *str = g_string_append_len (*str, *start, (blank - *start));
2235                         *str = g_string_append_c (*str, '"');
2236                         *str = g_string_append_len (*str, blank, (*cur - blank));
2237                         *str = g_string_append (*str, ";");
2238                         *start = g_utf8_next_char (*cur);
2239                 }
2240         } else {
2241                 *str = g_string_append_len (*str, *start, str_len);
2242                 *str = g_string_append (*str, ";");
2243                 *start = g_utf8_next_char (*cur);
2244         }
2245 }
2246
2247 gchar *
2248 modest_text_utils_quote_names (const gchar *recipients)
2249 {
2250         GString *str;
2251         gchar *start, *cur;
2252
2253         str = g_string_new ("");
2254         start = (gchar*) recipients;
2255         cur = (gchar*) recipients;
2256
2257         for (cur = start; *cur != '\0'; cur = g_utf8_next_char (cur)) {
2258                 if (*cur == ',' || *cur == ';') {
2259                         if (!g_utf8_strchr (start, (cur - start + 1), g_utf8_get_char ("@")))
2260                                 continue;
2261                         quote_name_part (&str, &cur, &start);
2262                 }
2263         }
2264
2265         quote_name_part (&str, &cur, &start);
2266
2267         return g_string_free (str, FALSE);
2268 }
2269
2270 /* Returns TRUE if there is no recipients in the text buffer. Note
2271    that strings like " ; , " contain only separators and thus no
2272    recipients */
2273 gboolean
2274 modest_text_utils_no_recipient (GtkTextBuffer *buffer)
2275 {
2276         gboolean retval = TRUE;
2277         gchar *text, *tmp;
2278         GtkTextIter start, end;
2279
2280         if (gtk_text_buffer_get_char_count (buffer) == 0)
2281                 return TRUE;
2282
2283         gtk_text_buffer_get_start_iter (buffer, &start);
2284         gtk_text_buffer_get_end_iter (buffer, &end);
2285
2286         text = g_strstrip (gtk_text_buffer_get_text (buffer, &start, &end, FALSE));
2287         if (!g_strcmp0 (text, ""))
2288                 return TRUE;
2289
2290         tmp = text;
2291         while (tmp && *tmp != '\0') {
2292                 if ((*tmp != ',') && (*tmp != ';') &&
2293                     (*tmp != '\r') && (*tmp != '\n') &&
2294                     (*tmp != ' ')) {
2295                         retval = FALSE;
2296                         break;
2297                 } else {
2298                         tmp++;
2299                 }
2300         }
2301         g_free (text);
2302
2303         return retval;
2304 }
2305
2306 gchar *
2307 modest_text_utils_create_colored_signature (const gchar *signature)
2308 {
2309         gchar *gray_color_markup = NULL, *retval;
2310         GdkColor color;
2311         GtkWidget *widget;
2312
2313         /* Get color from widgets */
2314         widget = (GtkWidget *) modest_window_mgr_get_current_top (modest_runtime_get_window_mgr ());
2315         if (widget && gtk_style_lookup_color (gtk_widget_get_style (widget), "SecondaryTextColor", &color))
2316                 gray_color_markup = modest_text_utils_get_color_string (&color);
2317
2318         retval = g_strdup_printf ("<br/>\n<font color=\"%s\">%s<br/>\n%s<br/>\n</font>",
2319                                   (gray_color_markup) ? gray_color_markup : "#babababababa",
2320                                   MODEST_TEXT_UTILS_SIGNATURE_MARKER,
2321                                   signature);
2322
2323         if (gray_color_markup)
2324                 g_free (gray_color_markup);
2325
2326         return retval;
2327 }
2328
2329 gboolean
2330 modest_text_utils_live_search_find (const gchar *haystack, const gchar *needles)
2331 {
2332         gchar *haystack_fold;
2333         gchar *needles_fold;
2334         gchar **needle, **current;
2335         gboolean match;
2336
2337         match = FALSE;
2338
2339         haystack_fold = g_utf8_casefold (haystack, -1);
2340         needles_fold = g_utf8_casefold (needles, -1);
2341
2342         needle = g_strsplit (needles_fold, " ", -1);
2343
2344         current = needle;
2345         while (current && *current != NULL) {
2346
2347                 if (g_strstr_len (haystack_fold, -1, *current) != NULL) {
2348                         match = TRUE;
2349                 } else {
2350                         match = FALSE;
2351                         break;
2352                 }
2353                 current++;
2354         }
2355
2356         g_strfreev (needle);
2357         g_free (needles_fold);
2358         g_free (haystack_fold);
2359         
2360         return match;
2361 }