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