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