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