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