* fix the url handling of '&'; it's a bit hairy because of the
[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 /*
69  * we mark the ampersand with \007 when converting text->html
70  * because after text->html we do hyperlink detecting, which
71  * could be screwed up by the ampersand
72  */
73 #define MARK_AMP '\007'
74 #define MARK_AMP_STR "\007"
75
76 /*
77  * we need these regexps to find URLs in plain text e-mails
78  */
79 typedef struct _url_match_pattern_t url_match_pattern_t;
80 struct _url_match_pattern_t {
81         gchar   *regex;
82         regex_t *preg;
83         gchar   *prefix;
84 };
85
86 typedef struct _url_match_t url_match_t;
87 struct _url_match_t {
88         guint offset;
89         guint len;
90         const gchar* prefix;
91 };
92
93 /* note: match MARK_AMP_STR as well, because after txt->html, a '&' will look like $(MARK_AMP_STR)"amp;" */
94 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
95         { "^(file|rtsp|http|ftp|https)://[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_STR "]+[-a-z0-9_$%" MARK_AMP_STR "=?/~#]",\
96           NULL, NULL },\
97         { "^www\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_STR "]+[-a-z0-9_$%" MARK_AMP_STR "=?/~#]",\
98                         NULL, "http://" },                              \
99         { "^ftp\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_STR "]+[-a-z0-9_$%" MARK_AMP_STR "=?/~#]",\
100           NULL, "ftp://" },\
101         { "^(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.+]+", \
102            NULL, NULL},                                             \
103         { "^mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                   \
104           NULL, NULL},\
105         { "^[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
106           NULL, "mailto:"}\
107         }
108
109 const gchar account_title_forbidden_chars[] = {
110         '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
111 };
112 const gchar folder_name_forbidden_chars[] = {
113         '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$', '#', '&'
114 };
115 const gchar user_name_forbidden_chars[] = {
116         '<', '>'
117 };
118 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
119 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
120 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
121
122 /* private */
123 static gchar*   cite                    (const time_t sent_date, const gchar *from);
124 static void     hyperlinkify_plain_text (GString *txt);
125 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
126 static GSList*  get_url_matches         (GString *txt);
127
128 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
129 static int      get_indent_level        (const char *l);
130 static void     unquote_line            (GString * l);
131 static void     append_quoted           (GString * buf, const int indent, const GString * str, 
132                                          const int cutpoint);
133 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
134 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
135 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
136
137 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
138                                                     const gchar *cite, 
139                                                     const gchar *signature,
140                                                     GList *attachments, 
141                                                     int limit);
142
143 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
144                                                     const gchar *cite,
145                                                     const gchar *signature,
146                                                     GList *attachments,
147                                                     int limit);
148 static gchar*   get_email_from_address (const gchar *address);
149
150
151 /* ******************************************************************* */
152 /* ************************* PUBLIC FUNCTIONS ************************ */
153 /* ******************************************************************* */
154
155 gchar *
156 modest_text_utils_quote (const gchar *text, 
157                          const gchar *content_type,
158                          const gchar *signature,
159                          const gchar *from,
160                          const time_t sent_date, 
161                          GList *attachments,
162                          int limit)
163 {
164         gchar *retval, *cited;
165
166         g_return_val_if_fail (text, NULL);
167         g_return_val_if_fail (content_type, NULL);
168
169         cited = cite (sent_date, from);
170         
171         if (content_type && strcmp (content_type, "text/html") == 0)
172                 /* TODO: extract the <body> of the HTML and pass it to
173                    the function */
174                 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
175         else
176                 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
177         
178         g_free (cited);
179         
180         return retval;
181 }
182
183
184 gchar *
185 modest_text_utils_cite (const gchar *text,
186                         const gchar *content_type,
187                         const gchar *signature,
188                         const gchar *from,
189                         time_t sent_date)
190 {
191         gchar *retval;
192         gchar *tmp_sig;
193         
194         g_return_val_if_fail (text, NULL);
195         g_return_val_if_fail (content_type, NULL);
196         
197         if (!signature)
198                 retval = g_strdup ("");
199         else if (strcmp(content_type, "text/html") == 0) {
200                 tmp_sig = g_strconcat ("\n", signature, NULL);
201                 retval = modest_text_utils_convert_to_html_body(tmp_sig, -1, TRUE);
202                 g_free (tmp_sig);
203         } else {
204                 retval = g_strconcat (text, "\n", signature, NULL);
205         }
206
207         return retval;
208 }
209
210 static gchar *
211 forward_cite (const gchar *from,
212               const gchar *sent,
213               const gchar *to,
214               const gchar *subject)
215 {
216         return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n", 
217                                 FORWARD_STRING, 
218                                 FROM_STRING, (from)?from:"",
219                                 SENT_STRING, sent,
220                                 TO_STRING, (to)?to:"",
221                                 SUBJECT_STRING, (subject)?subject:"");
222 }
223
224 gchar * 
225 modest_text_utils_inline (const gchar *text,
226                           const gchar *content_type,
227                           const gchar *signature,
228                           const gchar *from,
229                           time_t sent_date,
230                           const gchar *to,
231                           const gchar *subject)
232 {
233         gchar sent_str[101];
234         gchar *cited;
235         gchar *retval;
236         
237         g_return_val_if_fail (text, NULL);
238         g_return_val_if_fail (content_type, NULL);
239         
240         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
241
242         cited = forward_cite (from, sent_str, to, subject);
243         
244         if (content_type && strcmp (content_type, "text/html") == 0)
245                 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
246         else
247                 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
248         
249         g_free (cited);
250         return retval;
251 }
252
253 /* just to prevent warnings:
254  * warning: `%x' yields only last 2 digits of year in some locales
255  */
256 gsize
257 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
258 {
259         struct tm tm;
260
261         /* does not work on old maemo glib: 
262          *   g_date_set_time_t (&date, timet);
263          */
264         localtime_r (&timet, &tm);
265         return strftime(s, max, fmt, &tm);
266 }
267
268 gchar *
269 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
270 {
271         gchar *tmp;
272
273         g_return_val_if_fail (prefix, NULL);
274
275         if (!subject || subject[0] == '\0')
276                 subject = _("mail_va_no_subject");
277
278         tmp = g_strchug (g_strdup (subject));
279
280         if (!strncmp (tmp, prefix, strlen (prefix))) {
281                 return tmp;
282         } else {
283                 g_free (tmp);
284                 return g_strdup_printf ("%s %s", prefix, subject);
285         }
286 }
287
288 gchar*
289 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
290 {
291         gchar *dup, *token, *ptr = NULL, *result;
292         GString *filtered_emails;
293         gchar *email_address;
294
295         g_return_val_if_fail (address_list, NULL);
296         
297         if (!address)
298                 return g_strdup (address_list);
299
300         email_address = get_email_from_address (address);
301         
302         /* search for substring */
303         if (!strstr ((const char *) address_list, (const char *) email_address)) {
304                 g_free (email_address);
305                 return g_strdup (address_list);
306         }
307
308         dup = g_strdup (address_list);
309         filtered_emails = g_string_new (NULL);
310         
311         token = strtok_r (dup, ",", &ptr);
312
313         while (token != NULL) {
314                 /* Add to list if not found */
315                 if (!strstr ((const char *) token, (const char *) email_address)) {
316                         if (filtered_emails->len == 0)
317                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
318                         else
319                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
320                 }
321                 token = strtok_r (NULL, ",", &ptr);
322         }
323         result = filtered_emails->str;
324
325         /* Clean */
326         g_free (email_address);
327         g_free (dup);
328         g_string_free (filtered_emails, FALSE);
329
330         return result;
331 }
332
333
334 gchar*
335 modest_text_utils_remove_duplicate_addresses (const gchar *address_list)
336 {
337         GSList *addresses, *cursor;
338         GHashTable *table;
339         gchar *new_list;
340         
341         g_return_val_if_fail (address_list, NULL);
342
343         table = g_hash_table_new (g_str_hash, g_str_equal);
344         addresses = modest_text_utils_split_addresses_list (address_list);
345
346         new_list = g_strdup("");
347         cursor = addresses;
348         while (cursor) {
349                 const gchar* address = (const gchar*)cursor->data;
350
351                 /* ignore the address if already seen */
352                 if (g_hash_table_lookup (table, address) == 0) {
353                 
354                         gchar *tmp = g_strjoin (",", new_list, address, NULL);
355                         g_free (new_list);
356                         new_list = tmp;
357                         
358                         g_hash_table_insert (table, (gchar*)address, GINT_TO_POINTER(1));
359                 }
360                 cursor = g_slist_next (cursor);
361         }
362
363         g_hash_table_destroy (table);
364         g_slist_foreach (addresses, (GFunc)g_free, NULL);
365         g_slist_free (addresses);
366
367         return new_list;
368 }
369
370
371 static void
372 modest_text_utils_convert_buffer_to_html_start (GString *html, const gchar *data, gssize n)
373 {
374         guint           i;
375         gboolean        space_seen = FALSE;
376         guint           break_dist = 0; /* distance since last break point */
377
378         if (n == -1)
379                 n = strlen (data);
380
381         /* replace with special html chars where needed*/
382         for (i = 0; i != n; ++i)  {
383                 char kar = data[i];
384                 
385                 if (space_seen && kar != ' ') {
386                         g_string_append_c (html, ' ');
387                         space_seen = FALSE;
388                 }
389                 
390                 /* we artificially insert a breakpoint (newline)
391                  * after 256, to make sure our lines are not so long
392                  * they will DOS the regexping later
393                  */
394                 if (++break_dist == 256) {
395                         g_string_append_c (html, '\n');
396                         break_dist = 0;
397                 }
398                 
399                 switch (kar) {
400                 case 0:
401                 case MARK_AMP: /* this is a temp place holder for '&'; we can only
402                                 * set the real '&' after hyperlink translation, otherwise
403                                 * we might screw that up */
404                         break; /* ignore embedded \0s and MARK_AMP */   
405                 case '<'  : g_string_append (html, MARK_AMP_STR "lt;");   break;
406                 case '>'  : g_string_append (html, MARK_AMP_STR "gt;");   break;
407                 case '&'  : g_string_append (html, MARK_AMP_STR "amp;");  break;
408                 case '"'  : g_string_append (html, MARK_AMP_STR "quot;");  break;
409
410                 /* don't convert &apos; --> wpeditor will try to re-convert it... */    
411                 //case '\'' : g_string_append (html, "&apos;"); break;
412                 case '\n' : g_string_append (html, "<br>\n");break_dist= 0; break;
413                 case '\t' : g_string_append (html, MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp; ");
414                         break_dist=0; break; /* note the space at the end*/
415                 case ' ':
416                         break_dist = 0;
417                         if (space_seen) { /* second space in a row */
418                                 g_string_append (html, "&nbsp; ");
419                                 space_seen = FALSE;
420                         } else
421                                 space_seen = TRUE;
422                         break;
423                 default:
424                         g_string_append_c (html, kar);
425                 }
426         }
427 }
428
429
430 static void
431 modest_text_utils_convert_buffer_to_html_finish (GString *html)
432 {
433         int i;
434         /* replace all our MARK_AMPs with real ones */
435         for (i = 0; i != html->len; ++i)
436                 if ((html->str)[i] == MARK_AMP)
437                         (html->str)[i] = '&';
438 }
439
440
441 gchar*
442 modest_text_utils_convert_to_html (const gchar *data)
443 {
444         GString         *html;      
445         gsize           len;
446
447         g_return_val_if_fail (data, NULL);
448         
449         if (!data)
450                 return NULL;
451
452         len = strlen (data);
453         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
454
455         g_string_append_printf (html,
456                                 "<html><head>"
457                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
458                                 "</head>"
459                                 "<body>");
460
461         modest_text_utils_convert_buffer_to_html_start (html, data, -1);
462         
463         g_string_append (html, "</body></html>");
464
465         if (len <= HYPERLINKIFY_MAX_LENGTH)
466                 hyperlinkify_plain_text (html);
467
468         modest_text_utils_convert_buffer_to_html_finish (html);
469         
470         return g_string_free (html, FALSE);
471 }
472
473 gchar *
474 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
475 {
476         GString         *html;      
477
478         g_return_val_if_fail (data, NULL);
479
480         if (!data)
481                 return NULL;
482
483         if (n == -1) 
484                 n = strlen (data);
485         html = g_string_sized_new (1.5 * n);    /* just a  guess... */
486
487         modest_text_utils_convert_buffer_to_html_start (html, data, n);
488
489         if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
490                 hyperlinkify_plain_text (html);
491
492         modest_text_utils_convert_buffer_to_html_finish (html);
493         
494         return g_string_free (html, FALSE);
495 }
496
497 void
498 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
499 {
500         gchar *current, *start, *last_blank;
501         gint start_offset = 0, current_offset = 0;
502
503         g_return_if_fail (start_indexes != NULL);
504         g_return_if_fail (end_indexes != NULL);
505
506         start = (gchar *) addresses;
507         current = start;
508         last_blank = start;
509
510         while (*current != '\0') {
511                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
512                         start = g_utf8_next_char (start);
513                         start_offset++;
514                         last_blank = current;
515                 } else if ((*current == ',')||(*current == ';')) {
516                         gint *start_index, *end_index;
517                         start_index = g_new0(gint, 1);
518                         end_index = g_new0(gint, 1);
519                         *start_index = start_offset;
520                         *end_index = current_offset;
521                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
522                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
523                         start = g_utf8_next_char (current);
524                         start_offset = current_offset + 1;
525                         last_blank = start;
526                 } else if (*current == '"') {
527                         current = g_utf8_next_char (current);
528                         current_offset ++;
529                         while ((*current != '"')&&(*current != '\0')) {
530                                 current = g_utf8_next_char (current);
531                                 current_offset ++;
532                         }
533                 }
534                                 
535                 current = g_utf8_next_char (current);
536                 current_offset ++;
537         }
538
539         if (start != current) {
540                         gint *start_index, *end_index;
541                         start_index = g_new0(gint, 1);
542                         end_index = g_new0(gint, 1);
543                         *start_index = start_offset;
544                         *end_index = current_offset;
545                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
546                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
547         }
548         
549         *start_indexes = g_slist_reverse (*start_indexes);
550         *end_indexes = g_slist_reverse (*end_indexes);
551
552         return;
553 }
554
555 #if 0
556 GSList *
557 modest_text_utils_split_addresses_list (const gchar *addresses)
558 {
559         gchar *current, *start, *last_blank;
560         GSList *result = NULL;
561
562         start = (gchar *) addresses;
563         current = start;
564         last_blank = start;
565
566         while (*current != '\0') {
567                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
568                         start = g_utf8_next_char (start);
569                         last_blank = current;
570                 } else if ((*current == ',')||(*current == ';')) {
571                         gchar *new_address = NULL;
572                         new_address = g_strndup (start, current - last_blank);
573                         result = g_slist_prepend (result, new_address);
574                         start = g_utf8_next_char (current);
575                         last_blank = start;
576                 } else if (*current == '\"') {
577                         if (current == start) {
578                                 current = g_utf8_next_char (current);
579                                 start = g_utf8_next_char (start);
580                         }
581                         while ((*current != '\"')&&(*current != '\0'))
582                                 current = g_utf8_next_char (current);
583                 }
584                                 
585                 current = g_utf8_next_char (current);
586         }
587
588         if (start != current) {
589                 gchar *new_address = NULL;
590                 new_address = g_strndup (start, current - last_blank);
591                 result = g_slist_prepend (result, new_address);
592         }
593
594         result = g_slist_reverse (result);
595         return result;
596
597 }
598 #endif
599
600
601
602
603 GSList *
604 modest_text_utils_split_addresses_list (const gchar *addresses)
605 {
606         GSList *head;
607         const gchar *my_addrs = addresses;
608         const gchar *end;
609         gchar *addr;
610         
611         /* skip any space, ',', ';' at the start */
612         while (my_addrs && (my_addrs[0] == ' ' || my_addrs[0] == ',' || my_addrs[0] == ';'))
613                ++my_addrs;
614
615         /* are we at the end of addresses list? */
616         if (!my_addrs[0])
617                 return NULL;
618         
619         /* nope, we are at the start of some address
620          * now, let's find the end of the address */
621         end = my_addrs + 1;
622         while (end[0] && end[0] != ',' && end[0] != ';')
623                 ++end;
624
625         /* we got the address; copy it and remove trailing whitespace */
626         addr = g_strndup (my_addrs, end - my_addrs);
627         g_strchomp (addr);
628
629         head = g_slist_append (NULL, addr);
630         head->next = modest_text_utils_split_addresses_list (end); /* recurse */
631
632         return head;
633 }
634
635
636 void
637 modest_text_utils_address_range_at_position (const gchar *recipients_list,
638                                              guint position,
639                                              guint *start,
640                                              guint *end)
641 {
642         gchar *current = NULL;
643         gint range_start = 0;
644         gint range_end = 0;
645         gint index;
646         gboolean is_quoted = FALSE;
647
648         g_return_if_fail (recipients_list);
649         g_return_if_fail (position < g_utf8_strlen(recipients_list, -1));
650                 
651         index = 0;
652         for (current = (gchar *) recipients_list; *current != '\0';
653              current = g_utf8_find_next_char (current, NULL)) {
654                 gunichar c = g_utf8_get_char (current);
655
656                 if ((c == ',') && (!is_quoted)) {
657                         if (index < position) {
658                                 range_start = index + 1;
659                         } else {
660                                 break;
661                         }
662                 } else if (c == '\"') {
663                         is_quoted = !is_quoted;
664                 } else if ((c == ' ') &&(range_start == index)) {
665                         range_start ++;
666                 }
667                 index ++;
668                 range_end = index;
669         }
670
671         if (start)
672                 *start = range_start;
673         if (end)
674                 *end = range_end;
675 }
676
677
678 /* ******************************************************************* */
679 /* ************************* UTILIY FUNCTIONS ************************ */
680 /* ******************************************************************* */
681
682 static GString *
683 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
684 {
685         GString *gs;
686         const gchar *i0;
687         
688         if (iter > b + blen)
689                 return g_string_new("");
690         
691         i0 = iter;
692         while (iter[0]) {
693                 if (iter[0] == '\n')
694                         break;
695                 iter++;
696         }
697         gs = g_string_new_len (i0, iter - i0);
698         return gs;
699 }
700 static int
701 get_indent_level (const char *l)
702 {
703         int indent = 0;
704
705         while (l[0]) {
706                 if (l[0] == '>') {
707                         indent++;
708                         if (l[1] == ' ') {
709                                 l++;
710                         }
711                 } else {
712                         break;
713                 }
714                 l++;
715
716         }
717
718         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
719          *      stops reformatting.
720          */
721         if (strcmp (l, "-- ") == 0) {
722                 return -1 - indent;
723         } else {
724                 return indent;
725         }
726 }
727
728 static void
729 unquote_line (GString * l)
730 {
731         gchar *p;
732
733         p = l->str;
734         while (p[0]) {
735                 if (p[0] == '>') {
736                         if (p[1] == ' ') {
737                                 p++;
738                         }
739                 } else {
740                         break;
741                 }
742                 p++;
743         }
744         g_string_erase (l, 0, p - l->str);
745 }
746
747 static void
748 append_quoted (GString * buf, int indent, const GString * str,
749                const int cutpoint)
750 {
751         int i;
752
753         indent = indent < 0 ? abs (indent) - 1 : indent;
754         for (i = 0; i <= indent; i++) {
755                 g_string_append (buf, "> ");
756         }
757         if (cutpoint > 0) {
758                 g_string_append_len (buf, str->str, cutpoint);
759         } else {
760                 g_string_append (buf, str->str);
761         }
762         g_string_append (buf, "\n");
763 }
764
765 static int
766 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
767 {
768         gint index = 0;
769         const gchar *pos, *last;
770         gunichar *uni;
771
772         indent = indent < 0 ? abs (indent) - 1 : indent;
773
774         last = NULL;
775         pos = s;
776         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
777         while (pos[0]) {
778                 if ((index + 2 * indent > limit) && last) {
779                         g_free (uni);
780                         return last - s;
781                 }
782                 if (g_unichar_isspace (uni[index])) {
783                         last = pos;
784                 }
785                 pos = g_utf8_next_char (pos);
786                 index++;
787         }
788         g_free (uni);
789         return strlen (s);
790 }
791
792 static int
793 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
794 {
795         gint i, last;
796
797         last = strlen (s);
798         if (last + 2 * indent < limit)
799                 return last;
800
801         for (i = strlen (s); i > 0; i--) {
802                 if (s[i] == ' ') {
803                         if (i + 2 * indent <= limit) {
804                                 return i;
805                         } else {
806                                 last = i;
807                         }
808                 }
809         }
810         return last;
811 }
812
813 static int
814 get_breakpoint (const gchar * s, const gint indent, const gint limit)
815 {
816
817         if (g_utf8_validate (s, -1, NULL)) {
818                 return get_breakpoint_utf8 (s, indent, limit);
819         } else {                /* assume ASCII */
820                 //g_warning("invalid UTF-8 in msg");
821                 return get_breakpoint_ascii (s, indent, limit);
822         }
823 }
824
825 static gchar *
826 cite (const time_t sent_date, const gchar *from)
827 {
828         return g_strdup (_("mcen_ia_editor_original_message"));
829 }
830
831 static gchar *
832 quoted_attachments (GList *attachments)
833 {
834         GList *node = NULL;
835         GString *result = g_string_new ("");
836         for (node = attachments; node != NULL; node = g_list_next (node)) {
837                 gchar *filename = (gchar *) node->data;
838                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
839         }
840
841         return g_string_free (result, FALSE);
842
843 }
844
845 static gchar *
846 modest_text_utils_quote_plain_text (const gchar *text, 
847                                     const gchar *cite, 
848                                     const gchar *signature,
849                                     GList *attachments,
850                                     int limit)
851 {
852         const gchar *iter;
853         gint indent, breakpoint, rem_indent = 0;
854         GString *q, *l, *remaining;
855         gsize len;
856         gchar *attachments_string = NULL;
857
858         /* remaining will store the rest of the line if we have to break it */
859         q = g_string_new ("\n");
860         q = g_string_append (q, cite);
861         q = g_string_append_c (q, '\n');
862         remaining = g_string_new ("");
863
864         iter = text;
865         len = strlen(text);
866         do {
867                 l = get_next_line (text, len, iter);
868                 iter = iter + l->len + 1;
869                 indent = get_indent_level (l->str);
870                 unquote_line (l);
871
872                 if (remaining->len) {
873                         if (l->len && indent == rem_indent) {
874                                 g_string_prepend (l, " ");
875                                 g_string_prepend (l, remaining->str);
876                         } else {
877                                 do {
878                                         breakpoint =
879                                                 get_breakpoint (remaining->str,
880                                                                 rem_indent,
881                                                                 limit);
882                                         append_quoted (q, rem_indent,
883                                                        remaining, breakpoint);
884                                         g_string_erase (remaining, 0,
885                                                         breakpoint);
886                                         if (remaining->str[0] == ' ') {
887                                                 g_string_erase (remaining, 0,
888                                                                 1);
889                                         }
890                                 } while (remaining->len);
891                         }
892                 }
893                 g_string_free (remaining, TRUE);
894                 breakpoint = get_breakpoint (l->str, indent, limit);
895                 remaining = g_string_new (l->str + breakpoint);
896                 if (remaining->str[0] == ' ') {
897                         g_string_erase (remaining, 0, 1);
898                 }
899                 rem_indent = indent;
900                 append_quoted (q, indent, l, breakpoint);
901                 g_string_free (l, TRUE);
902         } while ((iter < text + len) || (remaining->str[0]));
903
904         attachments_string = quoted_attachments (attachments);
905         q = g_string_append (q, attachments_string);
906         g_free (attachments_string);
907
908         if (signature != NULL) {
909                 q = g_string_append_c (q, '\n');
910                 q = g_string_append (q, signature);
911         }
912
913         return g_string_free (q, FALSE);
914 }
915
916 static gchar*
917 modest_text_utils_quote_html (const gchar *text, 
918                               const gchar *cite, 
919                               const gchar *signature,
920                               GList *attachments,
921                               int limit)
922 {
923         gchar *result = NULL;
924         gchar *signature_result = NULL;
925         const gchar *format = \
926                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
927                 "<html>\n" \
928                 "<body>\n" \
929                 "<br/>%s<br/>" \
930                 "<pre>%s<br/>%s<br/>%s</pre>\n" \
931                 "</body>\n" \
932                 "</html>\n";
933         gchar *attachments_string = NULL;
934         gchar *q_attachments_string = NULL;
935         gchar *q_cite = NULL;
936         gchar *html_text = NULL;
937
938         if (signature == NULL)
939                 signature_result = g_strdup ("");
940         else
941                 signature_result = modest_text_utils_convert_to_html_body (signature, -1, TRUE);
942
943         attachments_string = quoted_attachments (attachments);
944         q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string, -1, TRUE);
945         q_cite = modest_text_utils_convert_to_html_body (cite, -1, TRUE);
946         html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
947         result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
948         g_free (q_cite);
949         g_free (html_text);
950         g_free (attachments_string);
951         g_free (q_attachments_string);
952         g_free (signature_result);
953         
954         return result;
955 }
956
957 static gint 
958 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
959 {
960         return match2->offset - match1->offset;
961 }
962
963 static gboolean url_matches_block = 0;
964 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
965
966
967 static gboolean
968 compile_patterns ()
969 {
970         guint i;
971         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
972         for (i = 0; i != pattern_num; ++i) {
973                 patterns[i].preg = g_slice_new0 (regex_t);
974                 
975                 /* this should not happen */
976                 if (regcomp (patterns[i].preg, patterns[i].regex,
977                              REG_ICASE|REG_EXTENDED|REG_NEWLINE) != 0) {
978                         g_warning ("%s: error in regexp:\n%s\n", __FUNCTION__, patterns[i].regex);
979                         return FALSE;
980                 }
981         }
982         return TRUE;
983 }
984
985 static void 
986 free_patterns ()
987 {
988         guint i;
989         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
990         for (i = 0; i != pattern_num; ++i) {
991                 regfree (patterns[i].preg);
992                 g_slice_free  (regex_t, patterns[i].preg);
993         } /* don't free patterns itself -- it's static */
994 }
995
996 void
997 modest_text_utils_hyperlinkify_begin (void)
998 {
999         if (url_matches_block == 0)
1000                 compile_patterns ();
1001         url_matches_block ++;
1002 }
1003
1004 void
1005 modest_text_utils_hyperlinkify_end (void)
1006 {
1007         url_matches_block--;
1008         if (url_matches_block <= 0)
1009                 free_patterns ();
1010 }
1011
1012
1013 static GSList*
1014 get_url_matches (GString *txt)
1015 {
1016         regmatch_t rm;
1017         guint rv, i, offset = 0;
1018         GSList *match_list = NULL;
1019
1020         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1021
1022         /* initalize the regexps */
1023         modest_text_utils_hyperlinkify_begin ();
1024
1025         /* find all the matches */
1026         for (i = 0; i != pattern_num; ++i) {
1027                 offset     = 0; 
1028                 while (1) {
1029                         url_match_t *match;
1030                         gboolean is_submatch;
1031                         GSList *cursor;
1032                         
1033                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
1034                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
1035                                 break; /* try next regexp */ 
1036                         }
1037                         if (rm.rm_so == -1)
1038                                 break;
1039                         
1040                         is_submatch = FALSE;
1041                         /* check  old matches to see if this has already been matched */
1042                         cursor = match_list;
1043                         while (cursor && !is_submatch) {
1044                                 const url_match_t *old_match =
1045                                         (const url_match_t *) cursor->data;
1046                                 guint new_offset = offset + rm.rm_so;
1047                                 is_submatch = (new_offset >  old_match->offset &&
1048                                                new_offset <  old_match->offset + old_match->len);
1049                                 cursor = g_slist_next (cursor);
1050                         }
1051
1052                         if (!is_submatch) {
1053                                 /* make a list of our matches (<offset, len, prefix> tupels)*/
1054                                 match = g_slice_new (url_match_t);
1055                                 match->offset = offset + rm.rm_so;
1056                                 match->len    = rm.rm_eo - rm.rm_so;
1057                                 match->prefix = patterns[i].prefix;
1058                                 match_list = g_slist_prepend (match_list, match);
1059                         }               
1060                         offset += rm.rm_eo;
1061                 }
1062         }
1063
1064         modest_text_utils_hyperlinkify_end ();
1065         
1066         /* now sort the list, so the matches are in reverse order of occurence.
1067          * that way, we can do the replacements starting from the end, so we don't need
1068          * to recalculate the offsets
1069          */
1070         match_list = g_slist_sort (match_list,
1071                                    (GCompareFunc)cmp_offsets_reverse); 
1072         return match_list;      
1073 }
1074
1075
1076
1077 /* replace all occurences of needle in haystack with repl*/
1078 static gchar*
1079 replace_string (const gchar *haystack, const gchar *needle, gchar repl)
1080 {
1081         gchar *str, *cursor;
1082
1083         if (!haystack || !needle || strlen(needle) == 0)
1084                 return haystack ? g_strdup(haystack) : NULL;
1085         
1086         str = g_strdup (haystack);
1087
1088         for (cursor = str; cursor && *cursor; ++cursor) {
1089                 if (g_str_has_prefix (cursor, needle)) {
1090                         cursor[0] = repl;
1091                         memmove (cursor + 1,
1092                                  cursor + strlen (needle),
1093                                  strlen (cursor + strlen (needle)) + 1);
1094                 }
1095         }
1096         
1097         return str;
1098 }
1099
1100 static void
1101 hyperlinkify_plain_text (GString *txt)
1102 {
1103         GSList *cursor;
1104         GSList *match_list = get_url_matches (txt);
1105
1106         /* we will work backwards, so the offsets stay valid */
1107         for (cursor = match_list; cursor; cursor = cursor->next) {
1108
1109                 url_match_t *match = (url_match_t*) cursor->data;
1110                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
1111                 gchar *repl = NULL; /* replacement  */
1112
1113                 /* the string still contains $(MARK_AMP_STR)"amp;" for each
1114                  * '&' in the original, because of the text->html conversion.
1115                  * in the href-URL (and only there), we must convert that back to
1116                  * '&'
1117                  */
1118                 gchar *href_url = replace_string (url, MARK_AMP_STR "amp;", '&');
1119                 
1120                 /* the prefix is NULL: use the one that is already there */
1121                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1122                                         match->prefix ? match->prefix : EMPTY_STRING, 
1123                                         href_url, url);
1124
1125                 /* replace the old thing with our hyperlink
1126                  * replacement thing */
1127                 g_string_erase  (txt, match->offset, match->len);
1128                 g_string_insert (txt, match->offset, repl);
1129                 
1130                 g_free (url);
1131                 g_free (repl);
1132                 g_free (href_url);
1133
1134                 g_slice_free (url_match_t, match);      
1135         }
1136         
1137         g_slist_free (match_list);
1138 }
1139
1140
1141 /* for optimization reasons, we change the string in-place */
1142 void
1143 modest_text_utils_get_display_address (gchar *address)
1144 {
1145         int i;
1146
1147         g_return_if_fail (address);
1148         
1149         if (!address)
1150                 return;
1151         
1152         /* should not be needed, and otherwise, we probably won't screw up the address
1153          * more than it already is :) 
1154          * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1155          * */
1156         
1157         /* remove leading whitespace */
1158         if (address[0] == ' ')
1159                 g_strchug (address);
1160                 
1161         for (i = 0; address[i]; ++i) {
1162                 if (address[i] == '<') {
1163                         if (G_UNLIKELY(i == 0))
1164                                 return; /* there's nothing else, leave it */
1165                         else {
1166                                 address[i] = '\0'; /* terminate the string here */
1167                                 return;
1168                         }
1169                 }
1170         }
1171 }
1172
1173
1174
1175
1176
1177 gchar *
1178 modest_text_utils_get_email_address (const gchar *full_address)
1179 {
1180         const gchar *left, *right;
1181
1182         g_return_val_if_fail (full_address, NULL);
1183         
1184         if (!full_address)
1185                 return NULL;
1186         
1187         g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1188         
1189         left = g_strrstr_len (full_address, strlen(full_address), "<");
1190         if (left == NULL)
1191                 return g_strdup (full_address);
1192
1193         right = g_strstr_len (left, strlen(left), ">");
1194         if (right == NULL)
1195                 return g_strdup (full_address);
1196
1197         return g_strndup (left + 1, right - left - 1);
1198 }
1199
1200 gint 
1201 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1202 {
1203         gint prefix_len = 0;    
1204
1205         g_return_val_if_fail (sub, 0);
1206
1207         if (!sub)
1208                 return 0;
1209         
1210         /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1211         if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1212                 return 0;
1213         else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1214                 return 0;
1215
1216         prefix_len = 2;
1217         if (sub[2] == 'd')
1218                 ++prefix_len;
1219
1220         /* skip over a [...] block */
1221         if (sub[prefix_len] == '[') {
1222                 int c = prefix_len + 1;
1223                 while (sub[c] && sub[c] != ']')
1224                         ++c;
1225                 if (sub[c])
1226                         return 0; /* no end to the ']' found */
1227                 else
1228                         prefix_len = c + 1;
1229         }
1230
1231         /* did we find the ':' ? */
1232         if (sub[prefix_len] == ':') {
1233                 ++prefix_len;
1234                 if (sub[prefix_len] == ' ')
1235                         ++prefix_len;
1236                 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1237 /*              g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1238                 return prefix_len;
1239         } else
1240                 return 0;
1241 }
1242
1243
1244 gint
1245 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1246 {
1247
1248 /* work even when s1 and/or s2 == NULL */
1249         if (G_UNLIKELY(s1 == s2))
1250                 return 0;
1251         if (G_UNLIKELY(!s1))
1252                 return -1;
1253         if (G_UNLIKELY(!s2))
1254                 return 1;
1255         
1256         /* if it's not case sensitive */
1257         if (!insensitive) {
1258
1259                 /* optimization: short cut if first char is ascii */ 
1260                 if (((s1[0] & 0xf0)== 0) && ((s2[0] & 0xf0) == 0)) 
1261                         return s1[0] - s2[0];
1262                 
1263                 return g_utf8_collate (s1, s2);
1264
1265         } else {
1266                 gint result;
1267                 gchar *n1, *n2;
1268
1269                 /* optimization: short cut iif first char is ascii */ 
1270                 if (((s1[0] & 0xf0) == 0) && ((s2[0] & 0xf0) == 0)) 
1271                         return tolower(s1[0]) - tolower(s2[0]);
1272                 
1273                 n1 = g_utf8_strdown (s1, -1);
1274                 n2 = g_utf8_strdown (s2, -1);
1275                 
1276                 result = g_utf8_collate (n1, n2);
1277                 
1278                 g_free (n1);
1279                 g_free (n2);
1280         
1281                 return result;
1282         }
1283 }
1284
1285
1286 const gchar*
1287 modest_text_utils_get_display_date (time_t date)
1288 {
1289 #define DATE_BUF_SIZE 64 
1290         static gchar date_buf[DATE_BUF_SIZE];
1291         
1292         /* calculate the # of days since epoch for 
1293          * for today and for the date provided 
1294          * based on idea from pvanhoof */
1295         int day      = time(NULL) / (24 * 60 * 60);
1296         int date_day = date       / (24 * 60 * 60);
1297
1298         /* if it's today, show the time, if it's not today, show the date instead */
1299
1300         if (day == date_day) /* is the date today? */
1301                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%X", date);
1302         else 
1303                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%x", date); 
1304
1305         return date_buf; /* this is a static buffer, don't free! */
1306 }
1307
1308
1309
1310 gboolean
1311 modest_text_utils_validate_folder_name (const gchar *folder_name)
1312 {
1313         /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1314          * with some extras */
1315         
1316         guint len;
1317         gint i;
1318         const gchar **cursor = NULL;
1319         const gchar *forbidden_names[] = { /* windows does not like these */
1320                 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
1321                 "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1322                 ".", "..", NULL
1323         };
1324         
1325         /* cannot be NULL */
1326         if (!folder_name) 
1327                 return FALSE;
1328
1329         /* cannot be empty */
1330         len = strlen(folder_name);
1331         if (len == 0)
1332                 return FALSE;
1333         
1334         /* cannot start or end with a space */
1335         if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1336                 return FALSE; 
1337
1338         /* cannot contain a forbidden char */   
1339         for (i = 0; i < len; i++)
1340                 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1341                         return FALSE;
1342         
1343         /* cannot contain a forbidden word */
1344         if (len <= 4) {
1345                 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1346                         if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1347                                 return FALSE;
1348                 }
1349         }
1350
1351         return TRUE; /* it's valid! */
1352 }
1353
1354
1355
1356 gboolean
1357 modest_text_utils_validate_domain_name (const gchar *domain)
1358 {
1359         gboolean valid = FALSE;
1360         regex_t rx;
1361         const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1362
1363         g_return_val_if_fail (domain, FALSE);
1364         
1365         if (!domain)
1366                 return FALSE;
1367         
1368         memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1369                 
1370         /* domain name: all alphanum or '-' or '.',
1371          * but beginning/ending in alphanum */  
1372         if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1373                 g_warning ("BUG: error in regexp");
1374                 return FALSE;
1375         }
1376         
1377         valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1378         regfree (&rx);
1379                 
1380         return valid;
1381 }
1382
1383
1384
1385 gboolean
1386 modest_text_utils_validate_email_address (const gchar *email_address,
1387                                           const gchar **invalid_char_position)
1388 {
1389         int count = 0;
1390         const gchar *c = NULL, *domain = NULL;
1391         static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1392         
1393         if (invalid_char_position)
1394                 *invalid_char_position = NULL;
1395         
1396         g_return_val_if_fail (email_address, FALSE);
1397         
1398         /* check that the email adress contains exactly one @ */
1399         if (!strstr(email_address, "@") || 
1400                         (strstr(email_address, "@") != g_strrstr(email_address, "@"))) 
1401                 return FALSE;
1402         
1403         /* first we validate the name portion (name@domain) */
1404         for (c = email_address;  *c;  c++) {
1405                 if (*c == '\"' && 
1406                     (c == email_address || 
1407                      *(c - 1) == '.' || 
1408                      *(c - 1) == '\"')) {
1409                         while (*++c) {
1410                                 if (*c == '\"') 
1411                                         break;
1412                                 if (*c == '\\' && (*++c == ' ')) 
1413                                         continue;
1414                                 if (*c <= ' ' || *c >= 127) 
1415                                         return FALSE;
1416                         }
1417                         if (!*c++) 
1418                                 return FALSE;
1419                         if (*c == '@') 
1420                                 break;
1421                         if (*c != '.') 
1422                                 return FALSE;
1423                         continue;
1424                 }
1425                 if (*c == '@') 
1426                         break;
1427                 if (*c <= ' ' || *c >= 127) 
1428                         return FALSE;
1429                 if (strchr(rfc822_specials, *c)) {
1430                         if (invalid_char_position)
1431                                 *invalid_char_position = c;
1432                         return FALSE;
1433                 }
1434         }
1435         if (c == email_address || *(c - 1) == '.') 
1436                 return FALSE;
1437
1438         /* next we validate the domain portion (name@domain) */
1439         if (!*(domain = ++c)) 
1440                 return FALSE;
1441         do {
1442                 if (*c == '.') {
1443                         if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0') 
1444                                 return FALSE;
1445                         count++;
1446                 }
1447                 if (*c <= ' ' || *c >= 127) 
1448                         return FALSE;
1449                 if (strchr(rfc822_specials, *c)) {
1450                         if (invalid_char_position)
1451                                 *invalid_char_position = c;
1452                         return FALSE;
1453                 }
1454         } while (*++c);
1455
1456         return (count >= 1) ? TRUE : FALSE;
1457 }
1458
1459 gboolean 
1460 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1461 {
1462         gchar *stripped, *current;
1463         gchar *right_part;
1464         gboolean has_error = FALSE;
1465
1466         if (invalid_char_position)
1467                 *invalid_char_position = NULL;
1468         
1469         g_return_val_if_fail (recipient, FALSE);
1470         
1471         if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1472                 return TRUE;
1473
1474         stripped = g_strdup (recipient);
1475         stripped = g_strstrip (stripped);
1476         current = stripped;
1477
1478         if (*current == '\0') {
1479                 g_free (stripped);
1480                 return FALSE;
1481         }
1482
1483         /* quoted string */
1484         if (*current == '\"') {
1485                 current = g_utf8_next_char (current);
1486                 has_error = TRUE;
1487                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1488                         if (*current == '\\') {
1489                                 /* TODO: This causes a warning, which breaks the build, 
1490                                  * because a gchar cannot be < 0.
1491                                  * murrayc. 
1492                                 if (current[1] <0) {
1493                                         has_error = TRUE;
1494                                         break;
1495                                 }
1496                                 */
1497                         } else if (*current == '\"') {
1498                                 has_error = FALSE;
1499                                 current = g_utf8_next_char (current);
1500                                 break;
1501                         }
1502                 }
1503         } else {
1504                 has_error = TRUE;
1505                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1506                         if (*current == '<') {
1507                                 has_error = FALSE;
1508                                 break;
1509                         }
1510                 }
1511         }
1512                 
1513         if (has_error) {
1514                 g_free (stripped);
1515                 return FALSE;
1516         }
1517
1518         right_part = g_strdup (current);
1519         g_free (stripped);
1520         right_part = g_strstrip (right_part);
1521
1522         if (g_str_has_prefix (right_part, "<") &&
1523             g_str_has_suffix (right_part, ">")) {
1524                 gchar *address;
1525                 gboolean valid;
1526
1527                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1528                 g_free (right_part);
1529                 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1530                 g_free (address);
1531                 return valid;
1532         } else {
1533                 g_free (right_part);
1534                 return FALSE;
1535         }
1536 }
1537
1538
1539 gchar *
1540 modest_text_utils_get_display_size (guint64 size)
1541 {
1542         const guint KB=1024;
1543         const guint MB=1024 * KB;
1544         const guint GB=1024 * MB;
1545
1546         if (size == 0)
1547                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1548         if (0 < size && size < KB)
1549                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1550         else if (KB <= size && size < 100 * KB)
1551                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1552         else if (100*KB <= size && size < MB)
1553                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1554         else if (MB <= size && size < 10*MB)
1555                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1556         else if (10*MB <= size && size < GB)
1557                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1558         else
1559                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1560 }
1561
1562 static gchar *
1563 get_email_from_address (const gchar * address)
1564 {
1565         gchar *left_limit, *right_limit;
1566
1567         left_limit = strstr (address, "<");
1568         right_limit = g_strrstr (address, ">");
1569
1570         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1571                 return g_strdup (address);
1572         else
1573                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1574 }
1575
1576 gchar *      
1577 modest_text_utils_get_color_string (GdkColor *color)
1578 {
1579         g_return_val_if_fail (color, NULL);
1580         
1581         return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1582                                 (color->red >> 12)   & 0xf, (color->red >> 8)   & 0xf,
1583                                 (color->red >>  4)   & 0xf, (color->red)        & 0xf,
1584                                 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1585                                 (color->green >>  4) & 0xf, (color->green)      & 0xf,
1586                                 (color->blue >> 12)  & 0xf, (color->blue >> 8)  & 0xf,
1587                                 (color->blue >>  4)  & 0xf, (color->blue)       & 0xf);
1588 }
1589
1590 gchar *
1591 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1592 {
1593         GtkTextIter start, end;
1594         gchar *slice, *current;
1595         GString *result = g_string_new ("");
1596
1597         g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1598         
1599         gtk_text_buffer_get_start_iter (buffer, &start);
1600         gtk_text_buffer_get_end_iter (buffer, &end);
1601
1602         slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1603         current = slice;
1604
1605         while (current && current != '\0') {
1606                 if (g_utf8_get_char (current) == 0xFFFC) {
1607                         result = g_string_append_c (result, ' ');
1608                         current = g_utf8_next_char (current);
1609                 } else {
1610                         gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1611                         if (next == NULL) {
1612                                 result = g_string_append (result, current);
1613                         } else {
1614                                 result = g_string_append_len (result, current, next - current);
1615                         }
1616                         current = next;
1617                 }
1618         }
1619         g_free (slice);
1620
1621         return g_string_free (result, FALSE);
1622         
1623 }
1624
1625 gboolean
1626 modest_text_utils_is_forbidden_char (const gchar character,
1627                                      ModestTextUtilsForbiddenCharType type)
1628 {
1629         gint i, len;
1630         const gchar *forbidden_chars = NULL;
1631         
1632         /* We need to get the length in the switch because the
1633            compiler needs to know the size at compile time */
1634         switch (type) {
1635         case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1636                 forbidden_chars = account_title_forbidden_chars;
1637                 len = G_N_ELEMENTS (account_title_forbidden_chars);
1638                 break;
1639         case FOLDER_NAME_FORBIDDEN_CHARS:
1640                 forbidden_chars = folder_name_forbidden_chars;
1641                 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1642                 break;
1643         case USER_NAME_FORBIDDEN_NAMES:
1644                 forbidden_chars = user_name_forbidden_chars;
1645                 len = G_N_ELEMENTS (user_name_forbidden_chars);
1646                 break;
1647         default:
1648                 g_return_val_if_reached (TRUE);
1649         }
1650
1651         for (i = 0; i < len ; i++)
1652                 if (forbidden_chars[i] == character)
1653                         return TRUE;
1654
1655         return FALSE; /* it's valid! */
1656 }