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)
201 g_return_val_if_fail (prefix, NULL);
204 return g_strdup (prefix);
206 tmp = g_strchug (g_strdup (subject));
208 if (!strncmp (tmp, prefix, strlen (prefix))) {
212 return g_strdup_printf ("%s %s", prefix, subject);
217 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
219 gchar *dup, *token, *ptr, *result;
220 GString *filtered_emails;
222 g_return_val_if_fail (address_list, NULL);
225 return g_strdup (address_list);
227 /* search for substring */
228 if (!strstr ((const char *) address_list, (const char *) address))
229 return g_strdup (address_list);
231 dup = g_strdup (address_list);
232 filtered_emails = g_string_new (NULL);
234 token = strtok_r (dup, ",", &ptr);
236 while (token != NULL) {
237 /* Add to list if not found */
238 if (!strstr ((const char *) token, (const char *) address)) {
239 if (filtered_emails->len == 0)
240 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
242 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
244 token = strtok_r (NULL, ",", &ptr);
246 result = filtered_emails->str;
250 g_string_free (filtered_emails, FALSE);
256 modest_text_utils_convert_to_html (const gchar *data)
259 gboolean first_space = TRUE;
267 html = g_string_sized_new (len + 100); /* just a guess... */
269 g_string_append_printf (html,
272 "<meta http-equiv=\"content-type\""
273 " content=\"text/html; charset=utf8\">"
277 /* replace with special html chars where needed*/
278 for (i = 0; i != len; ++i) {
282 case 0: break; /* ignore embedded \0s */
283 case '<' : g_string_append (html, "<"); break;
284 case '>' : g_string_append (html, ">"); break;
285 case '&' : g_string_append (html, """); break;
286 case '\n': g_string_append (html, "<br>\n"); break;
289 g_string_append (html, first_space ? " " : " ");
291 } else if (kar == '\t')
292 g_string_append (html, " ");
296 /* optimization trick: accumulate 'normal' chars, then copy */
298 kar = data [++charnum + i];
300 } while ((i + charnum < len) &&
301 (kar > '>' || (kar != '<' && kar != '>'
302 && kar != '&' && kar != ' '
303 && kar != '\n' && kar != '\t')));
304 g_string_append_len (html, &data[i], charnum);
310 g_string_append (html, "</tt></body></html>");
311 hyperlinkify_plain_text (html);
313 return g_string_free (html, FALSE);
316 /* ******************************************************************* */
317 /* ************************* UTILIY FUNCTIONS ************************ */
318 /* ******************************************************************* */
321 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
327 return g_string_new("");
335 gs = g_string_new_len (i0, iter - i0);
339 get_indent_level (const char *l)
356 /* if we hit the signature marker "-- ", we return -(indent + 1). This
357 * stops reformatting.
359 if (strcmp (l, "-- ") == 0) {
367 unquote_line (GString * l)
382 g_string_erase (l, 0, p - l->str);
386 append_quoted (GString * buf, int indent, const GString * str,
391 indent = indent < 0 ? abs (indent) - 1 : indent;
392 for (i = 0; i <= indent; i++) {
393 g_string_append (buf, "> ");
396 g_string_append_len (buf, str->str, cutpoint);
398 g_string_append (buf, str->str);
400 g_string_append (buf, "\n");
404 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
407 const gchar *pos, *last;
410 indent = indent < 0 ? abs (indent) - 1 : indent;
414 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
416 if ((index + 2 * indent > limit) && last) {
420 if (g_unichar_isspace (uni[index])) {
423 pos = g_utf8_next_char (pos);
431 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
436 if (last + 2 * indent < limit)
439 for (i = strlen (s); i > 0; i--) {
441 if (i + 2 * indent <= limit) {
452 get_breakpoint (const gchar * s, const gint indent, const gint limit)
455 if (g_utf8_validate (s, -1, NULL)) {
456 return get_breakpoint_utf8 (s, indent, limit);
457 } else { /* assume ASCII */
458 //g_warning("invalid UTF-8 in msg");
459 return get_breakpoint_ascii (s, indent, limit);
464 cite (const time_t sent_date, const gchar *from)
468 /* format sent_date */
469 modest_text_utils_strftime (sent_str, 100, "%c", localtime (&sent_date));
470 return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
475 modest_text_utils_quote_plain_text (const gchar *text,
480 gint indent, breakpoint, rem_indent = 0;
481 GString *q, *l, *remaining;
485 /* remaining will store the rest of the line if we have to break it */
486 q = g_string_new (cite);
487 remaining = g_string_new ("");
492 l = get_next_line (text, len, iter);
493 iter = iter + l->len + 1;
494 indent = get_indent_level (l->str);
497 if (remaining->len) {
498 if (l->len && indent == rem_indent) {
499 g_string_prepend (l, " ");
500 g_string_prepend (l, remaining->str);
504 get_breakpoint (remaining-> str,
507 append_quoted (q, rem_indent,
508 remaining, breakpoint);
509 g_string_erase (remaining, 0,
511 if (remaining->str[0] == ' ') {
512 g_string_erase (remaining, 0,
515 } while (remaining->len);
518 g_string_free (remaining, TRUE);
519 breakpoint = get_breakpoint (l->str, indent, limit);
520 remaining = g_string_new (l->str + breakpoint);
521 if (remaining->str[0] == ' ') {
522 g_string_erase (remaining, 0, 1);
525 append_quoted (q, indent, l, breakpoint);
526 g_string_free (l, TRUE);
527 } while ((iter < text + len) || (remaining->str[0]));
529 return g_string_free (q, FALSE);
533 modest_text_utils_quote_html (const gchar *text,
537 const gchar *format = \
538 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
542 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
546 return g_strdup_printf (format, cite, text);
550 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
552 return match2->offset - match1->offset;
558 * check if the match is inside an existing match... */
560 chk_partial_match (const url_match_t *match, guint* offset)
562 if (*offset >= match->offset && *offset < match->offset + match->len)
567 get_url_matches (GString *txt)
570 guint rv, i, offset = 0;
571 GSList *match_list = NULL;
573 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
574 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
576 /* initalize the regexps */
577 for (i = 0; i != pattern_num; ++i) {
578 patterns[i].preg = g_new0 (regex_t,1);
579 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
580 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
582 /* find all the matches */
583 for (i = 0; i != pattern_num; ++i) {
587 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
588 g_assert (rv == REG_NOMATCH); /* this should not happen */
589 break; /* try next regexp */
594 /* FIXME: optimize this */
595 /* to avoid partial matches on something that was already found... */
596 /* check_partial_match will put -1 in the data ptr if that is the case */
597 test_offset = offset + rm.rm_so;
598 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
600 /* make a list of our matches (<offset, len, prefix> tupels)*/
601 if (test_offset != -1) {
602 url_match_t *match = g_new (url_match_t,1);
603 match->offset = offset + rm.rm_so;
604 match->len = rm.rm_eo - rm.rm_so;
605 match->prefix = patterns[i].prefix;
606 match_list = g_slist_prepend (match_list, match);
612 for (i = 0; i != pattern_num; ++i) {
613 regfree (patterns[i].preg);
614 g_free (patterns[i].preg);
615 } /* don't free patterns itself -- it's static */
617 /* now sort the list, so the matches are in reverse order of occurence.
618 * that way, we can do the replacements starting from the end, so we don't need
619 * to recalculate the offsets
621 match_list = g_slist_sort (match_list,
622 (GCompareFunc)cmp_offsets_reverse);
629 hyperlinkify_plain_text (GString *txt)
632 GSList *match_list = get_url_matches (txt);
634 /* we will work backwards, so the offsets stay valid */
635 for (cursor = match_list; cursor; cursor = cursor->next) {
637 url_match_t *match = (url_match_t*) cursor->data;
638 gchar *url = g_strndup (txt->str + match->offset, match->len);
639 gchar *repl = NULL; /* replacement */
641 /* the prefix is NULL: use the one that is already there */
642 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
643 match->prefix ? match->prefix : "", url, url);
645 /* replace the old thing with our hyperlink
646 * replacement thing */
647 g_string_erase (txt, match->offset, match->len);
648 g_string_insert (txt, match->offset, repl);
653 g_free (cursor->data);
656 g_slist_free (match_list);
662 modest_text_utils_display_address (gchar *address)
669 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
671 g_strchug (address); /* remove leading whitespace */
673 /* <email@address> from display name */
674 cursor = g_strstr_len (address, strlen(address), "<");
675 if (cursor == address) /* there's nothing else? leave it */
680 /* remove (bla bla) from display name */
681 cursor = g_strstr_len (address, strlen(address), "(");
682 if (cursor == address) /* there's nothing else? leave it */
687 g_strchomp (address); /* remove trailing whitespace */