* use the slice allocator
[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_slice_new0 (regex_t);
604
605                 /* this should not happen */
606                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
607                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
608         }
609         /* find all the matches */
610         for (i = 0; i != pattern_num; ++i) {
611                 offset     = 0; 
612                 while (1) {
613                         int test_offset;
614                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
615                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
616                                 break; /* try next regexp */ 
617                         }
618                         if (rm.rm_so == -1)
619                                 break;
620
621                         /* FIXME: optimize this */
622                         /* to avoid partial matches on something that was already found... */
623                         /* check_partial_match will put -1 in the data ptr if that is the case */
624                         test_offset = offset + rm.rm_so;
625                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
626                         
627                         /* make a list of our matches (<offset, len, prefix> tupels)*/
628                         if (test_offset != -1) {
629                                 url_match_t *match = g_slice_new (url_match_t);
630                                 match->offset = offset + rm.rm_so;
631                                 match->len    = rm.rm_eo - rm.rm_so;
632                                 match->prefix = patterns[i].prefix;
633                                 match_list = g_slist_prepend (match_list, match);
634                         }
635                         offset += rm.rm_eo;
636                 }
637         }
638
639         for (i = 0; i != pattern_num; ++i) {
640                 regfree (patterns[i].preg);
641                 g_slice_free  (regex_t, patterns[i].preg);
642         } /* don't free patterns itself -- it's static */
643         
644         /* now sort the list, so the matches are in reverse order of occurence.
645          * that way, we can do the replacements starting from the end, so we don't need
646          * to recalculate the offsets
647          */
648         match_list = g_slist_sort (match_list,
649                                    (GCompareFunc)cmp_offsets_reverse); 
650         return match_list;      
651 }
652
653
654
655 static void
656 hyperlinkify_plain_text (GString *txt)
657 {
658         GSList *cursor;
659         GSList *match_list = get_url_matches (txt);
660
661         /* we will work backwards, so the offsets stay valid */
662         for (cursor = match_list; cursor; cursor = cursor->next) {
663
664                 url_match_t *match = (url_match_t*) cursor->data;
665                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
666                 gchar *repl = NULL; /* replacement  */
667
668                 /* the prefix is NULL: use the one that is already there */
669                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
670                                         match->prefix ? match->prefix : "", url, url);
671
672                 /* replace the old thing with our hyperlink
673                  * replacement thing */
674                 g_string_erase  (txt, match->offset, match->len);
675                 g_string_insert (txt, match->offset, repl);
676                 
677                 g_free (url);
678                 g_free (repl);
679
680                 g_slice_free (url_match_t, match);      
681         }
682         
683         g_slist_free (match_list);
684 }
685
686
687
688 gchar*
689 modest_text_utils_get_display_address (gchar *address)
690 {
691         gchar *cursor;
692         
693         if (!address)
694                 return NULL;
695
696         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
697
698         g_strchug (address); /* remove leading whitespace */
699
700         /*  <email@address> from display name */
701         cursor = g_strstr_len (address, strlen(address), "<");
702         if (cursor == address) /* there's nothing else? leave it */
703                 return address;
704         if (cursor) 
705                 cursor[0]='\0';
706
707         /* remove (bla bla) from display name */
708         cursor = g_strstr_len (address, strlen(address), "(");
709         if (cursor == address) /* there's nothing else? leave it */
710                 return address;
711         if (cursor) 
712                 cursor[0]='\0';
713
714         g_strchomp (address); /* remove trailing whitespace */
715
716         return address;
717 }
718
719
720
721 gint 
722 modest_text_utils_get_subject_prefix_len (const gchar *sub)
723 {
724         gint i;
725         static const gchar* prefix[] = {
726                 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
727         };
728                 
729         if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
730                 return 0;
731
732         i = 0;
733         
734         while (prefix[i]) {
735                 if (g_str_has_prefix(sub, prefix[i])) {
736                         int prefix_len = strlen(prefix[i]); 
737                         if (sub[prefix_len] == ' ')
738                                 ++prefix_len; /* ignore space after prefix as well */
739                         return prefix_len; 
740                 }
741                 ++i;
742         }
743         return 0;
744 }
745
746
747 gint
748 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
749 {
750         gint result = 0;
751         gchar *n1, *n2;
752
753         /* work even when s1 and/or s2 == NULL */
754         if (G_UNLIKELY(s1 == s2))
755                 return 0;
756
757         /* if it's not case sensitive */
758         if (!insensitive)
759                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
760         
761         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
762         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
763         
764         result = strcmp (n1, n2);
765
766         g_free (n1);
767         g_free (n2);
768         
769         return result;
770 }
771
772 static GHashTable*
773 get_display_date_cache (void)
774 {
775         return modest_cache_mgr_get_cache (modest_runtime_get_cache_mgr (),
776                                            MODEST_CACHE_MGR_CACHE_TYPE_DATE_STRING);
777 }
778
779
780
781 const gchar*
782 modest_text_utils_get_display_date (time_t date)
783 {
784         static GHashTable *date_cache = NULL;
785
786         time_t now;
787         const guint BUF_SIZE = 64; 
788         gchar date_buf[BUF_SIZE];  
789         gchar now_buf [BUF_SIZE];  
790         gchar* cached_val;
791         
792         if (G_UNLIKELY(!date_cache))
793                 date_cache = get_display_date_cache ();
794         
795         cached_val = g_hash_table_lookup (date_cache, &date);
796         if (cached_val)
797                 return cached_val;
798                                                     
799         now = time (NULL);
800         
801         /* get today's date */
802         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
803         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x",  now);
804         /* today */
805
806         /* if this is today, get the time instead of the date */
807         if (strcmp (date_buf, now_buf) == 0)
808                 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
809
810         cached_val = g_strdup(date_buf);
811         g_hash_table_insert (date_cache, (gpointer)&date, (gpointer)cached_val);
812         
813         return cached_val;
814 }
815
816 gboolean 
817 modest_text_utils_validate_email_address (const gchar *email_address)
818 {
819         int count = 0;
820         const gchar *c, *domain;
821         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
822
823         /* first we validate the name portion (name@domain) */
824         for (c = email_address;  *c;  c++) {
825                 if (*c == '\"' && 
826                     (c == email_address || 
827                      *(c - 1) == '.' || 
828                      *(c - 1) == '\"')) {
829                         while (*++c) {
830                                 if (*c == '\"') 
831                                         break;
832                                 if (*c == '\\' && (*++c == ' ')) 
833                                         continue;
834                                 if (*c <= ' ' || *c >= 127) 
835                                         return FALSE;
836                         }
837                         if (!*c++) 
838                                 return FALSE;
839                         if (*c == '@') 
840                                 break;
841                         if (*c != '.') 
842                                 return FALSE;
843                         continue;
844                 }
845                 if (*c == '@') 
846                         break;
847                 if (*c <= ' ' || *c >= 127) 
848                         return FALSE;
849                 if (strchr(rfc822_specials, *c)) 
850                         return FALSE;
851         }
852         if (c == email_address || *(c - 1) == '.') 
853                 return FALSE;
854
855         /* next we validate the domain portion (name@domain) */
856         if (!*(domain = ++c)) 
857                 return FALSE;
858         do {
859                 if (*c == '.') {
860                         if (c == domain || *(c - 1) == '.') 
861                                 return FALSE;
862                         count++;
863                 }
864                 if (*c <= ' ' || *c >= 127) 
865                         return FALSE;
866                 if (strchr(rfc822_specials, *c)) 
867                         return FALSE;
868         } while (*++c);
869
870         return (count >= 1) ? TRUE : FALSE;
871 }
872
873
874
875
876 gchar *
877 modest_text_utils_get_display_size (guint size)
878 {
879         const guint KB=1024;
880         const guint MB=1024 * KB;
881         const guint GB=1024 * MB;
882         const guint TB=1024 * GB;
883
884         if (size < KB)
885                 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
886         else if (size < MB)
887                 return g_strdup_printf (_("%d Kb"), size / KB);
888         else if (size < GB)
889                 return g_strdup_printf (_("%d Mb"), size / MB);
890         else if (size < TB)
891                 return g_strdup_printf (_("%d Gb"), size/ GB);
892         else
893                 return g_strdup_printf (_("Very big"));
894 }