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