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