* src/modest-text-utils.[ch]:
[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                                                     GList *attachments, 
105                                                     int limit);
106
107 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
108                                                     const gchar *cite,
109                                                     const gchar *signature,
110                                                     GList *attachments,
111                                                     int limit);
112 static gchar*   get_email_from_address (const gchar *address);
113
114
115 /* ******************************************************************* */
116 /* ************************* PUBLIC FUNCTIONS ************************ */
117 /* ******************************************************************* */
118
119 gchar *
120 modest_text_utils_quote (const gchar *text, 
121                          const gchar *content_type,
122                          const gchar *signature,
123                          const gchar *from,
124                          const time_t sent_date, 
125                          GList *attachments,
126                          int limit)
127 {
128         gchar *retval, *cited;
129
130         g_return_val_if_fail (text, NULL);
131         g_return_val_if_fail (content_type, NULL);
132
133         cited = cite (sent_date, from);
134         
135         if (content_type && strcmp (content_type, "text/html") == 0)
136                 /* TODO: extract the <body> of the HTML and pass it to
137                    the function */
138                 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
139         else
140                 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
141         
142         g_free (cited);
143
144         return retval;
145 }
146
147
148 gchar *
149 modest_text_utils_cite (const gchar *text,
150                         const gchar *content_type,
151                         const gchar *signature,
152                         const gchar *from,
153                         time_t sent_date)
154 {
155         gchar *retval;
156         gchar *tmp_sig;
157
158         g_return_val_if_fail (text, NULL);
159         g_return_val_if_fail (content_type, NULL);
160
161         if (!signature)
162                 tmp_sig = g_strdup ("");
163         else if (!strcmp(content_type, "text/html")) {
164                 tmp_sig = modest_text_utils_convert_to_html_body(signature);
165         } else {
166                 tmp_sig = g_strdup (signature);
167         }
168
169         retval = g_strdup_printf ("\n%s\n", tmp_sig);
170         g_free (tmp_sig);
171
172         return retval;
173 }
174
175 gchar * 
176 modest_text_utils_inline (const gchar *text,
177                           const gchar *content_type,
178                           const gchar *signature,
179                           const gchar *from,
180                           time_t sent_date,
181                           const gchar *to,
182                           const gchar *subject)
183 {
184         gchar sent_str[101];
185         gchar *formatted_signature;
186         const gchar *plain_format = "%s%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
187         const gchar *html_format = \
188                 "%s%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\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                 "<tr><td>%s</td><td>%s</td></tr>\n" \
193                 "<br><br>%s";
194         const gchar *format;
195
196         g_return_val_if_fail (text, NULL);
197         g_return_val_if_fail (content_type, NULL);
198         g_return_val_if_fail (text, NULL);
199         
200         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
201
202         if (!strcmp (content_type, "text/html"))
203                 /* TODO: extract the <body> of the HTML and pass it to
204                    the function */
205                 format = html_format;
206         else
207                 format = plain_format;
208
209         if (signature != NULL) {
210                 if (!strcmp (content_type, "text/html")) {
211                         formatted_signature = g_strconcat (signature, "<br/>", NULL);
212                 } else {
213                         formatted_signature = g_strconcat (signature, "\n", NULL);
214                 }
215         } else {
216                 formatted_signature = "";
217         }
218
219         return g_strdup_printf (format, formatted_signature, 
220                                 FORWARD_STRING,
221                                 FROM_STRING, (from) ? from : EMPTY_STRING,
222                                 SENT_STRING, sent_str,
223                                 TO_STRING, (to) ? to : EMPTY_STRING,
224                                 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
225                                 text);
226 }
227
228 /* just to prevent warnings:
229  * warning: `%x' yields only last 2 digits of year in some locales
230  */
231 gsize
232 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
233 {
234         struct tm tm;
235
236         /* does not work on old maemo glib: 
237          *   g_date_set_time_t (&date, timet);
238          */
239         localtime_r (&timet, &tm);
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         return g_strdup (_("mcen_ia_editor_original_message"));
683 }
684
685 static gchar *
686 quoted_attachments (GList *attachments)
687 {
688         GList *node = NULL;
689         GString *result = g_string_new ("");
690         for (node = attachments; node != NULL; node = g_list_next (node)) {
691                 gchar *filename = (gchar *) node->data;
692                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
693         }
694
695         return g_string_free (result, FALSE);
696
697 }
698
699 static gchar *
700 modest_text_utils_quote_plain_text (const gchar *text, 
701                                     const gchar *cite, 
702                                     const gchar *signature,
703                                     GList *attachments,
704                                     int limit)
705 {
706         const gchar *iter;
707         gint indent, breakpoint, rem_indent = 0;
708         GString *q, *l, *remaining;
709         gsize len;
710         gchar *attachments_string = NULL;
711
712         /* remaining will store the rest of the line if we have to break it */
713         q = g_string_new ("\n");
714         q = g_string_append (q, cite);
715         q = g_string_append_c (q, '\n');
716         remaining = g_string_new ("");
717
718         iter = text;
719         len = strlen(text);
720         do {
721                 l = get_next_line (text, len, iter);
722                 iter = iter + l->len + 1;
723                 indent = get_indent_level (l->str);
724                 unquote_line (l);
725
726                 if (remaining->len) {
727                         if (l->len && indent == rem_indent) {
728                                 g_string_prepend (l, " ");
729                                 g_string_prepend (l, remaining->str);
730                         } else {
731                                 do {
732                                         breakpoint =
733                                                 get_breakpoint (remaining->str,
734                                                                 rem_indent,
735                                                                 limit);
736                                         append_quoted (q, rem_indent,
737                                                        remaining, breakpoint);
738                                         g_string_erase (remaining, 0,
739                                                         breakpoint);
740                                         if (remaining->str[0] == ' ') {
741                                                 g_string_erase (remaining, 0,
742                                                                 1);
743                                         }
744                                 } while (remaining->len);
745                         }
746                 }
747                 g_string_free (remaining, TRUE);
748                 breakpoint = get_breakpoint (l->str, indent, limit);
749                 remaining = g_string_new (l->str + breakpoint);
750                 if (remaining->str[0] == ' ') {
751                         g_string_erase (remaining, 0, 1);
752                 }
753                 rem_indent = indent;
754                 append_quoted (q, indent, l, breakpoint);
755                 g_string_free (l, TRUE);
756         } while ((iter < text + len) || (remaining->str[0]));
757
758         attachments_string = quoted_attachments (attachments);
759         q = g_string_append (q, attachments_string);
760         g_free (attachments_string);
761
762         if (signature != NULL) {
763                 q = g_string_append_c (q, '\n');
764                 q = g_string_append (q, signature);
765         }
766
767         return g_string_free (q, FALSE);
768 }
769
770 static gchar*
771 modest_text_utils_quote_html (const gchar *text, 
772                               const gchar *cite, 
773                               const gchar *signature,
774                               GList *attachments,
775                               int limit)
776 {
777         gchar *result = NULL;
778         gchar *signature_result = NULL;
779         const gchar *format = \
780                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
781                 "<html>\n" \
782                 "<body>\n" \
783                 "<br/>%s<br/>" \
784                 "<pre>%s<br/>%s<br/>%s</pre>\n" \
785                 "</body>\n" \
786                 "</html>\n";
787         gchar *attachments_string = NULL;
788         gchar *q_attachments_string = NULL;
789         gchar *html_text = NULL;
790
791         if (signature == NULL)
792                 signature_result = g_strdup ("");
793         else
794                 signature_result = modest_text_utils_convert_to_html_body (signature);
795
796         attachments_string = quoted_attachments (attachments);
797         q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string);
798         html_text = modest_text_utils_convert_to_html_body (text);
799         result = g_strdup_printf (format, signature_result, cite, html_text, q_attachments_string);
800         g_free (html_text);
801         g_free (attachments_string);
802         g_free (q_attachments_string);
803         g_free (signature_result);
804         return result;
805 }
806
807 static gint 
808 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
809 {
810         return match2->offset - match1->offset;
811 }
812
813
814
815 /*
816  * check if the match is inside an existing match... */
817 static void
818 chk_partial_match (const url_match_t *match, guint* offset)
819 {
820         if (*offset >= match->offset && *offset < match->offset + match->len)
821                 *offset = -1;
822 }
823
824 static GSList*
825 get_url_matches (GString *txt)
826 {
827         regmatch_t rm;
828         guint rv, i, offset = 0;
829         GSList *match_list = NULL;
830
831         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
832         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
833
834         /* initalize the regexps */
835         for (i = 0; i != pattern_num; ++i) {
836                 patterns[i].preg = g_slice_new0 (regex_t);
837
838                 /* this should not happen */
839                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
840                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
841         }
842         /* find all the matches */
843         for (i = 0; i != pattern_num; ++i) {
844                 offset     = 0; 
845                 while (1) {
846                         int test_offset;
847                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
848                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
849                                 break; /* try next regexp */ 
850                         }
851                         if (rm.rm_so == -1)
852                                 break;
853
854                         /* FIXME: optimize this */
855                         /* to avoid partial matches on something that was already found... */
856                         /* check_partial_match will put -1 in the data ptr if that is the case */
857                         test_offset = offset + rm.rm_so;
858                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
859                         
860                         /* make a list of our matches (<offset, len, prefix> tupels)*/
861                         if (test_offset != -1) {
862                                 url_match_t *match = g_slice_new (url_match_t);
863                                 match->offset = offset + rm.rm_so;
864                                 match->len    = rm.rm_eo - rm.rm_so;
865                                 match->prefix = patterns[i].prefix;
866                                 match_list = g_slist_prepend (match_list, match);
867                         }
868                         offset += rm.rm_eo;
869                 }
870         }
871
872         for (i = 0; i != pattern_num; ++i) {
873                 regfree (patterns[i].preg);
874                 g_slice_free  (regex_t, patterns[i].preg);
875         } /* don't free patterns itself -- it's static */
876         
877         /* now sort the list, so the matches are in reverse order of occurence.
878          * that way, we can do the replacements starting from the end, so we don't need
879          * to recalculate the offsets
880          */
881         match_list = g_slist_sort (match_list,
882                                    (GCompareFunc)cmp_offsets_reverse); 
883         return match_list;      
884 }
885
886
887
888 static void
889 hyperlinkify_plain_text (GString *txt)
890 {
891         GSList *cursor;
892         GSList *match_list = get_url_matches (txt);
893
894         /* we will work backwards, so the offsets stay valid */
895         for (cursor = match_list; cursor; cursor = cursor->next) {
896
897                 url_match_t *match = (url_match_t*) cursor->data;
898                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
899                 gchar *repl = NULL; /* replacement  */
900
901                 /* the prefix is NULL: use the one that is already there */
902                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
903                                         match->prefix ? match->prefix : EMPTY_STRING, 
904                                         url, url);
905
906                 /* replace the old thing with our hyperlink
907                  * replacement thing */
908                 g_string_erase  (txt, match->offset, match->len);
909                 g_string_insert (txt, match->offset, repl);
910                 
911                 g_free (url);
912                 g_free (repl);
913
914                 g_slice_free (url_match_t, match);      
915         }
916         
917         g_slist_free (match_list);
918 }
919
920
921
922 gchar*
923 modest_text_utils_get_display_address (gchar *address)
924 {
925         gchar *cursor;
926         
927         if (!address)
928                 return NULL;
929         
930         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
931         
932         g_strchug (address); /* remove leading whitespace */
933
934         /*  <email@address> from display name */
935         cursor = g_strstr_len (address, strlen(address), "<");
936         if (cursor == address) /* there's nothing else? leave it */
937                 return address;
938         if (cursor) 
939                 cursor[0]='\0';
940
941         /* remove (bla bla) from display name */
942         cursor = g_strstr_len (address, strlen(address), "(");
943         if (cursor == address) /* there's nothing else? leave it */
944                 return address;
945         if (cursor) 
946                 cursor[0]='\0';
947
948         g_strchomp (address); /* remove trailing whitespace */
949
950         return address;
951 }
952
953
954
955 gint 
956 modest_text_utils_get_subject_prefix_len (const gchar *sub)
957 {
958         gint i;
959         static const gchar* prefix[] = {
960                 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
961         };
962                 
963         if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
964                 return 0;
965
966         i = 0;
967         
968         while (prefix[i]) {
969                 if (g_str_has_prefix(sub, prefix[i])) {
970                         int prefix_len = strlen(prefix[i]); 
971                         if (sub[prefix_len] == ' ')
972                                 ++prefix_len; /* ignore space after prefix as well */
973                         return prefix_len; 
974                 }
975                 ++i;
976         }
977         return 0;
978 }
979
980
981 gint
982 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
983 {
984         gint result = 0;
985         gchar *n1, *n2;
986
987         /* work even when s1 and/or s2 == NULL */
988         if (G_UNLIKELY(s1 == s2))
989                 return 0;
990
991         /* if it's not case sensitive */
992         if (!insensitive)
993                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
994         
995         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
996         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
997         
998         result = strcmp (n1, n2);
999
1000         g_free (n1);
1001         g_free (n2);
1002         
1003         return result;
1004 }
1005
1006
1007 gchar*
1008 modest_text_utils_get_display_date (time_t date)
1009 {
1010         time_t now;
1011         const guint BUF_SIZE = 64; 
1012         gchar date_buf[BUF_SIZE];  
1013         gchar now_buf [BUF_SIZE];  
1014         
1015         now = time (NULL);
1016
1017         /* use the localized dates */
1018         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date); 
1019         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x", now); 
1020         
1021         /* if this is today, get the time instead of the date */
1022         if (strcmp (date_buf, now_buf) == 0)
1023                 modest_text_utils_strftime (date_buf, BUF_SIZE, "%X", date);
1024         
1025         return g_strdup(date_buf);
1026 }
1027
1028 gboolean 
1029 modest_text_utils_validate_email_address (const gchar *email_address)
1030 {
1031         int count = 0;
1032         const gchar *c = NULL, *domain = NULL;
1033         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
1034
1035         /* first we validate the name portion (name@domain) */
1036         for (c = email_address;  *c;  c++) {
1037                 if (*c == '\"' && 
1038                     (c == email_address || 
1039                      *(c - 1) == '.' || 
1040                      *(c - 1) == '\"')) {
1041                         while (*++c) {
1042                                 if (*c == '\"') 
1043                                         break;
1044                                 if (*c == '\\' && (*++c == ' ')) 
1045                                         continue;
1046                                 if (*c <= ' ' || *c >= 127) 
1047                                         return FALSE;
1048                         }
1049                         if (!*c++) 
1050                                 return FALSE;
1051                         if (*c == '@') 
1052                                 break;
1053                         if (*c != '.') 
1054                                 return FALSE;
1055                         continue;
1056                 }
1057                 if (*c == '@') 
1058                         break;
1059                 if (*c <= ' ' || *c >= 127) 
1060                         return FALSE;
1061                 if (strchr(rfc822_specials, *c)) 
1062                         return FALSE;
1063         }
1064         if (c == email_address || *(c - 1) == '.') 
1065                 return FALSE;
1066
1067         /* next we validate the domain portion (name@domain) */
1068         if (!*(domain = ++c)) 
1069                 return FALSE;
1070         do {
1071                 if (*c == '.') {
1072                         if (c == domain || *(c - 1) == '.') 
1073                                 return FALSE;
1074                         count++;
1075                 }
1076                 if (*c <= ' ' || *c >= 127) 
1077                         return FALSE;
1078                 if (strchr(rfc822_specials, *c)) 
1079                         return FALSE;
1080         } while (*++c);
1081
1082         return (count >= 1) ? TRUE : FALSE;
1083 }
1084
1085 gboolean 
1086 modest_text_utils_validate_recipient (const gchar *recipient)
1087 {
1088         gchar *stripped, *current;
1089         gchar *right_part;
1090         gboolean has_error = FALSE;
1091
1092         if (modest_text_utils_validate_email_address (recipient))
1093                 return TRUE;
1094         stripped = g_strdup (recipient);
1095         stripped = g_strstrip (stripped);
1096         current = stripped;
1097
1098         if (*current == '\0') {
1099                 g_free (stripped);
1100                 return FALSE;
1101         }
1102
1103         /* quoted string */
1104         if (*current == '\"') {
1105                 current = g_utf8_next_char (current);
1106                 has_error = TRUE;
1107                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1108                         if (*current == '\\') {
1109                                 /* TODO: This causes a warning, which breaks the build, 
1110                                  * because a gchar cannot be < 0.
1111                                  * murrayc. 
1112                                 if (current[1] <0) {
1113                                         has_error = TRUE;
1114                                         break;
1115                                 }
1116                                 */
1117                         } else if (*current == '\"') {
1118                                 has_error = FALSE;
1119                                 current = g_utf8_next_char (current);
1120                                 break;
1121                         }
1122                 }
1123         } else {
1124                 has_error = TRUE;
1125                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1126                         if (*current == '<') {
1127                                 has_error = FALSE;
1128                                 break;
1129                         }
1130                 }
1131         }
1132                 
1133         if (has_error) {
1134                 g_free (stripped);
1135                 return FALSE;
1136         }
1137
1138         right_part = g_strdup (current);
1139         g_free (stripped);
1140         right_part = g_strstrip (right_part);
1141
1142         if (g_str_has_prefix (right_part, "<") &&
1143             g_str_has_suffix (right_part, ">")) {
1144                 gchar *address;
1145                 gboolean valid;
1146
1147                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1148                 g_free (right_part);
1149                 valid = modest_text_utils_validate_email_address (address);
1150                 g_free (address);
1151                 return valid;
1152         } else {
1153                 g_free (right_part);
1154                 return FALSE;
1155         }
1156 }
1157
1158
1159 gchar *
1160 modest_text_utils_get_display_size (guint64 size)
1161 {
1162         const guint KB=1024;
1163         const guint MB=1024 * KB;
1164         const guint GB=1024 * MB;
1165
1166         if (size == 0)
1167                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1168         if (0 < size && size < KB)
1169                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1170         else if (KB <= size && size < 100 * KB)
1171                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1172         else if (100*KB <= size && size < MB)
1173                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1174         else if (MB <= size && size < 10*MB)
1175                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1176         else if (10*MB <= size && size < GB)
1177                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1178         else
1179                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1180 }
1181
1182 static gchar *
1183 get_email_from_address (const gchar * address)
1184 {
1185         gchar *left_limit, *right_limit;
1186
1187         left_limit = strstr (address, "<");
1188         right_limit = g_strrstr (address, ">");
1189
1190         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1191                 return g_strdup (address);
1192         else
1193                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1194 }