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