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