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