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