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