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