e5712ed55ce07a0aa27ddd0d03d63a8b50dc5ebf
[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", 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 gsize
203 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
204 {
205         /* only since Gtk 2.10
206          *
207          *static GDate date;
208          *g_date_set_time_t (&date, timet);
209          *return g_date_strftime (s, max, fmt, (const GDate*) &date);
210          */
211
212         struct tm *time_tm;
213         time_tm = localtime (&timet);
214         
215         return strftime (s, max, fmt, time_tm);
216 }
217
218 gchar *
219 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
220 {
221         gchar *tmp;
222
223         g_return_val_if_fail (prefix, NULL);
224         
225         if (!subject)
226                 return g_strdup (prefix);
227
228         tmp = g_strchug (g_strdup (subject));
229
230         if (!strncmp (tmp, prefix, strlen (prefix))) {
231                 return tmp;
232         } else {
233                 g_free (tmp);
234                 return g_strdup_printf ("%s %s", prefix, subject);
235         }
236 }
237
238 gchar*
239 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
240 {
241         gchar *dup, *token, *ptr, *result;
242         GString *filtered_emails;
243
244         g_return_val_if_fail (address_list, NULL);
245
246         if (!address)
247                 return g_strdup (address_list);
248         
249         /* search for substring */
250         if (!strstr ((const char *) address_list, (const char *) address))
251                 return g_strdup (address_list);
252
253         dup = g_strdup (address_list);
254         filtered_emails = g_string_new (NULL);
255         
256         token = strtok_r (dup, ",", &ptr);
257
258         while (token != NULL) {
259                 /* Add to list if not found */
260                 if (!strstr ((const char *) token, (const char *) address)) {
261                         if (filtered_emails->len == 0)
262                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
263                         else
264                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
265                 }
266                 token = strtok_r (NULL, ",", &ptr);
267         }
268         result = filtered_emails->str;
269
270         /* Clean */
271         g_free (dup);
272         g_string_free (filtered_emails, FALSE);
273
274         return result;
275 }
276
277 gchar*
278 modest_text_utils_convert_to_html (const gchar *data)
279 {
280         guint            i;
281         gboolean         first_space = TRUE;
282         GString         *html;      
283         gsize           len;
284
285         if (!data)
286                 return NULL;
287
288         len = strlen (data);
289         html = g_string_sized_new (len + 100);  /* just a  guess... */
290         
291         g_string_append_printf (html,
292                                 "<html>"
293                                 "<head>"
294                                 "<meta http-equiv=\"content-type\""
295                                 " content=\"text/html; charset=utf8\">"
296                                 "</head>"
297                                 "<body><tt>");
298         
299         /* replace with special html chars where needed*/
300         for (i = 0; i != len; ++i)  {
301                 char    kar = data[i]; 
302                 switch (kar) {
303                         
304                 case 0:  break; /* ignore embedded \0s */       
305                 case '<' : g_string_append   (html, "&lt;"); break;
306                 case '>' : g_string_append   (html, "&gt;"); break;
307                 case '&' : g_string_append   (html, "&quot;"); break;
308                 case '\n': g_string_append   (html, "<br>\n"); break;
309                 default:
310                         if (kar == ' ') {
311                                 g_string_append (html, first_space ? " " : "&nbsp;");
312                                 first_space = FALSE;
313                         } else  if (kar == '\t')
314                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
315                         else {
316                                 int charnum = 0;
317                                 first_space = TRUE;
318                                 /* optimization trick: accumulate 'normal' chars, then copy */
319                                 do {
320                                         kar = data [++charnum + i];
321                                         
322                                 } while ((i + charnum < len) &&
323                                          (kar > '>' || (kar != '<' && kar != '>'
324                                                         && kar != '&' && kar !=  ' '
325                                                         && kar != '\n' && kar != '\t')));
326                                 g_string_append_len (html, &data[i], charnum);
327                                 i += (charnum  - 1);
328                         }
329                 }
330         }
331         
332         g_string_append (html, "</tt></body></html>");
333         hyperlinkify_plain_text (html);
334
335         return g_string_free (html, FALSE);
336 }
337
338 /* ******************************************************************* */
339 /* ************************* UTILIY FUNCTIONS ************************ */
340 /* ******************************************************************* */
341
342 static GString *
343 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
344 {
345         GString *gs;
346         const gchar *i0;
347         
348         if (iter > b + blen)
349                 return g_string_new("");
350         
351         i0 = iter;
352         while (iter[0]) {
353                 if (iter[0] == '\n')
354                         break;
355                 iter++;
356         }
357         gs = g_string_new_len (i0, iter - i0);
358         return gs;
359 }
360 static int
361 get_indent_level (const char *l)
362 {
363         int indent = 0;
364
365         while (l[0]) {
366                 if (l[0] == '>') {
367                         indent++;
368                         if (l[1] == ' ') {
369                                 l++;
370                         }
371                 } else {
372                         break;
373                 }
374                 l++;
375
376         }
377
378         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
379          *      stops reformatting.
380          */
381         if (strcmp (l, "-- ") == 0) {
382                 return -1 - indent;
383         } else {
384                 return indent;
385         }
386 }
387
388 static void
389 unquote_line (GString * l)
390 {
391         gchar *p;
392
393         p = l->str;
394         while (p[0]) {
395                 if (p[0] == '>') {
396                         if (p[1] == ' ') {
397                                 p++;
398                         }
399                 } else {
400                         break;
401                 }
402                 p++;
403         }
404         g_string_erase (l, 0, p - l->str);
405 }
406
407 static void
408 append_quoted (GString * buf, int indent, const GString * str,
409                const int cutpoint)
410 {
411         int i;
412
413         indent = indent < 0 ? abs (indent) - 1 : indent;
414         for (i = 0; i <= indent; i++) {
415                 g_string_append (buf, "> ");
416         }
417         if (cutpoint > 0) {
418                 g_string_append_len (buf, str->str, cutpoint);
419         } else {
420                 g_string_append (buf, str->str);
421         }
422         g_string_append (buf, "\n");
423 }
424
425 static int
426 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
427 {
428         gint index = 0;
429         const gchar *pos, *last;
430         gunichar *uni;
431
432         indent = indent < 0 ? abs (indent) - 1 : indent;
433
434         last = NULL;
435         pos = s;
436         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
437         while (pos[0]) {
438                 if ((index + 2 * indent > limit) && last) {
439                         g_free (uni);
440                         return last - s;
441                 }
442                 if (g_unichar_isspace (uni[index])) {
443                         last = pos;
444                 }
445                 pos = g_utf8_next_char (pos);
446                 index++;
447         }
448         g_free (uni);
449         return strlen (s);
450 }
451
452 static int
453 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
454 {
455         gint i, last;
456
457         last = strlen (s);
458         if (last + 2 * indent < limit)
459                 return last;
460
461         for (i = strlen (s); i > 0; i--) {
462                 if (s[i] == ' ') {
463                         if (i + 2 * indent <= limit) {
464                                 return i;
465                         } else {
466                                 last = i;
467                         }
468                 }
469         }
470         return last;
471 }
472
473 static int
474 get_breakpoint (const gchar * s, const gint indent, const gint limit)
475 {
476
477         if (g_utf8_validate (s, -1, NULL)) {
478                 return get_breakpoint_utf8 (s, indent, limit);
479         } else {                /* assume ASCII */
480                 //g_warning("invalid UTF-8 in msg");
481                 return get_breakpoint_ascii (s, indent, limit);
482         }
483 }
484
485 static gchar *
486 cite (const time_t sent_date, const gchar *from)
487 {
488         gchar sent_str[101];
489
490         /* format sent_date */
491         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
492         return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
493 }
494
495
496 static gchar *
497 modest_text_utils_quote_plain_text (const gchar *text, 
498                                     const gchar *cite, 
499                                     int limit)
500 {
501         const gchar *iter;
502         gint indent, breakpoint, rem_indent = 0;
503         GString *q, *l, *remaining;
504         gsize len;
505
506         /* remaining will store the rest of the line if we have to break it */
507         q = g_string_new (cite);
508         remaining = g_string_new ("");
509
510         iter = text;
511         len = strlen(text);
512         do {
513                 l = get_next_line (text, len, iter);
514                 iter = iter + l->len + 1;
515                 indent = get_indent_level (l->str);
516                 unquote_line (l);
517
518                 if (remaining->len) {
519                         if (l->len && indent == rem_indent) {
520                                 g_string_prepend (l, " ");
521                                 g_string_prepend (l, remaining->str);
522                         } else {
523                                 do {
524                                         breakpoint =
525                                                 get_breakpoint (remaining->     str,
526                                                                 rem_indent,
527                                                                 limit);
528                                         append_quoted (q, rem_indent,
529                                                        remaining, breakpoint);
530                                         g_string_erase (remaining, 0,
531                                                         breakpoint);
532                                         if (remaining->str[0] == ' ') {
533                                                 g_string_erase (remaining, 0,
534                                                                 1);
535                                         }
536                                 } while (remaining->len);
537                         }
538                 }
539                 g_string_free (remaining, TRUE);
540                 breakpoint = get_breakpoint (l->str, indent, limit);
541                 remaining = g_string_new (l->str + breakpoint);
542                 if (remaining->str[0] == ' ') {
543                         g_string_erase (remaining, 0, 1);
544                 }
545                 rem_indent = indent;
546                 append_quoted (q, indent, l, breakpoint);
547                 g_string_free (l, TRUE);
548         } while ((iter < text + len) || (remaining->str[0]));
549
550         return g_string_free (q, FALSE);
551 }
552
553 static gchar*
554 modest_text_utils_quote_html (const gchar *text, 
555                               const gchar *cite, 
556                               int limit)
557 {
558         const gchar *format = \
559                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
560                 "<html>\n" \
561                 "<body>\n" \
562                 "%s" \
563                 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
564                 "</body>\n" \
565                 "</html>\n";
566
567         return g_strdup_printf (format, cite, text);
568 }
569
570 static gint 
571 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
572 {
573         return match2->offset - match1->offset;
574 }
575
576
577
578 /*
579  * check if the match is inside an existing match... */
580 static void
581 chk_partial_match (const url_match_t *match, guint* offset)
582 {
583         if (*offset >= match->offset && *offset < match->offset + match->len)
584                 *offset = -1;
585 }
586
587 static GSList*
588 get_url_matches (GString *txt)
589 {
590         regmatch_t rm;
591         guint rv, i, offset = 0;
592         GSList *match_list = NULL;
593
594         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
595         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
596
597         /* initalize the regexps */
598         for (i = 0; i != pattern_num; ++i) {
599                 patterns[i].preg = g_new0 (regex_t,1);
600                 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
601                                   REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
602         }
603         /* find all the matches */
604         for (i = 0; i != pattern_num; ++i) {
605                 offset     = 0; 
606                 while (1) {
607                         int test_offset;
608                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
609                                 g_assert (rv == REG_NOMATCH); /* this should not happen */
610                                 break; /* try next regexp */ 
611                         }
612                         if (rm.rm_so == -1)
613                                 break;
614
615                         /* FIXME: optimize this */
616                         /* to avoid partial matches on something that was already found... */
617                         /* check_partial_match will put -1 in the data ptr if that is the case */
618                         test_offset = offset + rm.rm_so;
619                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
620                         
621                         /* make a list of our matches (<offset, len, prefix> tupels)*/
622                         if (test_offset != -1) {
623                                 url_match_t *match = g_new (url_match_t,1);
624                                 match->offset = offset + rm.rm_so;
625                                 match->len    = rm.rm_eo - rm.rm_so;
626                                 match->prefix = patterns[i].prefix;
627                                 match_list = g_slist_prepend (match_list, match);
628                         }
629                         offset += rm.rm_eo;
630                 }
631         }
632
633         for (i = 0; i != pattern_num; ++i) {
634                 regfree (patterns[i].preg);
635                 g_free  (patterns[i].preg);
636         } /* don't free patterns itself -- it's static */
637         
638         /* now sort the list, so the matches are in reverse order of occurence.
639          * that way, we can do the replacements starting from the end, so we don't need
640          * to recalculate the offsets
641          */
642         match_list = g_slist_sort (match_list,
643                                    (GCompareFunc)cmp_offsets_reverse); 
644         return match_list;      
645 }
646
647
648
649 static void
650 hyperlinkify_plain_text (GString *txt)
651 {
652         GSList *cursor;
653         GSList *match_list = get_url_matches (txt);
654
655         /* we will work backwards, so the offsets stay valid */
656         for (cursor = match_list; cursor; cursor = cursor->next) {
657
658                 url_match_t *match = (url_match_t*) cursor->data;
659                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
660                 gchar *repl = NULL; /* replacement  */
661
662                 /* the prefix is NULL: use the one that is already there */
663                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
664                                         match->prefix ? match->prefix : "", 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_free (cursor->data);  
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 static GHashTable*
767 get_display_date_cache (void)
768 {
769         TnyPlatformFactory *fakt;
770         ModestCacheMgr     *cache_mgr;
771
772         fakt = modest_tny_platform_factory_get_instance ();
773         
774         cache_mgr =  modest_tny_platform_factory_get_cache_mgr_instance
775                 (MODEST_TNY_PLATFORM_FACTORY(fakt));
776         
777         return modest_cache_mgr_get_cache (cache_mgr,
778                                            MODEST_CACHE_MGR_CACHE_TYPE_DATE_STRING);
779 }
780
781
782
783 const gchar*
784 modest_text_utils_get_display_date (time_t date)
785 {
786         static GHashTable *date_cache = NULL;
787
788         time_t now;
789         const guint BUF_SIZE = 64; 
790         gchar date_buf[BUF_SIZE];  
791         gchar now_buf [BUF_SIZE];  
792         gchar* cached_val;
793         
794         if (G_UNLIKELY(!date_cache))
795                 date_cache = get_display_date_cache ();
796         
797         cached_val = g_hash_table_lookup (date_cache, &date);
798         if (cached_val)
799                 return cached_val;
800                                                     
801         now = time (NULL);
802         
803         /* get today's date */
804         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
805         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x",  now);
806         /* today */
807
808         /* if this is today, get the time instead of the date */
809         if (strcmp (date_buf, now_buf) == 0)
810                 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
811
812         cached_val = g_strdup(date_buf);
813         g_hash_table_insert (date_cache, (gpointer)&date, (gpointer)cached_val);
814         
815         return cached_val;
816 }
817
818 gboolean 
819 modest_text_utils_validate_email_address (const gchar *email_address)
820 {
821         int count = 0;
822         const gchar *c, *domain;
823         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
824
825         /* first we validate the name portion (name@domain) */
826         for (c = email_address;  *c;  c++) {
827                 if (*c == '\"' && 
828                     (c == email_address || 
829                      *(c - 1) == '.' || 
830                      *(c - 1) == '\"')) {
831                         while (*++c) {
832                                 if (*c == '\"') 
833                                         break;
834                                 if (*c == '\\' && (*++c == ' ')) 
835                                         continue;
836                                 if (*c <= ' ' || *c >= 127) 
837                                         return FALSE;
838                         }
839                         if (!*c++) 
840                                 return FALSE;
841                         if (*c == '@') 
842                                 break;
843                         if (*c != '.') 
844                                 return FALSE;
845                         continue;
846                 }
847                 if (*c == '@') 
848                         break;
849                 if (*c <= ' ' || *c >= 127) 
850                         return FALSE;
851                 if (strchr(rfc822_specials, *c)) 
852                         return FALSE;
853         }
854         if (c == email_address || *(c - 1) == '.') 
855                 return FALSE;
856
857         /* next we validate the domain portion (name@domain) */
858         if (!*(domain = ++c)) 
859                 return FALSE;
860         do {
861                 if (*c == '.') {
862                         if (c == domain || *(c - 1) == '.') 
863                                 return FALSE;
864                         count++;
865                 }
866                 if (*c <= ' ' || *c >= 127) 
867                         return FALSE;
868                 if (strchr(rfc822_specials, *c)) 
869                         return FALSE;
870         } while (*++c);
871
872         return (count >= 1) ? TRUE : FALSE;
873 }
874
875
876
877
878 gchar *
879 modest_text_utils_get_display_size (guint size)
880 {
881         const guint KB=1024;
882         const guint MB=1024 * KB;
883         const guint GB=1024 * MB;
884         const guint TB=1024 * GB;
885
886         if (size < KB)
887                 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
888         else if (size < MB)
889                 return g_strdup_printf (_("%d Kb"), size / KB);
890         else if (size < GB)
891                 return g_strdup_printf (_("%d Mb"), size / MB);
892         else if (size < TB)
893                 return g_strdup_printf (_("%d Gb"), size/ GB);
894         else
895                 return g_strdup_printf (_("Very big"));
896 }