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