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