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 g_return_val_if_fail (text, NULL);
121 g_return_val_if_fail (content_type, NULL);
122 g_return_val_if_fail (from, NULL);
124 cited = cite (sent_date, from);
126 if (content_type && strcmp (content_type, "text/html") == 0)
127 /* TODO: extract the <body> of the HTML and pass it to
129 retval = modest_text_utils_quote_html (text, cited, limit);
131 retval = modest_text_utils_quote_plain_text (text, cited, limit);
140 modest_text_utils_cite (const gchar *text,
141 const gchar *content_type,
147 tmp = cite (sent_date, from);
148 retval = g_strdup_printf ("%s%s\n", tmp, text);
155 modest_text_utils_inline (const gchar *text,
156 const gchar *content_type,
160 const gchar *subject)
163 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
164 const gchar *html_format = \
165 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
166 "<tr><td>%s</td><td>%s</td></tr>\n" \
167 "<tr><td>%s</td><td>%s</td></tr>\n" \
168 "<tr><td>%s</td><td>%s</td></tr>\n" \
169 "<tr><td>%s</td><td>%s</td></tr>\n" \
173 g_return_val_if_fail (text, NULL);
174 g_return_val_if_fail (content_type, NULL);
175 g_return_val_if_fail (from, NULL);
176 g_return_val_if_fail (text, NULL);
177 g_return_val_if_fail (to, NULL);
178 g_return_val_if_fail (subject, NULL);
180 modest_text_utils_strftime (sent_str, 100, "%c", localtime (&sent_date));
182 if (!strcmp (content_type, "text/html"))
183 /* TODO: extract the <body> of the HTML and pass it to
185 format = html_format;
187 format = plain_format;
189 return g_strdup_printf (format,
192 SENT_STRING, sent_str,
194 SUBJECT_STRING, subject,
198 /* just to prevent warnings:
199 * warning: `%x' yields only last 2 digits of year in some locales
202 modest_text_utils_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
204 return strftime(s, max, fmt, tm);
208 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
212 g_return_val_if_fail (prefix, NULL);
215 return g_strdup (prefix);
217 tmp = g_strchug (g_strdup (subject));
219 if (!strncmp (tmp, prefix, strlen (prefix))) {
223 return g_strdup_printf ("%s %s", prefix, subject);
228 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
230 gchar *dup, *token, *ptr, *result;
231 GString *filtered_emails;
233 g_return_val_if_fail (address_list, NULL);
236 return g_strdup (address_list);
238 /* search for substring */
239 if (!strstr ((const char *) address_list, (const char *) address))
240 return g_strdup (address_list);
242 dup = g_strdup (address_list);
243 filtered_emails = g_string_new (NULL);
245 token = strtok_r (dup, ",", &ptr);
247 while (token != NULL) {
248 /* Add to list if not found */
249 if (!strstr ((const char *) token, (const char *) address)) {
250 if (filtered_emails->len == 0)
251 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
253 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
255 token = strtok_r (NULL, ",", &ptr);
257 result = filtered_emails->str;
261 g_string_free (filtered_emails, FALSE);
267 modest_text_utils_convert_to_html (const gchar *data)
270 gboolean first_space = TRUE;
278 html = g_string_sized_new (len + 100); /* just a guess... */
280 g_string_append_printf (html,
283 "<meta http-equiv=\"content-type\""
284 " content=\"text/html; charset=utf8\">"
288 /* replace with special html chars where needed*/
289 for (i = 0; i != len; ++i) {
293 case 0: break; /* ignore embedded \0s */
294 case '<' : g_string_append (html, "<"); break;
295 case '>' : g_string_append (html, ">"); break;
296 case '&' : g_string_append (html, """); break;
297 case '\n': g_string_append (html, "<br>\n"); break;
300 g_string_append (html, first_space ? " " : " ");
302 } else if (kar == '\t')
303 g_string_append (html, " ");
307 /* optimization trick: accumulate 'normal' chars, then copy */
309 kar = data [++charnum + i];
311 } while ((i + charnum < len) &&
312 (kar > '>' || (kar != '<' && kar != '>'
313 && kar != '&' && kar != ' '
314 && kar != '\n' && kar != '\t')));
315 g_string_append_len (html, &data[i], charnum);
321 g_string_append (html, "</tt></body></html>");
322 hyperlinkify_plain_text (html);
324 return g_string_free (html, FALSE);
327 /* ******************************************************************* */
328 /* ************************* UTILIY FUNCTIONS ************************ */
329 /* ******************************************************************* */
332 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
338 return g_string_new("");
346 gs = g_string_new_len (i0, iter - i0);
350 get_indent_level (const char *l)
367 /* if we hit the signature marker "-- ", we return -(indent + 1). This
368 * stops reformatting.
370 if (strcmp (l, "-- ") == 0) {
378 unquote_line (GString * l)
393 g_string_erase (l, 0, p - l->str);
397 append_quoted (GString * buf, int indent, const GString * str,
402 indent = indent < 0 ? abs (indent) - 1 : indent;
403 for (i = 0; i <= indent; i++) {
404 g_string_append (buf, "> ");
407 g_string_append_len (buf, str->str, cutpoint);
409 g_string_append (buf, str->str);
411 g_string_append (buf, "\n");
415 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
418 const gchar *pos, *last;
421 indent = indent < 0 ? abs (indent) - 1 : indent;
425 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
427 if ((index + 2 * indent > limit) && last) {
431 if (g_unichar_isspace (uni[index])) {
434 pos = g_utf8_next_char (pos);
442 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
447 if (last + 2 * indent < limit)
450 for (i = strlen (s); i > 0; i--) {
452 if (i + 2 * indent <= limit) {
463 get_breakpoint (const gchar * s, const gint indent, const gint limit)
466 if (g_utf8_validate (s, -1, NULL)) {
467 return get_breakpoint_utf8 (s, indent, limit);
468 } else { /* assume ASCII */
469 //g_warning("invalid UTF-8 in msg");
470 return get_breakpoint_ascii (s, indent, limit);
475 cite (const time_t sent_date, const gchar *from)
479 /* format sent_date */
480 modest_text_utils_strftime (sent_str, 100, "%c", localtime (&sent_date));
481 return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
486 modest_text_utils_quote_plain_text (const gchar *text,
491 gint indent, breakpoint, rem_indent = 0;
492 GString *q, *l, *remaining;
496 /* remaining will store the rest of the line if we have to break it */
497 q = g_string_new (cite);
498 remaining = g_string_new ("");
503 l = get_next_line (text, len, iter);
504 iter = iter + l->len + 1;
505 indent = get_indent_level (l->str);
508 if (remaining->len) {
509 if (l->len && indent == rem_indent) {
510 g_string_prepend (l, " ");
511 g_string_prepend (l, remaining->str);
515 get_breakpoint (remaining-> str,
518 append_quoted (q, rem_indent,
519 remaining, breakpoint);
520 g_string_erase (remaining, 0,
522 if (remaining->str[0] == ' ') {
523 g_string_erase (remaining, 0,
526 } while (remaining->len);
529 g_string_free (remaining, TRUE);
530 breakpoint = get_breakpoint (l->str, indent, limit);
531 remaining = g_string_new (l->str + breakpoint);
532 if (remaining->str[0] == ' ') {
533 g_string_erase (remaining, 0, 1);
536 append_quoted (q, indent, l, breakpoint);
537 g_string_free (l, TRUE);
538 } while ((iter < text + len) || (remaining->str[0]));
540 return g_string_free (q, FALSE);
544 modest_text_utils_quote_html (const gchar *text,
548 const gchar *format = \
549 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
553 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
557 return g_strdup_printf (format, cite, text);
561 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
563 return match2->offset - match1->offset;
569 * check if the match is inside an existing match... */
571 chk_partial_match (const url_match_t *match, guint* offset)
573 if (*offset >= match->offset && *offset < match->offset + match->len)
578 get_url_matches (GString *txt)
581 guint rv, i, offset = 0;
582 GSList *match_list = NULL;
584 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
585 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
587 /* initalize the regexps */
588 for (i = 0; i != pattern_num; ++i) {
589 patterns[i].preg = g_new0 (regex_t,1);
590 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
591 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
593 /* find all the matches */
594 for (i = 0; i != pattern_num; ++i) {
598 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
599 g_assert (rv == REG_NOMATCH); /* this should not happen */
600 break; /* try next regexp */
605 /* FIXME: optimize this */
606 /* to avoid partial matches on something that was already found... */
607 /* check_partial_match will put -1 in the data ptr if that is the case */
608 test_offset = offset + rm.rm_so;
609 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
611 /* make a list of our matches (<offset, len, prefix> tupels)*/
612 if (test_offset != -1) {
613 url_match_t *match = g_new (url_match_t,1);
614 match->offset = offset + rm.rm_so;
615 match->len = rm.rm_eo - rm.rm_so;
616 match->prefix = patterns[i].prefix;
617 match_list = g_slist_prepend (match_list, match);
623 for (i = 0; i != pattern_num; ++i) {
624 regfree (patterns[i].preg);
625 g_free (patterns[i].preg);
626 } /* don't free patterns itself -- it's static */
628 /* now sort the list, so the matches are in reverse order of occurence.
629 * that way, we can do the replacements starting from the end, so we don't need
630 * to recalculate the offsets
632 match_list = g_slist_sort (match_list,
633 (GCompareFunc)cmp_offsets_reverse);
640 hyperlinkify_plain_text (GString *txt)
643 GSList *match_list = get_url_matches (txt);
645 /* we will work backwards, so the offsets stay valid */
646 for (cursor = match_list; cursor; cursor = cursor->next) {
648 url_match_t *match = (url_match_t*) cursor->data;
649 gchar *url = g_strndup (txt->str + match->offset, match->len);
650 gchar *repl = NULL; /* replacement */
652 /* the prefix is NULL: use the one that is already there */
653 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
654 match->prefix ? match->prefix : "", url, url);
656 /* replace the old thing with our hyperlink
657 * replacement thing */
658 g_string_erase (txt, match->offset, match->len);
659 g_string_insert (txt, match->offset, repl);
664 g_free (cursor->data);
667 g_slist_free (match_list);
673 modest_text_utils_get_display_address (gchar *address)
680 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
682 g_strchug (address); /* remove leading whitespace */
684 /* <email@address> from display name */
685 cursor = g_strstr_len (address, strlen(address), "<");
686 if (cursor == address) /* there's nothing else? leave it */
691 /* remove (bla bla) from display name */
692 cursor = g_strstr_len (address, strlen(address), "(");
693 if (cursor == address) /* there's nothing else? leave it */
698 g_strchomp (address); /* remove trailing whitespace */
706 modest_text_utils_get_subject_prefix_len (const gchar *sub)
709 static const gchar* prefix[] = {
710 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
713 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
719 if (g_str_has_prefix(sub, prefix[i])) {
720 int prefix_len = strlen(prefix[i]);
721 if (sub[prefix_len] == ' ')
722 ++prefix_len; /* ignore space after prefix as well */
732 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
737 /* work even when s1 and/or s2 == NULL */
738 if (G_UNLIKELY(s1 == s2))
745 /* if it's not case sensitive */
747 return strcmp (s1, s2);
749 n1 = g_utf8_collate_key (s1, -1);
750 n2 = g_utf8_collate_key (s2, -1);
752 result = strcmp (n1, n2);
762 modest_text_utils_get_display_date (time_t date)
764 struct tm date_tm, now_tm;
767 const gint buf_size = 64;
768 static gchar date_buf[64]; /* buf_size is not ... */
769 static gchar now_buf[64]; /* ...const enough... */
773 localtime_r(&now, &now_tm);
774 localtime_r(&date, &date_tm);
776 /* get today's date */
777 modest_text_utils_strftime (date_buf, buf_size, "%x", &date_tm);
778 modest_text_utils_strftime (now_buf, buf_size, "%x", &now_tm);
781 /* if this is today, get the time instead of the date */
782 if (strcmp (date_buf, now_buf) == 0)
783 strftime (date_buf, buf_size, _("%X"), &date_tm);
789 modest_text_utils_validate_email_address (const gchar *email_address)
792 const gchar *c, *domain;
793 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
795 /* first we validate the name portion (name@domain) */
796 for (c = email_address; *c; c++) {
798 (c == email_address ||
804 if (*c == '\\' && (*++c == ' '))
806 if (*c <= ' ' || *c >= 127)
819 if (*c <= ' ' || *c >= 127)
821 if (strchr(rfc822_specials, *c))
824 if (c == email_address || *(c - 1) == '.')
827 /* next we validate the domain portion (name@domain) */
828 if (!*(domain = ++c))
832 if (c == domain || *(c - 1) == '.')
836 if (*c <= ' ' || *c >= 127)
838 if (strchr(rfc822_specials, *c))
842 return (count >= 1) ? TRUE : FALSE;