db6d708f86b87ce0e7c9decad06efdf982af1c18
[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 #include <glib.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <glib/gi18n.h>
35 #include <regex.h>
36 #include <modest-tny-platform-factory.h>
37 #include <modest-text-utils.h>
38 #include <modest-runtime.h>
39
40
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif /*HAVE_CONFIG_H */
44
45 /* defines */
46 #define FORWARD_STRING _("-----Forwarded Message-----")
47 #define FROM_STRING _("From:")
48 #define SENT_STRING _("Sent:")
49 #define TO_STRING _("To:")
50 #define SUBJECT_STRING _("Subject:")
51 #define EMPTY_STRING ""
52
53 /*
54  * we need these regexps to find URLs in plain text e-mails
55  */
56 typedef struct _url_match_pattern_t url_match_pattern_t;
57 struct _url_match_pattern_t {
58         gchar   *regex;
59         regex_t *preg;
60         gchar   *prefix;
61 };
62
63 typedef struct _url_match_t url_match_t;
64 struct _url_match_t {
65         guint offset;
66         guint len;
67         const gchar* prefix;
68 };
69
70 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
71         { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
72           NULL, NULL },\
73         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
74           NULL, "http://" },\
75         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
76           NULL, "ftp://" },\
77         { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
78            NULL, NULL},                                             \
79         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
80           NULL, NULL},\
81         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
82           NULL, "mailto:"}\
83         }
84
85 /* private */
86 static gchar*   cite                    (const time_t sent_date, const gchar *from);
87 static void     hyperlinkify_plain_text (GString *txt);
88 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
89 static void     chk_partial_match       (const url_match_t *match, guint* offset);
90 static GSList*  get_url_matches         (GString *txt);
91
92 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
93 static int      get_indent_level        (const char *l);
94 static void     unquote_line            (GString * l);
95 static void     append_quoted           (GString * buf, const int indent, const GString * str, 
96                                          const int cutpoint);
97 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
98 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
99 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
100
101 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
102                                                     const gchar *cite, 
103                                                     int limit);
104
105 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
106                                                     const gchar *cite, 
107                                                     int limit);
108
109
110 /* ******************************************************************* */
111 /* ************************* PUBLIC FUNCTIONS ************************ */
112 /* ******************************************************************* */
113
114 gchar *
115 modest_text_utils_quote (const gchar *text, 
116                          const gchar *content_type,
117                          const gchar *from,
118                          const time_t sent_date, 
119                          int limit)
120 {
121         gchar *retval, *cited;
122
123         g_return_val_if_fail (text, NULL);
124         g_return_val_if_fail (content_type, NULL);
125
126         cited = cite (sent_date, from);
127         
128         if (content_type && strcmp (content_type, "text/html") == 0)
129                 /* TODO: extract the <body> of the HTML and pass it to
130                    the function */
131                 retval = modest_text_utils_quote_html (text, cited, limit);
132         else
133                 retval = modest_text_utils_quote_plain_text (text, cited, limit);
134         
135         g_free (cited);
136
137         return retval;
138 }
139
140
141 gchar *
142 modest_text_utils_cite (const gchar *text,
143                         const gchar *content_type,
144                         const gchar *from,
145                         time_t sent_date)
146 {
147         gchar *tmp, *retval;
148
149         g_return_val_if_fail (text, NULL);
150         g_return_val_if_fail (content_type, NULL);
151
152         tmp = cite (sent_date, from);
153         retval = g_strdup_printf ("%s%s\n", tmp, text);
154         g_free (tmp);
155
156         return retval;
157 }
158
159 gchar * 
160 modest_text_utils_inline (const gchar *text,
161                           const gchar *content_type,
162                           const gchar *from,
163                           time_t sent_date,
164                           const gchar *to,
165                           const gchar *subject)
166 {
167         gchar sent_str[101];
168         const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
169         const gchar *html_format = \
170                 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
171                 "<tr><td>%s</td><td>%s</td></tr>\n" \
172                 "<tr><td>%s</td><td>%s</td></tr>\n" \
173                 "<tr><td>%s</td><td>%s</td></tr>\n" \
174                 "<tr><td>%s</td><td>%s</td></tr>\n" \
175                 "<br><br>%s";
176         const gchar *format;
177
178         g_return_val_if_fail (text, NULL);
179         g_return_val_if_fail (content_type, NULL);
180         g_return_val_if_fail (text, NULL);
181         
182         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
183
184         if (!strcmp (content_type, "text/html"))
185                 /* TODO: extract the <body> of the HTML and pass it to
186                    the function */
187                 format = html_format;
188         else
189                 format = plain_format;
190
191         return g_strdup_printf (format, 
192                                 FORWARD_STRING,
193                                 FROM_STRING, (from) ? from : EMPTY_STRING,
194                                 SENT_STRING, sent_str,
195                                 TO_STRING, (to) ? to : EMPTY_STRING,
196                                 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
197                                 text);
198 }
199
200 /* just to prevent warnings:
201  * warning: `%x' yields only last 2 digits of year in some locales
202  */
203 gsize
204 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
205 {
206         static GDate date;
207
208         /* FIXME: deprecated in newer glib versions */
209         g_date_set_time (&date, (GTime) timet);
210         return g_date_strftime (s, max, fmt, (const GDate*) &date);
211 }
212
213 gchar *
214 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
215 {
216         gchar *tmp;
217
218         g_return_val_if_fail (prefix, NULL);
219         
220         if (!subject)
221                 return g_strdup (prefix);
222
223         tmp = g_strchug (g_strdup (subject));
224
225         if (!strncmp (tmp, prefix, strlen (prefix))) {
226                 return tmp;
227         } else {
228                 g_free (tmp);
229                 return g_strdup_printf ("%s %s", prefix, subject);
230         }
231 }
232
233 gchar*
234 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
235 {
236         gchar *dup, *token, *ptr, *result;
237         GString *filtered_emails;
238
239         g_return_val_if_fail (address_list, NULL);
240
241         if (!address)
242                 return g_strdup (address_list);
243         
244         /* search for substring */
245         if (!strstr ((const char *) address_list, (const char *) address))
246                 return g_strdup (address_list);
247
248         dup = g_strdup (address_list);
249         filtered_emails = g_string_new (NULL);
250         
251         token = strtok_r (dup, ",", &ptr);
252
253         while (token != NULL) {
254                 /* Add to list if not found */
255                 if (!strstr ((const char *) token, (const char *) address)) {
256                         if (filtered_emails->len == 0)
257                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
258                         else
259                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
260                 }
261                 token = strtok_r (NULL, ",", &ptr);
262         }
263         result = filtered_emails->str;
264
265         /* Clean */
266         g_free (dup);
267         g_string_free (filtered_emails, FALSE);
268
269         return result;
270 }
271
272 gchar*
273 modest_text_utils_convert_to_html (const gchar *data)
274 {
275         guint            i;
276         gboolean         first_space = TRUE;
277         GString         *html;      
278         gsize           len;
279
280         if (!data)
281                 return NULL;
282
283         len = strlen (data);
284         html = g_string_sized_new (len + 100);  /* just a  guess... */
285         
286         g_string_append_printf (html,
287                                 "<html>"
288                                 "<head>"
289                                 "<meta http-equiv=\"content-type\""
290                                 " content=\"text/html; charset=utf8\">"
291                                 "</head>"
292                                 "<body><tt>");
293         
294         /* replace with special html chars where needed*/
295         for (i = 0; i != len; ++i)  {
296                 char    kar = data[i]; 
297                 switch (kar) {
298                         
299                 case 0:  break; /* ignore embedded \0s */       
300                 case '<' : g_string_append   (html, "&lt;"); break;
301                 case '>' : g_string_append   (html, "&gt;"); break;
302                 case '&' : g_string_append   (html, "&quot;"); break;
303                 case '\n': g_string_append   (html, "<br>\n"); break;
304                 default:
305                         if (kar == ' ') {
306                                 g_string_append (html, first_space ? " " : "&nbsp;");
307                                 first_space = FALSE;
308                         } else  if (kar == '\t')
309                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
310                         else {
311                                 int charnum = 0;
312                                 first_space = TRUE;
313                                 /* optimization trick: accumulate 'normal' chars, then copy */
314                                 do {
315                                         kar = data [++charnum + i];
316                                         
317                                 } while ((i + charnum < len) &&
318                                          (kar > '>' || (kar != '<' && kar != '>'
319                                                         && kar != '&' && kar !=  ' '
320                                                         && kar != '\n' && kar != '\t')));
321                                 g_string_append_len (html, &data[i], charnum);
322                                 i += (charnum  - 1);
323                         }
324                 }
325         }
326         
327         g_string_append (html, "</tt></body></html>");
328         hyperlinkify_plain_text (html);
329
330         return g_string_free (html, FALSE);
331 }
332
333 /* ******************************************************************* */
334 /* ************************* UTILIY FUNCTIONS ************************ */
335 /* ******************************************************************* */
336
337 static GString *
338 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
339 {
340         GString *gs;
341         const gchar *i0;
342         
343         if (iter > b + blen)
344                 return g_string_new("");
345         
346         i0 = iter;
347         while (iter[0]) {
348                 if (iter[0] == '\n')
349                         break;
350                 iter++;
351         }
352         gs = g_string_new_len (i0, iter - i0);
353         return gs;
354 }
355 static int
356 get_indent_level (const char *l)
357 {
358         int indent = 0;
359
360         while (l[0]) {
361                 if (l[0] == '>') {
362                         indent++;
363                         if (l[1] == ' ') {
364                                 l++;
365                         }
366                 } else {
367                         break;
368                 }
369                 l++;
370
371         }
372
373         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
374          *      stops reformatting.
375          */
376         if (strcmp (l, "-- ") == 0) {
377                 return -1 - indent;
378         } else {
379                 return indent;
380         }
381 }
382
383 static void
384 unquote_line (GString * l)
385 {
386         gchar *p;
387
388         p = l->str;
389         while (p[0]) {
390                 if (p[0] == '>') {
391                         if (p[1] == ' ') {
392                                 p++;
393                         }
394                 } else {
395                         break;
396                 }
397                 p++;
398         }
399         g_string_erase (l, 0, p - l->str);
400 }
401
402 static void
403 append_quoted (GString * buf, int indent, const GString * str,
404                const int cutpoint)
405 {
406         int i;
407
408         indent = indent < 0 ? abs (indent) - 1 : indent;
409         for (i = 0; i <= indent; i++) {
410                 g_string_append (buf, "> ");
411         }
412         if (cutpoint > 0) {
413                 g_string_append_len (buf, str->str, cutpoint);
414         } else {
415                 g_string_append (buf, str->str);
416         }
417         g_string_append (buf, "\n");
418 }
419
420 static int
421 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
422 {
423         gint index = 0;
424         const gchar *pos, *last;
425         gunichar *uni;
426
427         indent = indent < 0 ? abs (indent) - 1 : indent;
428
429         last = NULL;
430         pos = s;
431         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
432         while (pos[0]) {
433                 if ((index + 2 * indent > limit) && last) {
434                         g_free (uni);
435                         return last - s;
436                 }
437                 if (g_unichar_isspace (uni[index])) {
438                         last = pos;
439                 }
440                 pos = g_utf8_next_char (pos);
441                 index++;
442         }
443         g_free (uni);
444         return strlen (s);
445 }
446
447 static int
448 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
449 {
450         gint i, last;
451
452         last = strlen (s);
453         if (last + 2 * indent < limit)
454                 return last;
455
456         for (i = strlen (s); i > 0; i--) {
457                 if (s[i] == ' ') {
458                         if (i + 2 * indent <= limit) {
459                                 return i;
460                         } else {
461                                 last = i;
462                         }
463                 }
464         }
465         return last;
466 }
467
468 static int
469 get_breakpoint (const gchar * s, const gint indent, const gint limit)
470 {
471
472         if (g_utf8_validate (s, -1, NULL)) {
473                 return get_breakpoint_utf8 (s, indent, limit);
474         } else {                /* assume ASCII */
475                 //g_warning("invalid UTF-8 in msg");
476                 return get_breakpoint_ascii (s, indent, limit);
477         }
478 }
479
480 static gchar *
481 cite (const time_t sent_date, const gchar *from)
482 {
483         gchar sent_str[101];
484
485         /* format sent_date */
486         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
487         return g_strdup_printf (N_("On %s, %s wrote:\n"), 
488                                 sent_str, 
489                                 (from) ? from : EMPTY_STRING);
490 }
491
492
493 static gchar *
494 modest_text_utils_quote_plain_text (const gchar *text, 
495                                     const gchar *cite, 
496                                     int limit)
497 {
498         const gchar *iter;
499         gint indent, breakpoint, rem_indent = 0;
500         GString *q, *l, *remaining;
501         gsize len;
502
503         /* remaining will store the rest of the line if we have to break it */
504         q = g_string_new (cite);
505         remaining = g_string_new ("");
506
507         iter = text;
508         len = strlen(text);
509         do {
510                 l = get_next_line (text, len, iter);
511                 iter = iter + l->len + 1;
512                 indent = get_indent_level (l->str);
513                 unquote_line (l);
514
515                 if (remaining->len) {
516                         if (l->len && indent == rem_indent) {
517                                 g_string_prepend (l, " ");
518                                 g_string_prepend (l, remaining->str);
519                         } else {
520                                 do {
521                                         breakpoint =
522                                                 get_breakpoint (remaining->str,
523                                                                 rem_indent,
524                                                                 limit);
525                                         append_quoted (q, rem_indent,
526                                                        remaining, breakpoint);
527                                         g_string_erase (remaining, 0,
528                                                         breakpoint);
529                                         if (remaining->str[0] == ' ') {
530                                                 g_string_erase (remaining, 0,
531                                                                 1);
532                                         }
533                                 } while (remaining->len);
534                         }
535                 }
536                 g_string_free (remaining, TRUE);
537                 breakpoint = get_breakpoint (l->str, indent, limit);
538                 remaining = g_string_new (l->str + breakpoint);
539                 if (remaining->str[0] == ' ') {
540                         g_string_erase (remaining, 0, 1);
541                 }
542                 rem_indent = indent;
543                 append_quoted (q, indent, l, breakpoint);
544                 g_string_free (l, TRUE);
545         } while ((iter < text + len) || (remaining->str[0]));
546
547         return g_string_free (q, FALSE);
548 }
549
550 static gchar*
551 modest_text_utils_quote_html (const gchar *text, 
552                               const gchar *cite, 
553                               int limit)
554 {
555         const gchar *format = \
556                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
557                 "<html>\n" \
558                 "<body>\n" \
559                 "%s" \
560                 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
561                 "</body>\n" \
562                 "</html>\n";
563
564         return g_strdup_printf (format, cite, text);
565 }
566
567 static gint 
568 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
569 {
570         return match2->offset - match1->offset;
571 }
572
573
574
575 /*
576  * check if the match is inside an existing match... */
577 static void
578 chk_partial_match (const url_match_t *match, guint* offset)
579 {
580         if (*offset >= match->offset && *offset < match->offset + match->len)
581                 *offset = -1;
582 }
583
584 static GSList*
585 get_url_matches (GString *txt)
586 {
587         regmatch_t rm;
588         guint rv, i, offset = 0;
589         GSList *match_list = NULL;
590
591         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
592         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
593
594         /* initalize the regexps */
595         for (i = 0; i != pattern_num; ++i) {
596                 patterns[i].preg = g_slice_new0 (regex_t);
597
598                 /* this should not happen */
599                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
600                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
601         }
602         /* find all the matches */
603         for (i = 0; i != pattern_num; ++i) {
604                 offset     = 0; 
605                 while (1) {
606                         int test_offset;
607                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
608                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
609                                 break; /* try next regexp */ 
610                         }
611                         if (rm.rm_so == -1)
612                                 break;
613
614                         /* FIXME: optimize this */
615                         /* to avoid partial matches on something that was already found... */
616                         /* check_partial_match will put -1 in the data ptr if that is the case */
617                         test_offset = offset + rm.rm_so;
618                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
619                         
620                         /* make a list of our matches (<offset, len, prefix> tupels)*/
621                         if (test_offset != -1) {
622                                 url_match_t *match = g_slice_new (url_match_t);
623                                 match->offset = offset + rm.rm_so;
624                                 match->len    = rm.rm_eo - rm.rm_so;
625                                 match->prefix = patterns[i].prefix;
626                                 match_list = g_slist_prepend (match_list, match);
627                         }
628                         offset += rm.rm_eo;
629                 }
630         }
631
632         for (i = 0; i != pattern_num; ++i) {
633                 regfree (patterns[i].preg);
634                 g_slice_free  (regex_t, patterns[i].preg);
635         } /* don't free patterns itself -- it's static */
636         
637         /* now sort the list, so the matches are in reverse order of occurence.
638          * that way, we can do the replacements starting from the end, so we don't need
639          * to recalculate the offsets
640          */
641         match_list = g_slist_sort (match_list,
642                                    (GCompareFunc)cmp_offsets_reverse); 
643         return match_list;      
644 }
645
646
647
648 static void
649 hyperlinkify_plain_text (GString *txt)
650 {
651         GSList *cursor;
652         GSList *match_list = get_url_matches (txt);
653
654         /* we will work backwards, so the offsets stay valid */
655         for (cursor = match_list; cursor; cursor = cursor->next) {
656
657                 url_match_t *match = (url_match_t*) cursor->data;
658                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
659                 gchar *repl = NULL; /* replacement  */
660
661                 /* the prefix is NULL: use the one that is already there */
662                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
663                                         match->prefix ? match->prefix : EMPTY_STRING, 
664                                         url, url);
665
666                 /* replace the old thing with our hyperlink
667                  * replacement thing */
668                 g_string_erase  (txt, match->offset, match->len);
669                 g_string_insert (txt, match->offset, repl);
670                 
671                 g_free (url);
672                 g_free (repl);
673
674                 g_slice_free (url_match_t, match);      
675         }
676         
677         g_slist_free (match_list);
678 }
679
680
681
682 gchar*
683 modest_text_utils_get_display_address (gchar *address)
684 {
685         gchar *cursor;
686         
687         if (!address)
688                 return NULL;
689
690         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
691
692         g_strchug (address); /* remove leading whitespace */
693
694         /*  <email@address> from display name */
695         cursor = g_strstr_len (address, strlen(address), "<");
696         if (cursor == address) /* there's nothing else? leave it */
697                 return address;
698         if (cursor) 
699                 cursor[0]='\0';
700
701         /* remove (bla bla) from display name */
702         cursor = g_strstr_len (address, strlen(address), "(");
703         if (cursor == address) /* there's nothing else? leave it */
704                 return address;
705         if (cursor) 
706                 cursor[0]='\0';
707
708         g_strchomp (address); /* remove trailing whitespace */
709
710         return address;
711 }
712
713
714
715 gint 
716 modest_text_utils_get_subject_prefix_len (const gchar *sub)
717 {
718         gint i;
719         static const gchar* prefix[] = {
720                 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
721         };
722                 
723         if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
724                 return 0;
725
726         i = 0;
727         
728         while (prefix[i]) {
729                 if (g_str_has_prefix(sub, prefix[i])) {
730                         int prefix_len = strlen(prefix[i]); 
731                         if (sub[prefix_len] == ' ')
732                                 ++prefix_len; /* ignore space after prefix as well */
733                         return prefix_len; 
734                 }
735                 ++i;
736         }
737         return 0;
738 }
739
740
741 gint
742 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
743 {
744         gint result = 0;
745         gchar *n1, *n2;
746
747         /* work even when s1 and/or s2 == NULL */
748         if (G_UNLIKELY(s1 == s2))
749                 return 0;
750
751         /* if it's not case sensitive */
752         if (!insensitive)
753                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
754         
755         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
756         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
757         
758         result = strcmp (n1, n2);
759
760         g_free (n1);
761         g_free (n2);
762         
763         return result;
764 }
765
766
767 gchar*
768 modest_text_utils_get_display_date (time_t date)
769 {
770         time_t now;
771         const guint BUF_SIZE = 64; 
772         gchar date_buf[BUF_SIZE];  
773         gchar now_buf [BUF_SIZE];  
774         
775         now = time (NULL);
776
777         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
778         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x",  now); /* today */
779         
780         /* if this is today, get the time instead of the date */
781         if (strcmp (date_buf, now_buf) == 0)
782                 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
783         
784         return g_strdup(date_buf);
785 }
786
787 gboolean 
788 modest_text_utils_validate_email_address (const gchar *email_address)
789 {
790         int count = 0;
791         const gchar *c, *domain;
792         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
793
794         /* first we validate the name portion (name@domain) */
795         for (c = email_address;  *c;  c++) {
796                 if (*c == '\"' && 
797                     (c == email_address || 
798                      *(c - 1) == '.' || 
799                      *(c - 1) == '\"')) {
800                         while (*++c) {
801                                 if (*c == '\"') 
802                                         break;
803                                 if (*c == '\\' && (*++c == ' ')) 
804                                         continue;
805                                 if (*c <= ' ' || *c >= 127) 
806                                         return FALSE;
807                         }
808                         if (!*c++) 
809                                 return FALSE;
810                         if (*c == '@') 
811                                 break;
812                         if (*c != '.') 
813                                 return FALSE;
814                         continue;
815                 }
816                 if (*c == '@') 
817                         break;
818                 if (*c <= ' ' || *c >= 127) 
819                         return FALSE;
820                 if (strchr(rfc822_specials, *c)) 
821                         return FALSE;
822         }
823         if (c == email_address || *(c - 1) == '.') 
824                 return FALSE;
825
826         /* next we validate the domain portion (name@domain) */
827         if (!*(domain = ++c)) 
828                 return FALSE;
829         do {
830                 if (*c == '.') {
831                         if (c == domain || *(c - 1) == '.') 
832                                 return FALSE;
833                         count++;
834                 }
835                 if (*c <= ' ' || *c >= 127) 
836                         return FALSE;
837                 if (strchr(rfc822_specials, *c)) 
838                         return FALSE;
839         } while (*++c);
840
841         return (count >= 1) ? TRUE : FALSE;
842 }
843
844
845
846
847 gchar *
848 modest_text_utils_get_display_size (guint size)
849 {
850         const guint KB=1024;
851         const guint MB=1024 * KB;
852         const guint GB=1024 * MB;
853         const guint TB=1024 * GB;
854
855         if (size < KB)
856                 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
857         else if (size < MB)
858                 return g_strdup_printf (_("%d Kb"), size / KB);
859         else if (size < GB)
860                 return g_strdup_printf (_("%d Mb"), size / MB);
861         else if (size < TB)
862                 return g_strdup_printf (_("%d Gb"), size/ GB);
863         else
864                 return g_strdup_printf (_("Very big"));
865 }