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