1 /* Copyright (c) 2006, Nokia Corporation
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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.
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.
34 #include <glib/gi18n.h>
36 #include "modest-text-utils.h"
41 #endif /*HAVE_CONFIG_H */
44 #define FORWARD_STRING _("-----Forwarded Message-----")
45 #define FROM_STRING _("From:")
46 #define SENT_STRING _("Sent:")
47 #define TO_STRING _("To:")
48 #define SUBJECT_STRING _("Subject:")
51 * we need these regexps to find URLs in plain text e-mails
53 typedef struct _url_match_pattern_t url_match_pattern_t;
54 struct _url_match_pattern_t {
60 typedef struct _url_match_t url_match_t;
67 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
68 { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
70 { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
72 { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
74 { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
76 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
78 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
83 static gchar* cite (const time_t sent_date, const gchar *from);
84 static void hyperlinkify_plain_text (GString *txt);
85 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
86 static void chk_partial_match (const url_match_t *match, guint* offset);
87 static GSList* get_url_matches (GString *txt);
89 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
90 static int get_indent_level (const char *l);
91 static void unquote_line (GString * l);
92 static void append_quoted (GString * buf, const int indent, const GString * str,
94 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
95 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
96 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
98 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
102 static gchar* modest_text_utils_quote_html (const gchar *text,
107 /* ******************************************************************* */
108 /* ************************* PUBLIC FUNCTIONS ************************ */
109 /* ******************************************************************* */
112 modest_text_utils_quote (const gchar *text,
113 const gchar *content_type,
115 const time_t sent_date,
118 gchar *retval, *cited;
120 cited = cite (sent_date, from);
122 if (!strcmp (content_type, "text/html"))
123 /* TODO: extract the <body> of the HTML and pass it to
125 retval = modest_text_utils_quote_html (text, cited, limit);
127 retval = modest_text_utils_quote_plain_text (text, cited, limit);
136 modest_text_utils_cite (const gchar *text,
137 const gchar *content_type,
143 tmp = cite (sent_date, from);
144 retval = g_strdup_printf ("%s%s\n", tmp, text);
151 modest_text_utils_inline (const gchar *text,
152 const gchar *content_type,
156 const gchar *subject)
159 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
160 const gchar *html_format = \
161 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
162 "<tr><td>%s</td><td>%s</td></tr>\n" \
163 "<tr><td>%s</td><td>%s</td></tr>\n" \
164 "<tr><td>%s</td><td>%s</td></tr>\n" \
165 "<tr><td>%s</td><td>%s</td></tr>\n" \
169 modest_text_utils_strftime (sent_str, 100, "%c", localtime (&sent_date));
171 if (!strcmp (content_type, "text/html"))
172 /* TODO: extract the <body> of the HTML and pass it to
174 format = html_format;
176 format = plain_format;
178 return g_strdup_printf (format,
181 SENT_STRING, sent_str,
183 SUBJECT_STRING, subject,
187 /* just to prevent warnings:
188 * warning: `%x' yields only last 2 digits of year in some locales
191 modest_text_utils_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
193 return strftime(s, max, fmt, tm);
197 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
202 return g_strdup_printf ("%s ", prefix);
204 tmp = g_strchug (g_strdup (subject));
206 if (!strncmp (tmp, prefix, strlen (prefix))) {
210 return g_strdup_printf ("%s %s", prefix, subject);
215 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
217 char *dup, *token, *ptr, *result;
218 GString *filtered_emails;
223 /* Search for substring */
224 if (!strstr ((const char *) address_list, (const char *) address))
225 return g_strdup (address_list);
227 dup = g_strdup (address_list);
228 filtered_emails = g_string_new (NULL);
230 token = strtok_r (dup, ",", &ptr);
232 while (token != NULL) {
233 /* Add to list if not found */
234 if (!strstr ((const char *) token, (const char *) address)) {
235 if (filtered_emails->len == 0)
236 g_string_append_printf (filtered_emails, "%s", token);
238 g_string_append_printf (filtered_emails, ",%s", token);
240 token = strtok_r (NULL, ",", &ptr);
242 result = filtered_emails->str;
246 g_string_free (filtered_emails, FALSE);
252 modest_text_utils_convert_to_html (const gchar *data)
255 gboolean first_space = TRUE;
263 html = g_string_sized_new (len + 100); /* just a guess... */
265 g_string_append_printf (html,
268 "<meta http-equiv=\"content-type\""
269 " content=\"text/html; charset=utf8\">"
273 /* replace with special html chars where needed*/
274 for (i = 0; i != len; ++i) {
278 case 0: break; /* ignore embedded \0s */
279 case '<' : g_string_append (html, "<"); break;
280 case '>' : g_string_append (html, ">"); break;
281 case '&' : g_string_append (html, """); break;
282 case '\n': g_string_append (html, "<br>\n"); break;
285 g_string_append (html, first_space ? " " : " ");
287 } else if (kar == '\t')
288 g_string_append (html, " ");
292 /* optimization trick: accumulate 'normal' chars, then copy */
294 kar = data [++charnum + i];
296 } while ((i + charnum < len) &&
297 (kar > '>' || (kar != '<' && kar != '>'
298 && kar != '&' && kar != ' '
299 && kar != '\n' && kar != '\t')));
300 g_string_append_len (html, &data[i], charnum);
306 g_string_append (html, "</tt></body></html>");
307 hyperlinkify_plain_text (html);
309 return g_string_free (html, FALSE);
312 /* ******************************************************************* */
313 /* ************************* UTILIY FUNCTIONS ************************ */
314 /* ******************************************************************* */
317 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
323 return g_string_new("");
331 gs = g_string_new_len (i0, iter - i0);
335 get_indent_level (const char *l)
352 /* if we hit the signature marker "-- ", we return -(indent + 1). This
353 * stops reformatting.
355 if (strcmp (l, "-- ") == 0) {
363 unquote_line (GString * l)
378 g_string_erase (l, 0, p - l->str);
382 append_quoted (GString * buf, int indent, const GString * str,
387 indent = indent < 0 ? abs (indent) - 1 : indent;
388 for (i = 0; i <= indent; i++) {
389 g_string_append (buf, "> ");
392 g_string_append_len (buf, str->str, cutpoint);
394 g_string_append (buf, str->str);
396 g_string_append (buf, "\n");
400 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
403 const gchar *pos, *last;
406 indent = indent < 0 ? abs (indent) - 1 : indent;
410 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
412 if ((index + 2 * indent > limit) && last) {
416 if (g_unichar_isspace (uni[index])) {
419 pos = g_utf8_next_char (pos);
427 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
432 if (last + 2 * indent < limit)
435 for (i = strlen (s); i > 0; i--) {
437 if (i + 2 * indent <= limit) {
448 get_breakpoint (const gchar * s, const gint indent, const gint limit)
451 if (g_utf8_validate (s, -1, NULL)) {
452 return get_breakpoint_utf8 (s, indent, limit);
453 } else { /* assume ASCII */
454 //g_warning("invalid UTF-8 in msg");
455 return get_breakpoint_ascii (s, indent, limit);
460 cite (const time_t sent_date, const gchar *from)
464 /* format sent_date */
465 modest_text_utils_strftime (sent_str, 100, "%c", localtime (&sent_date));
466 return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
471 modest_text_utils_quote_plain_text (const gchar *text,
476 gint indent, breakpoint, rem_indent = 0;
477 GString *q, *l, *remaining;
481 /* remaining will store the rest of the line if we have to break it */
482 q = g_string_new (cite);
483 remaining = g_string_new ("");
488 l = get_next_line (text, len, iter);
489 iter = iter + l->len + 1;
490 indent = get_indent_level (l->str);
493 if (remaining->len) {
494 if (l->len && indent == rem_indent) {
495 g_string_prepend (l, " ");
496 g_string_prepend (l, remaining->str);
500 get_breakpoint (remaining-> str,
503 append_quoted (q, rem_indent,
504 remaining, breakpoint);
505 g_string_erase (remaining, 0,
507 if (remaining->str[0] == ' ') {
508 g_string_erase (remaining, 0,
511 } while (remaining->len);
514 g_string_free (remaining, TRUE);
515 breakpoint = get_breakpoint (l->str, indent, limit);
516 remaining = g_string_new (l->str + breakpoint);
517 if (remaining->str[0] == ' ') {
518 g_string_erase (remaining, 0, 1);
521 append_quoted (q, indent, l, breakpoint);
522 g_string_free (l, TRUE);
523 } while ((iter < text + len) || (remaining->str[0]));
525 return g_string_free (q, FALSE);
529 modest_text_utils_quote_html (const gchar *text,
533 const gchar *format = \
534 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
538 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
542 return g_strdup_printf (format, cite, text);
546 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
548 return match2->offset - match1->offset;
554 * check if the match is inside an existing match... */
556 chk_partial_match (const url_match_t *match, guint* offset)
558 if (*offset >= match->offset && *offset < match->offset + match->len)
563 get_url_matches (GString *txt)
566 guint rv, i, offset = 0;
567 GSList *match_list = NULL;
569 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
570 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
572 /* initalize the regexps */
573 for (i = 0; i != pattern_num; ++i) {
574 patterns[i].preg = g_new0 (regex_t,1);
575 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
576 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
578 /* find all the matches */
579 for (i = 0; i != pattern_num; ++i) {
583 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
584 g_assert (rv == REG_NOMATCH); /* this should not happen */
585 break; /* try next regexp */
590 /* FIXME: optimize this */
591 /* to avoid partial matches on something that was already found... */
592 /* check_partial_match will put -1 in the data ptr if that is the case */
593 test_offset = offset + rm.rm_so;
594 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
596 /* make a list of our matches (<offset, len, prefix> tupels)*/
597 if (test_offset != -1) {
598 url_match_t *match = g_new (url_match_t,1);
599 match->offset = offset + rm.rm_so;
600 match->len = rm.rm_eo - rm.rm_so;
601 match->prefix = patterns[i].prefix;
602 match_list = g_slist_prepend (match_list, match);
608 for (i = 0; i != pattern_num; ++i) {
609 regfree (patterns[i].preg);
610 g_free (patterns[i].preg);
611 } /* don't free patterns itself -- it's static */
613 /* now sort the list, so the matches are in reverse order of occurence.
614 * that way, we can do the replacements starting from the end, so we don't need
615 * to recalculate the offsets
617 match_list = g_slist_sort (match_list,
618 (GCompareFunc)cmp_offsets_reverse);
625 hyperlinkify_plain_text (GString *txt)
628 GSList *match_list = get_url_matches (txt);
630 /* we will work backwards, so the offsets stay valid */
631 for (cursor = match_list; cursor; cursor = cursor->next) {
633 url_match_t *match = (url_match_t*) cursor->data;
634 gchar *url = g_strndup (txt->str + match->offset, match->len);
635 gchar *repl = NULL; /* replacement */
637 /* the prefix is NULL: use the one that is already there */
638 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
639 match->prefix ? match->prefix : "", url, url);
641 /* replace the old thing with our hyperlink
642 * replacement thing */
643 g_string_erase (txt, match->offset, match->len);
644 g_string_insert (txt, match->offset, repl);
649 g_free (cursor->data);
652 g_slist_free (match_list);
658 modest_text_utils_display_address (gchar *address)
665 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
667 g_strchug (address); /* remove leading whitespace */
669 /* <email@address> from display name */
670 cursor = g_strstr_len (address, strlen(address), "<");
671 if (cursor == address) /* there's nothing else? leave it */
676 /* remove (bla bla) from display name */
677 cursor = g_strstr_len (address, strlen(address), "(");
678 if (cursor == address) /* there's nothing else? leave it */
683 g_strchomp (address); /* remove trailing whitespace */