f6f6efbe485408227cc620bb5756d4291085cc39
[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 /*
78  * we need these regexps to find URLs in plain text e-mails
79  */
80 typedef struct _url_match_pattern_t url_match_pattern_t;
81 struct _url_match_pattern_t {
82         gchar   *regex;
83         regex_t *preg;
84         gchar   *prefix;
85 };
86
87 typedef struct _url_match_t url_match_t;
88 struct _url_match_t {
89         guint offset;
90         guint len;
91         const gchar* prefix;
92 };
93
94 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
95         { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
96           NULL, NULL },\
97         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
98                         NULL, "http://" },                              \
99         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
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 static void
334 modest_text_utils_convert_buffer_to_html_start (GString *html, const gchar *data, gssize n)
335 {
336         guint            i;
337         gboolean        space_seen = FALSE;
338         guint           break_dist = 0; /* distance since last break point */
339
340         if (n == -1)
341                 n = strlen (data);
342
343         /* replace with special html chars where needed*/
344         for (i = 0; i != n; ++i)  {
345                 char kar = data[i];
346                 
347                 if (space_seen && kar != ' ') {
348                         g_string_append_c (html, ' ');
349                         space_seen = FALSE;
350                 }
351                 
352                 /* we artificially insert a breakpoint (newline)
353                  * after 256, to make sure our lines are not so long
354                  * they will DOS the regexping later
355                  */
356                 if (++break_dist == 256) {
357                         g_string_append_c (html, '\n');
358                         break_dist = 0;
359                 }
360                 
361                 switch (kar) {
362                 case 0:
363                 case MARK_AMP: /* this is a temp place holder for '&'; we can only
364                                 * set the real '&' after hyperlink translation, otherwise
365                                 * we might screw that up */
366                         break; /* ignore embedded \0s and MARK_AMP */   
367                 case '<'  : g_string_append (html, MARK_AMP_STR "lt;");   break;
368                 case '>'  : g_string_append (html, MARK_AMP_STR "gt;");   break;
369                 case '&'  : g_string_append (html, MARK_AMP_STR "amp;");  break;
370                 case '"'  : g_string_append (html, MARK_AMP_STR "quot;");  break;
371
372                 /* don't convert &apos; --> wpeditor will try to re-convert it... */    
373                 //case '\'' : g_string_append (html, "&apos;"); break;
374                 case '\n' : g_string_append (html, "<br>\n");break_dist= 0; break;
375                 case '\t' : g_string_append (html, MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp; ");
376                         break_dist=0; break; /* note the space at the end*/
377                 case ' ':
378                         break_dist = 0;
379                         if (space_seen) { /* second space in a row */
380                                 g_string_append (html, "&nbsp; ");
381                                 space_seen = FALSE;
382                         } else
383                                 space_seen = TRUE;
384                         break;
385                 default:
386                         g_string_append_c (html, kar);
387                 }
388         }
389 }
390
391
392 static void
393 modest_text_utils_convert_buffer_to_html_finish (GString *html)
394 {
395         int i;
396         /* replace all our MARK_AMPs with real ones */
397         for (i = 0; i != html->len; ++i)
398                 if ((html->str)[i] == MARK_AMP)
399                         (html->str)[i] = '&';
400 }
401
402
403 gchar*
404 modest_text_utils_convert_to_html (const gchar *data)
405 {
406         GString         *html;      
407         gsize           len;
408
409         g_return_val_if_fail (data, NULL);
410         
411         if (!data)
412                 return NULL;
413
414         len = strlen (data);
415         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
416
417         g_string_append_printf (html,
418                                 "<html><head>"
419                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
420                                 "</head>"
421                                 "<body>");
422
423         modest_text_utils_convert_buffer_to_html_start (html, data, -1);
424         
425         g_string_append (html, "</body></html>");
426
427         if (len <= HYPERLINKIFY_MAX_LENGTH)
428                 hyperlinkify_plain_text (html);
429
430         modest_text_utils_convert_buffer_to_html_finish (html);
431         
432         return g_string_free (html, FALSE);
433 }
434
435 gchar *
436 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
437 {
438         GString         *html;      
439
440         g_return_val_if_fail (data, NULL);
441
442         if (!data)
443                 return NULL;
444
445         if (n == -1) 
446                 n = strlen (data);
447         html = g_string_sized_new (1.5 * n);    /* just a  guess... */
448
449         modest_text_utils_convert_buffer_to_html_start (html, data, n);
450
451         if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
452                 hyperlinkify_plain_text (html);
453
454         modest_text_utils_convert_buffer_to_html_finish (html);
455         
456         return g_string_free (html, FALSE);
457 }
458
459 void
460 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
461 {
462         gchar *current, *start, *last_blank;
463         gint start_offset = 0, current_offset = 0;
464
465         g_return_if_fail (start_indexes != NULL);
466         g_return_if_fail (end_indexes != NULL);
467
468         start = (gchar *) addresses;
469         current = start;
470         last_blank = start;
471
472         while (*current != '\0') {
473                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
474                         start = g_utf8_next_char (start);
475                         start_offset++;
476                         last_blank = current;
477                 } else if ((*current == ',')||(*current == ';')) {
478                         gint *start_index, *end_index;
479                         start_index = g_new0(gint, 1);
480                         end_index = g_new0(gint, 1);
481                         *start_index = start_offset;
482                         *end_index = current_offset;
483                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
484                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
485                         start = g_utf8_next_char (current);
486                         start_offset = current_offset + 1;
487                         last_blank = start;
488                 } else if (*current == '"') {
489                         current = g_utf8_next_char (current);
490                         current_offset ++;
491                         while ((*current != '"')&&(*current != '\0')) {
492                                 current = g_utf8_next_char (current);
493                                 current_offset ++;
494                         }
495                 }
496                                 
497                 current = g_utf8_next_char (current);
498                 current_offset ++;
499         }
500
501         if (start != current) {
502                         gint *start_index, *end_index;
503                         start_index = g_new0(gint, 1);
504                         end_index = g_new0(gint, 1);
505                         *start_index = start_offset;
506                         *end_index = current_offset;
507                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
508                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
509         }
510         
511         *start_indexes = g_slist_reverse (*start_indexes);
512         *end_indexes = g_slist_reverse (*end_indexes);
513
514         return;
515 }
516
517 GSList *
518 modest_text_utils_split_addresses_list (const gchar *addresses)
519 {
520         gchar *current, *start, *last_blank;
521         GSList *result = NULL;
522
523         start = (gchar *) addresses;
524         current = start;
525         last_blank = start;
526
527         while (*current != '\0') {
528                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
529                         start = g_utf8_next_char (start);
530                         last_blank = current;
531                 } else if ((*current == ',')||(*current == ';')) {
532                         gchar *new_address = NULL;
533                         new_address = g_strndup (start, current - last_blank);
534                         result = g_slist_prepend (result, new_address);
535                         start = g_utf8_next_char (current);
536                         last_blank = start;
537                 } else if (*current == '\"') {
538                         if (current == start) {
539                                 current = g_utf8_next_char (current);
540                                 start = g_utf8_next_char (start);
541                         }
542                         while ((*current != '\"')&&(*current != '\0'))
543                                 current = g_utf8_next_char (current);
544                 }
545                                 
546                 current = g_utf8_next_char (current);
547         }
548
549         if (start != current) {
550                 gchar *new_address = NULL;
551                 new_address = g_strndup (start, current - last_blank);
552                 result = g_slist_prepend (result, new_address);
553         }
554
555         result = g_slist_reverse (result);
556         return result;
557
558 }
559
560 void
561 modest_text_utils_address_range_at_position (const gchar *recipients_list,
562                                              guint position,
563                                              guint *start,
564                                              guint *end)
565 {
566         gchar *current = NULL;
567         gint range_start = 0;
568         gint range_end = 0;
569         gint index;
570         gboolean is_quoted = FALSE;
571
572         g_return_if_fail (recipients_list);
573         g_return_if_fail (position < g_utf8_strlen(recipients_list, -1));
574                 
575         index = 0;
576         for (current = (gchar *) recipients_list; *current != '\0';
577              current = g_utf8_find_next_char (current, NULL)) {
578                 gunichar c = g_utf8_get_char (current);
579
580                 if ((c == ',') && (!is_quoted)) {
581                         if (index < position) {
582                                 range_start = index + 1;
583                         } else {
584                                 break;
585                         }
586                 } else if (c == '\"') {
587                         is_quoted = !is_quoted;
588                 } else if ((c == ' ') &&(range_start == index)) {
589                         range_start ++;
590                 }
591                 index ++;
592                 range_end = index;
593         }
594
595         if (start)
596                 *start = range_start;
597         if (end)
598                 *end = range_end;
599 }
600
601
602 /* ******************************************************************* */
603 /* ************************* UTILIY FUNCTIONS ************************ */
604 /* ******************************************************************* */
605
606 static GString *
607 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
608 {
609         GString *gs;
610         const gchar *i0;
611         
612         if (iter > b + blen)
613                 return g_string_new("");
614         
615         i0 = iter;
616         while (iter[0]) {
617                 if (iter[0] == '\n')
618                         break;
619                 iter++;
620         }
621         gs = g_string_new_len (i0, iter - i0);
622         return gs;
623 }
624 static int
625 get_indent_level (const char *l)
626 {
627         int indent = 0;
628
629         while (l[0]) {
630                 if (l[0] == '>') {
631                         indent++;
632                         if (l[1] == ' ') {
633                                 l++;
634                         }
635                 } else {
636                         break;
637                 }
638                 l++;
639
640         }
641
642         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
643          *      stops reformatting.
644          */
645         if (strcmp (l, "-- ") == 0) {
646                 return -1 - indent;
647         } else {
648                 return indent;
649         }
650 }
651
652 static void
653 unquote_line (GString * l)
654 {
655         gchar *p;
656
657         p = l->str;
658         while (p[0]) {
659                 if (p[0] == '>') {
660                         if (p[1] == ' ') {
661                                 p++;
662                         }
663                 } else {
664                         break;
665                 }
666                 p++;
667         }
668         g_string_erase (l, 0, p - l->str);
669 }
670
671 static void
672 append_quoted (GString * buf, int indent, const GString * str,
673                const int cutpoint)
674 {
675         int i;
676
677         indent = indent < 0 ? abs (indent) - 1 : indent;
678         for (i = 0; i <= indent; i++) {
679                 g_string_append (buf, "> ");
680         }
681         if (cutpoint > 0) {
682                 g_string_append_len (buf, str->str, cutpoint);
683         } else {
684                 g_string_append (buf, str->str);
685         }
686         g_string_append (buf, "\n");
687 }
688
689 static int
690 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
691 {
692         gint index = 0;
693         const gchar *pos, *last;
694         gunichar *uni;
695
696         indent = indent < 0 ? abs (indent) - 1 : indent;
697
698         last = NULL;
699         pos = s;
700         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
701         while (pos[0]) {
702                 if ((index + 2 * indent > limit) && last) {
703                         g_free (uni);
704                         return last - s;
705                 }
706                 if (g_unichar_isspace (uni[index])) {
707                         last = pos;
708                 }
709                 pos = g_utf8_next_char (pos);
710                 index++;
711         }
712         g_free (uni);
713         return strlen (s);
714 }
715
716 static int
717 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
718 {
719         gint i, last;
720
721         last = strlen (s);
722         if (last + 2 * indent < limit)
723                 return last;
724
725         for (i = strlen (s); i > 0; i--) {
726                 if (s[i] == ' ') {
727                         if (i + 2 * indent <= limit) {
728                                 return i;
729                         } else {
730                                 last = i;
731                         }
732                 }
733         }
734         return last;
735 }
736
737 static int
738 get_breakpoint (const gchar * s, const gint indent, const gint limit)
739 {
740
741         if (g_utf8_validate (s, -1, NULL)) {
742                 return get_breakpoint_utf8 (s, indent, limit);
743         } else {                /* assume ASCII */
744                 //g_warning("invalid UTF-8 in msg");
745                 return get_breakpoint_ascii (s, indent, limit);
746         }
747 }
748
749 static gchar *
750 cite (const time_t sent_date, const gchar *from)
751 {
752         return g_strdup (_("mcen_ia_editor_original_message"));
753 }
754
755 static gchar *
756 quoted_attachments (GList *attachments)
757 {
758         GList *node = NULL;
759         GString *result = g_string_new ("");
760         for (node = attachments; node != NULL; node = g_list_next (node)) {
761                 gchar *filename = (gchar *) node->data;
762                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
763         }
764
765         return g_string_free (result, FALSE);
766
767 }
768
769 static gchar *
770 modest_text_utils_quote_plain_text (const gchar *text, 
771                                     const gchar *cite, 
772                                     const gchar *signature,
773                                     GList *attachments,
774                                     int limit)
775 {
776         const gchar *iter;
777         gint indent, breakpoint, rem_indent = 0;
778         GString *q, *l, *remaining;
779         gsize len;
780         gchar *attachments_string = NULL;
781
782         /* remaining will store the rest of the line if we have to break it */
783         q = g_string_new ("\n");
784         q = g_string_append (q, cite);
785         q = g_string_append_c (q, '\n');
786         remaining = g_string_new ("");
787
788         iter = text;
789         len = strlen(text);
790         do {
791                 l = get_next_line (text, len, iter);
792                 iter = iter + l->len + 1;
793                 indent = get_indent_level (l->str);
794                 unquote_line (l);
795
796                 if (remaining->len) {
797                         if (l->len && indent == rem_indent) {
798                                 g_string_prepend (l, " ");
799                                 g_string_prepend (l, remaining->str);
800                         } else {
801                                 do {
802                                         breakpoint =
803                                                 get_breakpoint (remaining->str,
804                                                                 rem_indent,
805                                                                 limit);
806                                         append_quoted (q, rem_indent,
807                                                        remaining, breakpoint);
808                                         g_string_erase (remaining, 0,
809                                                         breakpoint);
810                                         if (remaining->str[0] == ' ') {
811                                                 g_string_erase (remaining, 0,
812                                                                 1);
813                                         }
814                                 } while (remaining->len);
815                         }
816                 }
817                 g_string_free (remaining, TRUE);
818                 breakpoint = get_breakpoint (l->str, indent, limit);
819                 remaining = g_string_new (l->str + breakpoint);
820                 if (remaining->str[0] == ' ') {
821                         g_string_erase (remaining, 0, 1);
822                 }
823                 rem_indent = indent;
824                 append_quoted (q, indent, l, breakpoint);
825                 g_string_free (l, TRUE);
826         } while ((iter < text + len) || (remaining->str[0]));
827
828         attachments_string = quoted_attachments (attachments);
829         q = g_string_append (q, attachments_string);
830         g_free (attachments_string);
831
832         if (signature != NULL) {
833                 q = g_string_append_c (q, '\n');
834                 q = g_string_append (q, signature);
835         }
836
837         return g_string_free (q, FALSE);
838 }
839
840 static gchar*
841 modest_text_utils_quote_html (const gchar *text, 
842                               const gchar *cite, 
843                               const gchar *signature,
844                               GList *attachments,
845                               int limit)
846 {
847         gchar *result = NULL;
848         gchar *signature_result = NULL;
849         const gchar *format = \
850                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
851                 "<html>\n" \
852                 "<body>\n" \
853                 "<br/>%s<br/>" \
854                 "<pre>%s<br/>%s<br/>%s</pre>\n" \
855                 "</body>\n" \
856                 "</html>\n";
857         gchar *attachments_string = NULL;
858         gchar *q_attachments_string = NULL;
859         gchar *q_cite = NULL;
860         gchar *html_text = NULL;
861
862         if (signature == NULL)
863                 signature_result = g_strdup ("");
864         else
865                 signature_result = modest_text_utils_convert_to_html_body (signature, -1, TRUE);
866
867         attachments_string = quoted_attachments (attachments);
868         q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string, -1, TRUE);
869         q_cite = modest_text_utils_convert_to_html_body (cite, -1, TRUE);
870         html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
871         result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
872         g_free (q_cite);
873         g_free (html_text);
874         g_free (attachments_string);
875         g_free (q_attachments_string);
876         g_free (signature_result);
877         
878         return result;
879 }
880
881 static gint 
882 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
883 {
884         return match2->offset - match1->offset;
885 }
886
887 static gboolean url_matches_block = 0;
888 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
889
890
891 static gboolean
892 compile_patterns ()
893 {
894         guint i;
895         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
896         for (i = 0; i != pattern_num; ++i) {
897                 patterns[i].preg = g_slice_new0 (regex_t);
898                 
899                 /* this should not happen */
900                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
901                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, FALSE);
902         }
903         return TRUE;
904 }
905
906 static void 
907 free_patterns ()
908 {
909         guint i;
910         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
911         for (i = 0; i != pattern_num; ++i) {
912                 regfree (patterns[i].preg);
913                 g_slice_free  (regex_t, patterns[i].preg);
914         } /* don't free patterns itself -- it's static */
915 }
916
917 void
918 modest_text_utils_hyperlinkify_begin (void)
919 {
920         if (url_matches_block == 0)
921                 compile_patterns ();
922         url_matches_block ++;
923 }
924
925 void
926 modest_text_utils_hyperlinkify_end (void)
927 {
928         url_matches_block--;
929         if (url_matches_block <= 0)
930                 free_patterns ();
931 }
932
933
934 static GSList*
935 get_url_matches (GString *txt)
936 {
937         regmatch_t rm;
938         guint rv, i, offset = 0;
939         GSList *match_list = NULL;
940
941         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
942
943         /* initalize the regexps */
944         modest_text_utils_hyperlinkify_begin ();
945
946         /* find all the matches */
947         for (i = 0; i != pattern_num; ++i) {
948                 offset     = 0; 
949                 while (1) {
950                         url_match_t *match;
951                         gboolean is_submatch;
952                         GSList *cursor;
953                         
954                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
955                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
956                                 break; /* try next regexp */ 
957                         }
958                         if (rm.rm_so == -1)
959                                 break;
960                         
961                         is_submatch = FALSE;
962                         /* check  old matches to see if this has already been matched */
963                         cursor = match_list;
964                         while (cursor && !is_submatch) {
965                                 const url_match_t *old_match =
966                                         (const url_match_t *) cursor->data;
967                                 guint new_offset = offset + rm.rm_so;
968                                 is_submatch = (new_offset >  old_match->offset &&
969                                                new_offset <  old_match->offset + old_match->len);
970                                 cursor = g_slist_next (cursor);
971                         }
972
973                         if (!is_submatch) {
974                                 /* make a list of our matches (<offset, len, prefix> tupels)*/
975                                 match = g_slice_new (url_match_t);
976                                 match->offset = offset + rm.rm_so;
977                                 match->len    = rm.rm_eo - rm.rm_so;
978                                 match->prefix = patterns[i].prefix;
979                                 match_list = g_slist_prepend (match_list, match);
980                         }               
981                         offset += rm.rm_eo;
982                 }
983         }
984
985         modest_text_utils_hyperlinkify_end ();
986         
987         /* now sort the list, so the matches are in reverse order of occurence.
988          * that way, we can do the replacements starting from the end, so we don't need
989          * to recalculate the offsets
990          */
991         match_list = g_slist_sort (match_list,
992                                    (GCompareFunc)cmp_offsets_reverse); 
993         return match_list;      
994 }
995
996
997
998 static void
999 hyperlinkify_plain_text (GString *txt)
1000 {
1001         GSList *cursor;
1002         GSList *match_list = get_url_matches (txt);
1003
1004         /* we will work backwards, so the offsets stay valid */
1005         for (cursor = match_list; cursor; cursor = cursor->next) {
1006
1007                 url_match_t *match = (url_match_t*) cursor->data;
1008                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
1009                 gchar *repl = NULL; /* replacement  */
1010
1011                 /* the prefix is NULL: use the one that is already there */
1012                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1013                                         match->prefix ? match->prefix : EMPTY_STRING, 
1014                                         url, url);
1015
1016                 /* replace the old thing with our hyperlink
1017                  * replacement thing */
1018                 g_string_erase  (txt, match->offset, match->len);
1019                 g_string_insert (txt, match->offset, repl);
1020                 
1021                 g_free (url);
1022                 g_free (repl);
1023
1024                 g_slice_free (url_match_t, match);      
1025         }
1026         
1027         g_slist_free (match_list);
1028 }
1029
1030
1031 /* for optimization reasons, we change the string in-place */
1032 void
1033 modest_text_utils_get_display_address (gchar *address)
1034 {
1035         int i;
1036
1037         g_return_if_fail (address);
1038         
1039         if (!address)
1040                 return;
1041         
1042         /* should not be needed, and otherwise, we probably won't screw up the address
1043          * more than it already is :) 
1044          * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1045          * */
1046         
1047         /* remove leading whitespace */
1048         if (address[0] == ' ')
1049                 g_strchug (address);
1050                 
1051         for (i = 0; address[i]; ++i) {
1052                 if (address[i] == '<') {
1053                         if (G_UNLIKELY(i == 0))
1054                                 return; /* there's nothing else, leave it */
1055                         else {
1056                                 address[i] = '\0'; /* terminate the string here */
1057                                 return;
1058                         }
1059                 }
1060         }
1061 }
1062
1063
1064
1065
1066
1067 gchar *
1068 modest_text_utils_get_email_address (const gchar *full_address)
1069 {
1070         const gchar *left, *right;
1071
1072         g_return_val_if_fail (full_address, NULL);
1073         
1074         if (!full_address)
1075                 return NULL;
1076         
1077         g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1078         
1079         left = g_strrstr_len (full_address, strlen(full_address), "<");
1080         if (left == NULL)
1081                 return g_strdup (full_address);
1082
1083         right = g_strstr_len (left, strlen(left), ">");
1084         if (right == NULL)
1085                 return g_strdup (full_address);
1086
1087         return g_strndup (left + 1, right - left - 1);
1088 }
1089
1090 gint 
1091 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1092 {
1093         gint prefix_len = 0;    
1094
1095         g_return_val_if_fail (sub, 0);
1096
1097         if (!sub)
1098                 return 0;
1099         
1100         /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1101         if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1102                 return 0;
1103         else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1104                 return 0;
1105
1106         prefix_len = 2;
1107         if (sub[2] == 'd')
1108                 ++prefix_len;
1109
1110         /* skip over a [...] block */
1111         if (sub[prefix_len] == '[') {
1112                 int c = prefix_len + 1;
1113                 while (sub[c] && sub[c] != ']')
1114                         ++c;
1115                 if (sub[c])
1116                         return 0; /* no end to the ']' found */
1117                 else
1118                         prefix_len = c + 1;
1119         }
1120
1121         /* did we find the ':' ? */
1122         if (sub[prefix_len] == ':') {
1123                 ++prefix_len;
1124                 if (sub[prefix_len] == ' ')
1125                         ++prefix_len;
1126                 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1127 /*              g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1128                 return prefix_len;
1129         } else
1130                 return 0;
1131 }
1132
1133
1134 gint
1135 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1136 {
1137
1138 /* work even when s1 and/or s2 == NULL */
1139         if (G_UNLIKELY(s1 == s2))
1140                 return 0;
1141         if (G_UNLIKELY(!s1))
1142                 return -1;
1143         if (G_UNLIKELY(!s2))
1144                 return 1;
1145         
1146         /* if it's not case sensitive */
1147         if (!insensitive) {
1148
1149                 /* optimization: short cut if first char is ascii */ 
1150                 if (((s1[0] & 0xf0)== 0) && ((s2[0] & 0xf0) == 0)) 
1151                         return s1[0] - s2[0];
1152                 
1153                 return g_utf8_collate (s1, s2);
1154
1155         } else {
1156                 gint result;
1157                 gchar *n1, *n2;
1158
1159                 /* optimization: short cut iif first char is ascii */ 
1160                 if (((s1[0] & 0xf0) == 0) && ((s2[0] & 0xf0) == 0)) 
1161                         return tolower(s1[0]) - tolower(s2[0]);
1162                 
1163                 n1 = g_utf8_strdown (s1, -1);
1164                 n2 = g_utf8_strdown (s2, -1);
1165                 
1166                 result = g_utf8_collate (n1, n2);
1167                 
1168                 g_free (n1);
1169                 g_free (n2);
1170         
1171                 return result;
1172         }
1173 }
1174
1175
1176 const gchar*
1177 modest_text_utils_get_display_date (time_t date)
1178 {
1179 #define DATE_BUF_SIZE 64 
1180         static gchar date_buf[DATE_BUF_SIZE];
1181         
1182         /* calculate the # of days since epoch for 
1183          * for today and for the date provided 
1184          * based on idea from pvanhoof */
1185         int day      = time(NULL) / (24 * 60 * 60);
1186         int date_day = date       / (24 * 60 * 60);
1187
1188         /* if it's today, show the time, if it's not today, show the date instead */
1189
1190         if (day == date_day) /* is the date today? */
1191                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%X", date);
1192         else 
1193                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%x", date); 
1194
1195         return date_buf; /* this is a static buffer, don't free! */
1196 }
1197
1198
1199
1200 gboolean
1201 modest_text_utils_validate_folder_name (const gchar *folder_name)
1202 {
1203         /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1204          * with some extras */
1205         
1206         guint len;
1207         gint i;
1208         const gchar **cursor = NULL;
1209         const gchar *forbidden_names[] = { /* windows does not like these */
1210                 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
1211                 "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1212                 ".", "..", NULL
1213         };
1214         
1215         /* cannot be NULL */
1216         if (!folder_name) 
1217                 return FALSE;
1218
1219         /* cannot be empty */
1220         len = strlen(folder_name);
1221         if (len == 0)
1222                 return FALSE;
1223         
1224         /* cannot start or end with a space */
1225         if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1226                 return FALSE; 
1227
1228         /* cannot contain a forbidden char */   
1229         for (i = 0; i < len; i++)
1230                 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1231                         return FALSE;
1232         
1233         /* cannot contain a forbidden word */
1234         if (len <= 4) {
1235                 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1236                         if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1237                                 return FALSE;
1238                 }
1239         }
1240
1241         return TRUE; /* it's valid! */
1242 }
1243
1244
1245
1246 gboolean
1247 modest_text_utils_validate_domain_name (const gchar *domain)
1248 {
1249         gboolean valid = FALSE;
1250         regex_t rx;
1251         const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1252
1253         g_return_val_if_fail (domain, FALSE);
1254         
1255         if (!domain)
1256                 return FALSE;
1257         
1258         memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1259                 
1260         /* domain name: all alphanum or '-' or '.',
1261          * but beginning/ending in alphanum */  
1262         if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1263                 g_warning ("BUG: error in regexp");
1264                 return FALSE;
1265         }
1266         
1267         valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1268         regfree (&rx);
1269                 
1270         return valid;
1271 }
1272
1273
1274
1275 gboolean
1276 modest_text_utils_validate_email_address (const gchar *email_address,
1277                                           const gchar **invalid_char_position)
1278 {
1279         int count = 0;
1280         const gchar *c = NULL, *domain = NULL;
1281         static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1282         
1283         if (invalid_char_position)
1284                 *invalid_char_position = NULL;
1285         
1286         g_return_val_if_fail (email_address, FALSE);
1287         
1288         /* check that the email adress contains exactly one @ */
1289         if (!strstr(email_address, "@") || 
1290                         (strstr(email_address, "@") != g_strrstr(email_address, "@"))) 
1291                 return FALSE;
1292         
1293         /* first we validate the name portion (name@domain) */
1294         for (c = email_address;  *c;  c++) {
1295                 if (*c == '\"' && 
1296                     (c == email_address || 
1297                      *(c - 1) == '.' || 
1298                      *(c - 1) == '\"')) {
1299                         while (*++c) {
1300                                 if (*c == '\"') 
1301                                         break;
1302                                 if (*c == '\\' && (*++c == ' ')) 
1303                                         continue;
1304                                 if (*c <= ' ' || *c >= 127) 
1305                                         return FALSE;
1306                         }
1307                         if (!*c++) 
1308                                 return FALSE;
1309                         if (*c == '@') 
1310                                 break;
1311                         if (*c != '.') 
1312                                 return FALSE;
1313                         continue;
1314                 }
1315                 if (*c == '@') 
1316                         break;
1317                 if (*c <= ' ' || *c >= 127) 
1318                         return FALSE;
1319                 if (strchr(rfc822_specials, *c)) {
1320                         if (invalid_char_position)
1321                                 *invalid_char_position = c;
1322                         return FALSE;
1323                 }
1324         }
1325         if (c == email_address || *(c - 1) == '.') 
1326                 return FALSE;
1327
1328         /* next we validate the domain portion (name@domain) */
1329         if (!*(domain = ++c)) 
1330                 return FALSE;
1331         do {
1332                 if (*c == '.') {
1333                         if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0') 
1334                                 return FALSE;
1335                         count++;
1336                 }
1337                 if (*c <= ' ' || *c >= 127) 
1338                         return FALSE;
1339                 if (strchr(rfc822_specials, *c)) {
1340                         if (invalid_char_position)
1341                                 *invalid_char_position = c;
1342                         return FALSE;
1343                 }
1344         } while (*++c);
1345
1346         return (count >= 1) ? TRUE : FALSE;
1347 }
1348
1349 gboolean 
1350 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1351 {
1352         gchar *stripped, *current;
1353         gchar *right_part;
1354         gboolean has_error = FALSE;
1355
1356         if (invalid_char_position)
1357                 *invalid_char_position = NULL;
1358         
1359         g_return_val_if_fail (recipient, FALSE);
1360         
1361         if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1362                 return TRUE;
1363
1364         stripped = g_strdup (recipient);
1365         stripped = g_strstrip (stripped);
1366         current = stripped;
1367
1368         if (*current == '\0') {
1369                 g_free (stripped);
1370                 return FALSE;
1371         }
1372
1373         /* quoted string */
1374         if (*current == '\"') {
1375                 current = g_utf8_next_char (current);
1376                 has_error = TRUE;
1377                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1378                         if (*current == '\\') {
1379                                 /* TODO: This causes a warning, which breaks the build, 
1380                                  * because a gchar cannot be < 0.
1381                                  * murrayc. 
1382                                 if (current[1] <0) {
1383                                         has_error = TRUE;
1384                                         break;
1385                                 }
1386                                 */
1387                         } else if (*current == '\"') {
1388                                 has_error = FALSE;
1389                                 current = g_utf8_next_char (current);
1390                                 break;
1391                         }
1392                 }
1393         } else {
1394                 has_error = TRUE;
1395                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1396                         if (*current == '<') {
1397                                 has_error = FALSE;
1398                                 break;
1399                         }
1400                 }
1401         }
1402                 
1403         if (has_error) {
1404                 g_free (stripped);
1405                 return FALSE;
1406         }
1407
1408         right_part = g_strdup (current);
1409         g_free (stripped);
1410         right_part = g_strstrip (right_part);
1411
1412         if (g_str_has_prefix (right_part, "<") &&
1413             g_str_has_suffix (right_part, ">")) {
1414                 gchar *address;
1415                 gboolean valid;
1416
1417                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1418                 g_free (right_part);
1419                 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1420                 g_free (address);
1421                 return valid;
1422         } else {
1423                 g_free (right_part);
1424                 return FALSE;
1425         }
1426 }
1427
1428
1429 gchar *
1430 modest_text_utils_get_display_size (guint64 size)
1431 {
1432         const guint KB=1024;
1433         const guint MB=1024 * KB;
1434         const guint GB=1024 * MB;
1435
1436         if (size == 0)
1437                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1438         if (0 < size && size < KB)
1439                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1440         else if (KB <= size && size < 100 * KB)
1441                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1442         else if (100*KB <= size && size < MB)
1443                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1444         else if (MB <= size && size < 10*MB)
1445                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1446         else if (10*MB <= size && size < GB)
1447                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1448         else
1449                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1450 }
1451
1452 static gchar *
1453 get_email_from_address (const gchar * address)
1454 {
1455         gchar *left_limit, *right_limit;
1456
1457         left_limit = strstr (address, "<");
1458         right_limit = g_strrstr (address, ">");
1459
1460         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1461                 return g_strdup (address);
1462         else
1463                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1464 }
1465
1466 gchar *      
1467 modest_text_utils_get_color_string (GdkColor *color)
1468 {
1469         g_return_val_if_fail (color, NULL);
1470         
1471         return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1472                                 (color->red >> 12)   & 0xf, (color->red >> 8)   & 0xf,
1473                                 (color->red >>  4)   & 0xf, (color->red)        & 0xf,
1474                                 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1475                                 (color->green >>  4) & 0xf, (color->green)      & 0xf,
1476                                 (color->blue >> 12)  & 0xf, (color->blue >> 8)  & 0xf,
1477                                 (color->blue >>  4)  & 0xf, (color->blue)       & 0xf);
1478 }
1479
1480 gchar *
1481 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1482 {
1483         GtkTextIter start, end;
1484         gchar *slice, *current;
1485         GString *result = g_string_new ("");
1486
1487         g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1488         
1489         gtk_text_buffer_get_start_iter (buffer, &start);
1490         gtk_text_buffer_get_end_iter (buffer, &end);
1491
1492         slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1493         current = slice;
1494
1495         while (current && current != '\0') {
1496                 if (g_utf8_get_char (current) == 0xFFFC) {
1497                         result = g_string_append_c (result, ' ');
1498                         current = g_utf8_next_char (current);
1499                 } else {
1500                         gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1501                         if (next == NULL) {
1502                                 result = g_string_append (result, current);
1503                         } else {
1504                                 result = g_string_append_len (result, current, next - current);
1505                         }
1506                         current = next;
1507                 }
1508         }
1509         g_free (slice);
1510
1511         return g_string_free (result, FALSE);
1512         
1513 }
1514
1515 gboolean
1516 modest_text_utils_is_forbidden_char (const gchar character,
1517                                      ModestTextUtilsForbiddenCharType type)
1518 {
1519         gint i, len;
1520         const gchar *forbidden_chars = NULL;
1521         
1522         /* We need to get the length in the switch because the
1523            compiler needs to know the size at compile time */
1524         switch (type) {
1525         case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1526                 forbidden_chars = account_title_forbidden_chars;
1527                 len = G_N_ELEMENTS (account_title_forbidden_chars);
1528                 break;
1529         case FOLDER_NAME_FORBIDDEN_CHARS:
1530                 forbidden_chars = folder_name_forbidden_chars;
1531                 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1532                 break;
1533         case USER_NAME_FORBIDDEN_NAMES:
1534                 forbidden_chars = user_name_forbidden_chars;
1535                 len = G_N_ELEMENTS (user_name_forbidden_chars);
1536                 break;
1537         default:
1538                 g_return_val_if_reached (TRUE);
1539         }
1540
1541         for (i = 0; i < len ; i++)
1542                 if (forbidden_chars[i] == character)
1543                         return TRUE;
1544
1545         return FALSE; /* it's valid! */
1546 }