d1cc2f66905a68696325a971a43b0c578d394cf5
[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 static gchar*   get_email_from_address (const gchar *address);
109
110
111 /* ******************************************************************* */
112 /* ************************* PUBLIC FUNCTIONS ************************ */
113 /* ******************************************************************* */
114
115 gchar *
116 modest_text_utils_quote (const gchar *text, 
117                          const gchar *content_type,
118                          const gchar *signature,
119                          const gchar *from,
120                          const time_t sent_date, 
121                          int limit)
122 {
123         gchar *retval, *cited;
124
125         g_return_val_if_fail (text, NULL);
126         g_return_val_if_fail (content_type, NULL);
127
128         cited = cite (sent_date, from);
129         
130         if (content_type && strcmp (content_type, "text/html") == 0)
131                 /* TODO: extract the <body> of the HTML and pass it to
132                    the function */
133                 retval = modest_text_utils_quote_html (text, cited, limit);
134         else
135                 retval = modest_text_utils_quote_plain_text (text, cited, limit);
136         
137         g_free (cited);
138
139         return retval;
140 }
141
142
143 gchar *
144 modest_text_utils_cite (const gchar *text,
145                         const gchar *content_type,
146                         const gchar *signature,
147                         const gchar *from,
148                         time_t sent_date)
149 {
150         gchar *tmp, *retval;
151         gchar *tmp_sig;
152
153         g_return_val_if_fail (text, NULL);
154         g_return_val_if_fail (content_type, NULL);
155
156         if (!signature)
157                 tmp_sig = g_strdup ("");
158         else if (!strcmp(content_type, "text/html")) {
159                 tmp_sig = modest_text_utils_convert_to_html_body(signature);
160         } else {
161                 tmp_sig = g_strdup (signature);
162         }
163
164         tmp = cite (sent_date, from);
165         retval = g_strdup_printf ("%s%s%s\n", tmp_sig, tmp, text);
166         g_free (tmp_sig);
167         g_free (tmp);
168
169         return retval;
170 }
171
172 gchar * 
173 modest_text_utils_inline (const gchar *text,
174                           const gchar *content_type,
175                           const gchar *signature,
176                           const gchar *from,
177                           time_t sent_date,
178                           const gchar *to,
179                           const gchar *subject)
180 {
181         gchar sent_str[101];
182         gchar *formatted_signature;
183         const gchar *plain_format = "%s%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
184         const gchar *html_format = \
185                 "%s%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
186                 "<tr><td>%s</td><td>%s</td></tr>\n" \
187                 "<tr><td>%s</td><td>%s</td></tr>\n" \
188                 "<tr><td>%s</td><td>%s</td></tr>\n" \
189                 "<tr><td>%s</td><td>%s</td></tr>\n" \
190                 "<br><br>%s";
191         const gchar *format;
192
193         g_return_val_if_fail (text, NULL);
194         g_return_val_if_fail (content_type, NULL);
195         g_return_val_if_fail (text, NULL);
196         
197         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
198
199         if (!strcmp (content_type, "text/html"))
200                 /* TODO: extract the <body> of the HTML and pass it to
201                    the function */
202                 format = html_format;
203         else
204                 format = plain_format;
205
206         if (signature != NULL) {
207                 if (!strcmp (content_type, "text/html")) {
208                         formatted_signature = g_strconcat (signature, "<br/>", NULL);
209                 } else {
210                         formatted_signature = g_strconcat (signature, "\n", NULL);
211                 }
212         } else {
213                 formatted_signature = "";
214         }
215
216         return g_strdup_printf (format, formatted_signature, 
217                                 FORWARD_STRING,
218                                 FROM_STRING, (from) ? from : EMPTY_STRING,
219                                 SENT_STRING, sent_str,
220                                 TO_STRING, (to) ? to : EMPTY_STRING,
221                                 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
222                                 text);
223 }
224
225 /* just to prevent warnings:
226  * warning: `%x' yields only last 2 digits of year in some locales
227  */
228 gsize
229 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
230 {
231         struct tm tm;
232
233         /* does not work on old maemo glib: 
234          *   g_date_set_time_t (&date, timet);
235          */
236         localtime_r (&timet, &tm);
237
238         return strftime(s, max, fmt, &tm);
239 }
240
241 gchar *
242 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
243 {
244         gchar *tmp;
245
246         g_return_val_if_fail (prefix, NULL);
247         
248         if (!subject)
249                 return g_strdup (prefix);
250
251         tmp = g_strchug (g_strdup (subject));
252
253         if (!strncmp (tmp, prefix, strlen (prefix))) {
254                 return tmp;
255         } else {
256                 g_free (tmp);
257                 return g_strdup_printf ("%s %s", prefix, subject);
258         }
259 }
260
261 gchar*
262 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
263 {
264         gchar *dup, *token, *ptr, *result;
265         GString *filtered_emails;
266         gchar *email_address;
267
268         g_return_val_if_fail (address_list, NULL);
269
270         if (!address)
271                 return g_strdup (address_list);
272
273         email_address = get_email_from_address (address);
274         
275         /* search for substring */
276         if (!strstr ((const char *) address_list, (const char *) email_address)) {
277                 g_free (email_address);
278                 return g_strdup (address_list);
279         }
280
281         dup = g_strdup (address_list);
282         filtered_emails = g_string_new (NULL);
283         
284         token = strtok_r (dup, ",", &ptr);
285
286         while (token != NULL) {
287                 /* Add to list if not found */
288                 if (!strstr ((const char *) token, (const char *) email_address)) {
289                         if (filtered_emails->len == 0)
290                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
291                         else
292                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
293                 }
294                 token = strtok_r (NULL, ",", &ptr);
295         }
296         result = filtered_emails->str;
297
298         /* Clean */
299         g_free (email_address);
300         g_free (dup);
301         g_string_free (filtered_emails, FALSE);
302
303         return result;
304 }
305
306 static void
307 modest_text_utils_convert_buffer_to_html (GString *html, const gchar *data)
308 {
309         guint            i;
310         gboolean        space_seen = FALSE;
311         gsize           len;
312
313         len = strlen (data);
314
315         /* replace with special html chars where needed*/
316         for (i = 0; i != len; ++i)  {
317                 char kar = data[i];
318                 
319                 if (space_seen && kar != ' ') {
320                         g_string_append_c (html, ' ');
321                         space_seen = FALSE;
322                 }
323                 
324                 switch (kar) {
325                 case 0:  break; /* ignore embedded \0s */       
326                 case '<'  : g_string_append (html, "&lt;");   break;
327                 case '>'  : g_string_append (html, "&gt;");   break;
328                 case '&'  : g_string_append (html, "&amp;");  break;
329                 case '"'  : g_string_append (html, "&quot;");  break;
330                 case '\'' : g_string_append (html, "&apos;"); break;
331                 case '\n' : g_string_append (html, "<br>\n");  break;
332                 case '\t' : g_string_append (html, "&nbsp;&nbsp;&nbsp; "); break; /* note the space at the end*/
333                 case ' ':
334                         if (space_seen) { /* second space in a row */
335                                 g_string_append (html, "&nbsp ");
336                                 space_seen = FALSE;
337                         } else
338                                 space_seen = TRUE;
339                         break;
340                 default:
341                         g_string_append_c (html, kar);
342                 }
343         }
344 }
345
346 gchar*
347 modest_text_utils_convert_to_html (const gchar *data)
348 {
349         GString         *html;      
350         gsize           len;
351         
352         if (!data)
353                 return NULL;
354
355         len = strlen (data);
356         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
357
358         g_string_append_printf (html,
359                                 "<html><head>"
360                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
361                                 "</head>"
362                                 "<body>");
363
364         modest_text_utils_convert_buffer_to_html (html, data);
365         
366         g_string_append (html, "</body></html>");
367         hyperlinkify_plain_text (html);
368
369         return g_string_free (html, FALSE);
370 }
371
372 gchar *
373 modest_text_utils_convert_to_html_body (const gchar *data)
374 {
375         GString         *html;      
376         gsize           len;
377         
378         if (!data)
379                 return NULL;
380
381         len = strlen (data);
382         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
383
384         modest_text_utils_convert_buffer_to_html (html, data);
385
386         hyperlinkify_plain_text (html);
387
388         return g_string_free (html, FALSE);
389 }
390
391 void
392 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
393 {
394         gchar *current, *start, *last_blank;
395         gint start_offset = 0, current_offset = 0;
396
397         g_return_if_fail (start_indexes != NULL);
398         g_return_if_fail (end_indexes != NULL);
399
400         start = (gchar *) addresses;
401         current = start;
402         last_blank = start;
403
404         while (*current != '\0') {
405                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
406                         start = g_utf8_next_char (start);
407                         start_offset++;
408                         last_blank = current;
409                 } else if ((*current == ',')||(*current == ';')) {
410                         gint *start_index, *end_index;
411                         start_index = g_new0(gint, 1);
412                         end_index = g_new0(gint, 1);
413                         *start_index = start_offset;
414                         *end_index = current_offset;
415                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
416                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
417                         start = g_utf8_next_char (current);
418                         start_offset = current_offset + 1;
419                         last_blank = start;
420                 } else if (*current == '"') {
421                         current = g_utf8_next_char (current);
422                         current_offset ++;
423                         while ((*current != '"')&&(*current != '\0')) {
424                                 current = g_utf8_next_char (current);
425                                 current_offset ++;
426                         }
427                 }
428                                 
429                 current = g_utf8_next_char (current);
430                 current_offset ++;
431         }
432
433         if (start != current) {
434                         gint *start_index, *end_index;
435                         start_index = g_new0(gint, 1);
436                         end_index = g_new0(gint, 1);
437                         *start_index = start_offset;
438                         *end_index = current_offset;
439                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
440                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
441         }
442         
443         *start_indexes = g_slist_reverse (*start_indexes);
444         *end_indexes = g_slist_reverse (*end_indexes);
445
446         return;
447 }
448
449 GSList *
450 modest_text_utils_split_addresses_list (const gchar *addresses)
451 {
452         gchar *current, *start, *last_blank;
453         GSList *result = NULL;
454
455         start = (gchar *) addresses;
456         current = start;
457         last_blank = start;
458
459         while (*current != '\0') {
460                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
461                         start = g_utf8_next_char (start);
462                         last_blank = current;
463                 } else if ((*current == ',')||(*current == ';')) {
464                         gchar *new_address = NULL;
465                         new_address = g_strndup (start, current - last_blank);
466                         result = g_slist_prepend (result, new_address);
467                         start = g_utf8_next_char (current);
468                         last_blank = start;
469                 } else if (*current == '\"') {
470                         if (current == start) {
471                                 current = g_utf8_next_char (current);
472                                 start = g_utf8_next_char (start);
473                         }
474                         while ((*current != '\"')&&(*current != '\0'))
475                                 current = g_utf8_next_char (current);
476                 }
477                                 
478                 current = g_utf8_next_char (current);
479         }
480
481         if (start != current) {
482                 gchar *new_address = NULL;
483                 new_address = g_strndup (start, current - last_blank);
484                 result = g_slist_prepend (result, new_address);
485         }
486
487         result = g_slist_reverse (result);
488         return result;
489
490 }
491
492 void
493 modest_text_utils_address_range_at_position (const gchar *recipients_list,
494                                              gint position,
495                                              gint *start,
496                                              gint *end)
497 {
498         gchar *current = NULL;
499         gint range_start = 0;
500         gint range_end = 0;
501         gint index;
502         gboolean is_quoted = FALSE;
503
504         index = 0;
505         for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
506                 gunichar c = g_utf8_get_char (current);
507
508                 if ((c == ',') && (!is_quoted)) {
509                         if (index < position) {
510                                 range_start = index + 1;
511                         } else {
512                                 break;
513                         }
514                 } else if (c == '\"') {
515                         is_quoted = !is_quoted;
516                 } else if ((c == ' ') &&(range_start == index)) {
517                         range_start ++;
518                 }
519                 index ++;
520                 range_end = index;
521         }
522
523         if (start)
524                 *start = range_start;
525         if (end)
526                 *end = range_end;
527 }
528
529
530 /* ******************************************************************* */
531 /* ************************* UTILIY FUNCTIONS ************************ */
532 /* ******************************************************************* */
533
534 static GString *
535 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
536 {
537         GString *gs;
538         const gchar *i0;
539         
540         if (iter > b + blen)
541                 return g_string_new("");
542         
543         i0 = iter;
544         while (iter[0]) {
545                 if (iter[0] == '\n')
546                         break;
547                 iter++;
548         }
549         gs = g_string_new_len (i0, iter - i0);
550         return gs;
551 }
552 static int
553 get_indent_level (const char *l)
554 {
555         int indent = 0;
556
557         while (l[0]) {
558                 if (l[0] == '>') {
559                         indent++;
560                         if (l[1] == ' ') {
561                                 l++;
562                         }
563                 } else {
564                         break;
565                 }
566                 l++;
567
568         }
569
570         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
571          *      stops reformatting.
572          */
573         if (strcmp (l, "-- ") == 0) {
574                 return -1 - indent;
575         } else {
576                 return indent;
577         }
578 }
579
580 static void
581 unquote_line (GString * l)
582 {
583         gchar *p;
584
585         p = l->str;
586         while (p[0]) {
587                 if (p[0] == '>') {
588                         if (p[1] == ' ') {
589                                 p++;
590                         }
591                 } else {
592                         break;
593                 }
594                 p++;
595         }
596         g_string_erase (l, 0, p - l->str);
597 }
598
599 static void
600 append_quoted (GString * buf, int indent, const GString * str,
601                const int cutpoint)
602 {
603         int i;
604
605         indent = indent < 0 ? abs (indent) - 1 : indent;
606         for (i = 0; i <= indent; i++) {
607                 g_string_append (buf, "> ");
608         }
609         if (cutpoint > 0) {
610                 g_string_append_len (buf, str->str, cutpoint);
611         } else {
612                 g_string_append (buf, str->str);
613         }
614         g_string_append (buf, "\n");
615 }
616
617 static int
618 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
619 {
620         gint index = 0;
621         const gchar *pos, *last;
622         gunichar *uni;
623
624         indent = indent < 0 ? abs (indent) - 1 : indent;
625
626         last = NULL;
627         pos = s;
628         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
629         while (pos[0]) {
630                 if ((index + 2 * indent > limit) && last) {
631                         g_free (uni);
632                         return last - s;
633                 }
634                 if (g_unichar_isspace (uni[index])) {
635                         last = pos;
636                 }
637                 pos = g_utf8_next_char (pos);
638                 index++;
639         }
640         g_free (uni);
641         return strlen (s);
642 }
643
644 static int
645 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
646 {
647         gint i, last;
648
649         last = strlen (s);
650         if (last + 2 * indent < limit)
651                 return last;
652
653         for (i = strlen (s); i > 0; i--) {
654                 if (s[i] == ' ') {
655                         if (i + 2 * indent <= limit) {
656                                 return i;
657                         } else {
658                                 last = i;
659                         }
660                 }
661         }
662         return last;
663 }
664
665 static int
666 get_breakpoint (const gchar * s, const gint indent, const gint limit)
667 {
668
669         if (g_utf8_validate (s, -1, NULL)) {
670                 return get_breakpoint_utf8 (s, indent, limit);
671         } else {                /* assume ASCII */
672                 //g_warning("invalid UTF-8 in msg");
673                 return get_breakpoint_ascii (s, indent, limit);
674         }
675 }
676
677 static gchar *
678 cite (const time_t sent_date, const gchar *from)
679 {
680         gchar sent_str[101];
681
682         /* format sent_date */
683         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
684         return g_strdup_printf (N_("On %s, %s wrote:\n"), 
685                                 sent_str, 
686                                 (from) ? from : EMPTY_STRING);
687 }
688
689
690 static gchar *
691 modest_text_utils_quote_plain_text (const gchar *text, 
692                                     const gchar *cite, 
693                                     int limit)
694 {
695         const gchar *iter;
696         gint indent, breakpoint, rem_indent = 0;
697         GString *q, *l, *remaining;
698         gsize len;
699
700         /* remaining will store the rest of the line if we have to break it */
701         q = g_string_new (cite);
702         remaining = g_string_new ("");
703
704         iter = text;
705         len = strlen(text);
706         do {
707                 l = get_next_line (text, len, iter);
708                 iter = iter + l->len + 1;
709                 indent = get_indent_level (l->str);
710                 unquote_line (l);
711
712                 if (remaining->len) {
713                         if (l->len && indent == rem_indent) {
714                                 g_string_prepend (l, " ");
715                                 g_string_prepend (l, remaining->str);
716                         } else {
717                                 do {
718                                         breakpoint =
719                                                 get_breakpoint (remaining->str,
720                                                                 rem_indent,
721                                                                 limit);
722                                         append_quoted (q, rem_indent,
723                                                        remaining, breakpoint);
724                                         g_string_erase (remaining, 0,
725                                                         breakpoint);
726                                         if (remaining->str[0] == ' ') {
727                                                 g_string_erase (remaining, 0,
728                                                                 1);
729                                         }
730                                 } while (remaining->len);
731                         }
732                 }
733                 g_string_free (remaining, TRUE);
734                 breakpoint = get_breakpoint (l->str, indent, limit);
735                 remaining = g_string_new (l->str + breakpoint);
736                 if (remaining->str[0] == ' ') {
737                         g_string_erase (remaining, 0, 1);
738                 }
739                 rem_indent = indent;
740                 append_quoted (q, indent, l, breakpoint);
741                 g_string_free (l, TRUE);
742         } while ((iter < text + len) || (remaining->str[0]));
743
744         return g_string_free (q, FALSE);
745 }
746
747 static gchar*
748 modest_text_utils_quote_html (const gchar *text, 
749                               const gchar *cite, 
750                               int limit)
751 {
752         const gchar *format = \
753                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
754                 "<html>\n" \
755                 "<body>\n" \
756                 "%s" \
757                 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
758                 "</body>\n" \
759                 "</html>\n";
760
761         return g_strdup_printf (format, cite, text);
762 }
763
764 static gint 
765 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
766 {
767         return match2->offset - match1->offset;
768 }
769
770
771
772 /*
773  * check if the match is inside an existing match... */
774 static void
775 chk_partial_match (const url_match_t *match, guint* offset)
776 {
777         if (*offset >= match->offset && *offset < match->offset + match->len)
778                 *offset = -1;
779 }
780
781 static GSList*
782 get_url_matches (GString *txt)
783 {
784         regmatch_t rm;
785         guint rv, i, offset = 0;
786         GSList *match_list = NULL;
787
788         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
789         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
790
791         /* initalize the regexps */
792         for (i = 0; i != pattern_num; ++i) {
793                 patterns[i].preg = g_slice_new0 (regex_t);
794
795                 /* this should not happen */
796                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
797                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
798         }
799         /* find all the matches */
800         for (i = 0; i != pattern_num; ++i) {
801                 offset     = 0; 
802                 while (1) {
803                         int test_offset;
804                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
805                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
806                                 break; /* try next regexp */ 
807                         }
808                         if (rm.rm_so == -1)
809                                 break;
810
811                         /* FIXME: optimize this */
812                         /* to avoid partial matches on something that was already found... */
813                         /* check_partial_match will put -1 in the data ptr if that is the case */
814                         test_offset = offset + rm.rm_so;
815                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
816                         
817                         /* make a list of our matches (<offset, len, prefix> tupels)*/
818                         if (test_offset != -1) {
819                                 url_match_t *match = g_slice_new (url_match_t);
820                                 match->offset = offset + rm.rm_so;
821                                 match->len    = rm.rm_eo - rm.rm_so;
822                                 match->prefix = patterns[i].prefix;
823                                 match_list = g_slist_prepend (match_list, match);
824                         }
825                         offset += rm.rm_eo;
826                 }
827         }
828
829         for (i = 0; i != pattern_num; ++i) {
830                 regfree (patterns[i].preg);
831                 g_slice_free  (regex_t, patterns[i].preg);
832         } /* don't free patterns itself -- it's static */
833         
834         /* now sort the list, so the matches are in reverse order of occurence.
835          * that way, we can do the replacements starting from the end, so we don't need
836          * to recalculate the offsets
837          */
838         match_list = g_slist_sort (match_list,
839                                    (GCompareFunc)cmp_offsets_reverse); 
840         return match_list;      
841 }
842
843
844
845 static void
846 hyperlinkify_plain_text (GString *txt)
847 {
848         GSList *cursor;
849         GSList *match_list = get_url_matches (txt);
850
851         /* we will work backwards, so the offsets stay valid */
852         for (cursor = match_list; cursor; cursor = cursor->next) {
853
854                 url_match_t *match = (url_match_t*) cursor->data;
855                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
856                 gchar *repl = NULL; /* replacement  */
857
858                 /* the prefix is NULL: use the one that is already there */
859                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
860                                         match->prefix ? match->prefix : EMPTY_STRING, 
861                                         url, url);
862
863                 /* replace the old thing with our hyperlink
864                  * replacement thing */
865                 g_string_erase  (txt, match->offset, match->len);
866                 g_string_insert (txt, match->offset, repl);
867                 
868                 g_free (url);
869                 g_free (repl);
870
871                 g_slice_free (url_match_t, match);      
872         }
873         
874         g_slist_free (match_list);
875 }
876
877
878
879 gchar*
880 modest_text_utils_get_display_address (gchar *address)
881 {
882         gchar *cursor;
883         
884         if (!address)
885                 return NULL;
886         
887         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
888         
889         g_strchug (address); /* remove leading whitespace */
890
891         /*  <email@address> from display name */
892         cursor = g_strstr_len (address, strlen(address), "<");
893         if (cursor == address) /* there's nothing else? leave it */
894                 return address;
895         if (cursor) 
896                 cursor[0]='\0';
897
898         /* remove (bla bla) from display name */
899         cursor = g_strstr_len (address, strlen(address), "(");
900         if (cursor == address) /* there's nothing else? leave it */
901                 return address;
902         if (cursor) 
903                 cursor[0]='\0';
904
905         g_strchomp (address); /* remove trailing whitespace */
906
907         return address;
908 }
909
910
911
912 gint 
913 modest_text_utils_get_subject_prefix_len (const gchar *sub)
914 {
915         gint i;
916         static const gchar* prefix[] = {
917                 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
918         };
919                 
920         if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
921                 return 0;
922
923         i = 0;
924         
925         while (prefix[i]) {
926                 if (g_str_has_prefix(sub, prefix[i])) {
927                         int prefix_len = strlen(prefix[i]); 
928                         if (sub[prefix_len] == ' ')
929                                 ++prefix_len; /* ignore space after prefix as well */
930                         return prefix_len; 
931                 }
932                 ++i;
933         }
934         return 0;
935 }
936
937
938 gint
939 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
940 {
941         gint result = 0;
942         gchar *n1, *n2;
943
944         /* work even when s1 and/or s2 == NULL */
945         if (G_UNLIKELY(s1 == s2))
946                 return 0;
947
948         /* if it's not case sensitive */
949         if (!insensitive)
950                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
951         
952         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
953         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
954         
955         result = strcmp (n1, n2);
956
957         g_free (n1);
958         g_free (n2);
959         
960         return result;
961 }
962
963
964 gchar*
965 modest_text_utils_get_display_date (time_t date)
966 {
967         time_t now;
968         const guint BUF_SIZE = 64; 
969         gchar date_buf[BUF_SIZE];  
970         gchar now_buf [BUF_SIZE];  
971         
972         now = time (NULL);
973
974         modest_text_utils_strftime (date_buf, BUF_SIZE, "%d/%m/%Y", date);
975         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%d/%m/%Y",  now); /* today */
976 /*      modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date); */
977 /*      modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x",  now); /\* today *\/ */
978         
979         /* if this is today, get the time instead of the date */
980         if (strcmp (date_buf, now_buf) == 0)
981                 modest_text_utils_strftime (date_buf, BUF_SIZE, "%H:%M %P", date);
982         
983         return g_strdup(date_buf);
984 }
985
986 gboolean 
987 modest_text_utils_validate_email_address (const gchar *email_address)
988 {
989         int count = 0;
990         const gchar *c = NULL, *domain = NULL;
991         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
992
993         /* first we validate the name portion (name@domain) */
994         for (c = email_address;  *c;  c++) {
995                 if (*c == '\"' && 
996                     (c == email_address || 
997                      *(c - 1) == '.' || 
998                      *(c - 1) == '\"')) {
999                         while (*++c) {
1000                                 if (*c == '\"') 
1001                                         break;
1002                                 if (*c == '\\' && (*++c == ' ')) 
1003                                         continue;
1004                                 if (*c <= ' ' || *c >= 127) 
1005                                         return FALSE;
1006                         }
1007                         if (!*c++) 
1008                                 return FALSE;
1009                         if (*c == '@') 
1010                                 break;
1011                         if (*c != '.') 
1012                                 return FALSE;
1013                         continue;
1014                 }
1015                 if (*c == '@') 
1016                         break;
1017                 if (*c <= ' ' || *c >= 127) 
1018                         return FALSE;
1019                 if (strchr(rfc822_specials, *c)) 
1020                         return FALSE;
1021         }
1022         if (c == email_address || *(c - 1) == '.') 
1023                 return FALSE;
1024
1025         /* next we validate the domain portion (name@domain) */
1026         if (!*(domain = ++c)) 
1027                 return FALSE;
1028         do {
1029                 if (*c == '.') {
1030                         if (c == domain || *(c - 1) == '.') 
1031                                 return FALSE;
1032                         count++;
1033                 }
1034                 if (*c <= ' ' || *c >= 127) 
1035                         return FALSE;
1036                 if (strchr(rfc822_specials, *c)) 
1037                         return FALSE;
1038         } while (*++c);
1039
1040         return (count >= 1) ? TRUE : FALSE;
1041 }
1042
1043 gboolean 
1044 modest_text_utils_validate_recipient (const gchar *recipient)
1045 {
1046         gchar *stripped, *current;
1047         gchar *right_part;
1048         gboolean has_error = FALSE;
1049
1050         if (modest_text_utils_validate_email_address (recipient))
1051                 return TRUE;
1052         stripped = g_strdup (recipient);
1053         stripped = g_strstrip (stripped);
1054         current = stripped;
1055
1056         if (*current == '\0') {
1057                 g_free (stripped);
1058                 return FALSE;
1059         }
1060
1061         /* quoted string */
1062         if (*current == '\"') {
1063                 current = g_utf8_next_char (current);
1064                 has_error = TRUE;
1065                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1066                         if (*current == '\\') {
1067                                 /* TODO: This causes a warning, which breaks the build, 
1068                                  * because a gchar cannot be < 0.
1069                                  * murrayc. 
1070                                 if (current[1] <0) {
1071                                         has_error = TRUE;
1072                                         break;
1073                                 }
1074                                 */
1075                         } else if (*current == '\"') {
1076                                 has_error = FALSE;
1077                                 current = g_utf8_next_char (current);
1078                                 break;
1079                         }
1080                 }
1081         } else {
1082                 has_error = TRUE;
1083                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1084                         if (*current == '<') {
1085                                 has_error = FALSE;
1086                                 break;
1087                         }
1088                 }
1089         }
1090                 
1091         if (has_error) {
1092                 g_free (stripped);
1093                 return FALSE;
1094         }
1095
1096         right_part = g_strdup (current);
1097         g_free (stripped);
1098         right_part = g_strstrip (right_part);
1099
1100         if (g_str_has_prefix (right_part, "<") &&
1101             g_str_has_suffix (right_part, ">")) {
1102                 gchar *address;
1103                 gboolean valid;
1104
1105                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1106                 g_free (right_part);
1107                 valid = modest_text_utils_validate_email_address (address);
1108                 g_free (address);
1109                 return valid;
1110         } else {
1111                 g_free (right_part);
1112                 return FALSE;
1113         }
1114 }
1115
1116
1117 gchar *
1118 modest_text_utils_get_display_size (guint64 size)
1119 {
1120         const guint KB=1024;
1121         const guint MB=1024 * KB;
1122         const guint GB=1024 * MB;
1123
1124         if (size == 0)
1125                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1126         if (0 < size && size < KB)
1127                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1128         else if (KB <= size && size < 100 * KB)
1129                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1130         else if (100*KB <= size && size < MB)
1131                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1132         else if (MB <= size && size < 10*MB)
1133                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1134         else if (10*MB <= size && size < GB)
1135                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1136         else
1137                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1138 }
1139
1140 static gchar *
1141 get_email_from_address (const gchar * address)
1142 {
1143         gchar *left_limit, *right_limit;
1144
1145         left_limit = strstr (address, "<");
1146         right_limit = g_strrstr (address, ">");
1147
1148         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1149                 return g_strdup (address);
1150         else
1151                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1152 }