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-tny-platform-factory.h>
37 #include <modest-text-utils.h>
38 #include <modest-runtime.h>
43 #endif /*HAVE_CONFIG_H */
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:")
53 * we need these regexps to find URLs in plain text e-mails
55 typedef struct _url_match_pattern_t url_match_pattern_t;
56 struct _url_match_pattern_t {
62 typedef struct _url_match_t url_match_t;
69 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
70 { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
72 { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
74 { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
76 { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
78 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
80 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
85 static gchar* cite (const time_t sent_date, const gchar *from);
86 static void hyperlinkify_plain_text (GString *txt);
87 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
88 static void chk_partial_match (const url_match_t *match, guint* offset);
89 static GSList* get_url_matches (GString *txt);
91 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
92 static int get_indent_level (const char *l);
93 static void unquote_line (GString * l);
94 static void append_quoted (GString * buf, const int indent, const GString * str,
96 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
97 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
98 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
100 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
104 static gchar* modest_text_utils_quote_html (const gchar *text,
109 /* ******************************************************************* */
110 /* ************************* PUBLIC FUNCTIONS ************************ */
111 /* ******************************************************************* */
114 modest_text_utils_quote (const gchar *text,
115 const gchar *content_type,
117 const time_t sent_date,
120 gchar *retval, *cited;
122 g_return_val_if_fail (text, NULL);
123 g_return_val_if_fail (content_type, NULL);
124 g_return_val_if_fail (from, NULL);
126 cited = cite (sent_date, from);
128 if (content_type && strcmp (content_type, "text/html") == 0)
129 /* TODO: extract the <body> of the HTML and pass it to
131 retval = modest_text_utils_quote_html (text, cited, limit);
133 retval = modest_text_utils_quote_plain_text (text, cited, limit);
142 modest_text_utils_cite (const gchar *text,
143 const gchar *content_type,
149 tmp = cite (sent_date, from);
150 retval = g_strdup_printf ("%s%s\n", tmp, text);
157 modest_text_utils_inline (const gchar *text,
158 const gchar *content_type,
162 const gchar *subject)
165 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
166 const gchar *html_format = \
167 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
168 "<tr><td>%s</td><td>%s</td></tr>\n" \
169 "<tr><td>%s</td><td>%s</td></tr>\n" \
170 "<tr><td>%s</td><td>%s</td></tr>\n" \
171 "<tr><td>%s</td><td>%s</td></tr>\n" \
175 g_return_val_if_fail (text, NULL);
176 g_return_val_if_fail (content_type, NULL);
177 g_return_val_if_fail (from, NULL);
178 g_return_val_if_fail (text, NULL);
179 g_return_val_if_fail (to, NULL);
180 g_return_val_if_fail (subject, NULL);
182 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
184 if (!strcmp (content_type, "text/html"))
185 /* TODO: extract the <body> of the HTML and pass it to
187 format = html_format;
189 format = plain_format;
191 return g_strdup_printf (format,
194 SENT_STRING, sent_str,
196 SUBJECT_STRING, subject,
200 /* just to prevent warnings:
201 * warning: `%x' yields only last 2 digits of year in some locales
204 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
206 /* only since Gtk 2.10
209 *g_date_set_time_t (&date, timet);
210 *return g_date_strftime (s, max, fmt, (const GDate*) &date);
214 time_tm = localtime (&timet);
216 return strftime (s, max, fmt, time_tm);
220 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
224 g_return_val_if_fail (prefix, NULL);
227 return g_strdup (prefix);
229 tmp = g_strchug (g_strdup (subject));
231 if (!strncmp (tmp, prefix, strlen (prefix))) {
235 return g_strdup_printf ("%s %s", prefix, subject);
240 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
242 gchar *dup, *token, *ptr, *result;
243 GString *filtered_emails;
245 g_return_val_if_fail (address_list, NULL);
248 return g_strdup (address_list);
250 /* search for substring */
251 if (!strstr ((const char *) address_list, (const char *) address))
252 return g_strdup (address_list);
254 dup = g_strdup (address_list);
255 filtered_emails = g_string_new (NULL);
257 token = strtok_r (dup, ",", &ptr);
259 while (token != NULL) {
260 /* Add to list if not found */
261 if (!strstr ((const char *) token, (const char *) address)) {
262 if (filtered_emails->len == 0)
263 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
265 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
267 token = strtok_r (NULL, ",", &ptr);
269 result = filtered_emails->str;
273 g_string_free (filtered_emails, FALSE);
279 modest_text_utils_convert_to_html (const gchar *data)
282 gboolean first_space = TRUE;
290 html = g_string_sized_new (len + 100); /* just a guess... */
292 g_string_append_printf (html,
295 "<meta http-equiv=\"content-type\""
296 " content=\"text/html; charset=utf8\">"
300 /* replace with special html chars where needed*/
301 for (i = 0; i != len; ++i) {
305 case 0: break; /* ignore embedded \0s */
306 case '<' : g_string_append (html, "<"); break;
307 case '>' : g_string_append (html, ">"); break;
308 case '&' : g_string_append (html, """); break;
309 case '\n': g_string_append (html, "<br>\n"); break;
312 g_string_append (html, first_space ? " " : " ");
314 } else if (kar == '\t')
315 g_string_append (html, " ");
319 /* optimization trick: accumulate 'normal' chars, then copy */
321 kar = data [++charnum + i];
323 } while ((i + charnum < len) &&
324 (kar > '>' || (kar != '<' && kar != '>'
325 && kar != '&' && kar != ' '
326 && kar != '\n' && kar != '\t')));
327 g_string_append_len (html, &data[i], charnum);
333 g_string_append (html, "</tt></body></html>");
334 hyperlinkify_plain_text (html);
336 return g_string_free (html, FALSE);
339 /* ******************************************************************* */
340 /* ************************* UTILIY FUNCTIONS ************************ */
341 /* ******************************************************************* */
344 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
350 return g_string_new("");
358 gs = g_string_new_len (i0, iter - i0);
362 get_indent_level (const char *l)
379 /* if we hit the signature marker "-- ", we return -(indent + 1). This
380 * stops reformatting.
382 if (strcmp (l, "-- ") == 0) {
390 unquote_line (GString * l)
405 g_string_erase (l, 0, p - l->str);
409 append_quoted (GString * buf, int indent, const GString * str,
414 indent = indent < 0 ? abs (indent) - 1 : indent;
415 for (i = 0; i <= indent; i++) {
416 g_string_append (buf, "> ");
419 g_string_append_len (buf, str->str, cutpoint);
421 g_string_append (buf, str->str);
423 g_string_append (buf, "\n");
427 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
430 const gchar *pos, *last;
433 indent = indent < 0 ? abs (indent) - 1 : indent;
437 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
439 if ((index + 2 * indent > limit) && last) {
443 if (g_unichar_isspace (uni[index])) {
446 pos = g_utf8_next_char (pos);
454 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
459 if (last + 2 * indent < limit)
462 for (i = strlen (s); i > 0; i--) {
464 if (i + 2 * indent <= limit) {
475 get_breakpoint (const gchar * s, const gint indent, const gint limit)
478 if (g_utf8_validate (s, -1, NULL)) {
479 return get_breakpoint_utf8 (s, indent, limit);
480 } else { /* assume ASCII */
481 //g_warning("invalid UTF-8 in msg");
482 return get_breakpoint_ascii (s, indent, limit);
487 cite (const time_t sent_date, const gchar *from)
491 /* format sent_date */
492 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
493 return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
498 modest_text_utils_quote_plain_text (const gchar *text,
503 gint indent, breakpoint, rem_indent = 0;
504 GString *q, *l, *remaining;
507 /* remaining will store the rest of the line if we have to break it */
508 q = g_string_new (cite);
509 remaining = g_string_new ("");
514 l = get_next_line (text, len, iter);
515 iter = iter + l->len + 1;
516 indent = get_indent_level (l->str);
519 if (remaining->len) {
520 if (l->len && indent == rem_indent) {
521 g_string_prepend (l, " ");
522 g_string_prepend (l, remaining->str);
526 get_breakpoint (remaining-> str,
529 append_quoted (q, rem_indent,
530 remaining, breakpoint);
531 g_string_erase (remaining, 0,
533 if (remaining->str[0] == ' ') {
534 g_string_erase (remaining, 0,
537 } while (remaining->len);
540 g_string_free (remaining, TRUE);
541 breakpoint = get_breakpoint (l->str, indent, limit);
542 remaining = g_string_new (l->str + breakpoint);
543 if (remaining->str[0] == ' ') {
544 g_string_erase (remaining, 0, 1);
547 append_quoted (q, indent, l, breakpoint);
548 g_string_free (l, TRUE);
549 } while ((iter < text + len) || (remaining->str[0]));
551 return g_string_free (q, FALSE);
555 modest_text_utils_quote_html (const gchar *text,
559 const gchar *format = \
560 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
564 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
568 return g_strdup_printf (format, cite, text);
572 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
574 return match2->offset - match1->offset;
580 * check if the match is inside an existing match... */
582 chk_partial_match (const url_match_t *match, guint* offset)
584 if (*offset >= match->offset && *offset < match->offset + match->len)
589 get_url_matches (GString *txt)
592 guint rv, i, offset = 0;
593 GSList *match_list = NULL;
595 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
596 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
598 /* initalize the regexps */
599 for (i = 0; i != pattern_num; ++i) {
600 patterns[i].preg = g_new0 (regex_t,1);
601 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
602 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
604 /* find all the matches */
605 for (i = 0; i != pattern_num; ++i) {
609 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
610 g_assert (rv == REG_NOMATCH); /* this should not happen */
611 break; /* try next regexp */
616 /* FIXME: optimize this */
617 /* to avoid partial matches on something that was already found... */
618 /* check_partial_match will put -1 in the data ptr if that is the case */
619 test_offset = offset + rm.rm_so;
620 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
622 /* make a list of our matches (<offset, len, prefix> tupels)*/
623 if (test_offset != -1) {
624 url_match_t *match = g_new (url_match_t,1);
625 match->offset = offset + rm.rm_so;
626 match->len = rm.rm_eo - rm.rm_so;
627 match->prefix = patterns[i].prefix;
628 match_list = g_slist_prepend (match_list, match);
634 for (i = 0; i != pattern_num; ++i) {
635 regfree (patterns[i].preg);
636 g_free (patterns[i].preg);
637 } /* don't free patterns itself -- it's static */
639 /* now sort the list, so the matches are in reverse order of occurence.
640 * that way, we can do the replacements starting from the end, so we don't need
641 * to recalculate the offsets
643 match_list = g_slist_sort (match_list,
644 (GCompareFunc)cmp_offsets_reverse);
651 hyperlinkify_plain_text (GString *txt)
654 GSList *match_list = get_url_matches (txt);
656 /* we will work backwards, so the offsets stay valid */
657 for (cursor = match_list; cursor; cursor = cursor->next) {
659 url_match_t *match = (url_match_t*) cursor->data;
660 gchar *url = g_strndup (txt->str + match->offset, match->len);
661 gchar *repl = NULL; /* replacement */
663 /* the prefix is NULL: use the one that is already there */
664 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
665 match->prefix ? match->prefix : "", url, url);
667 /* replace the old thing with our hyperlink
668 * replacement thing */
669 g_string_erase (txt, match->offset, match->len);
670 g_string_insert (txt, match->offset, repl);
675 g_free (cursor->data);
678 g_slist_free (match_list);
684 modest_text_utils_get_display_address (gchar *address)
691 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
693 g_strchug (address); /* remove leading whitespace */
695 /* <email@address> from display name */
696 cursor = g_strstr_len (address, strlen(address), "<");
697 if (cursor == address) /* there's nothing else? leave it */
702 /* remove (bla bla) from display name */
703 cursor = g_strstr_len (address, strlen(address), "(");
704 if (cursor == address) /* there's nothing else? leave it */
709 g_strchomp (address); /* remove trailing whitespace */
717 modest_text_utils_get_subject_prefix_len (const gchar *sub)
720 static const gchar* prefix[] = {
721 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
724 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
730 if (g_str_has_prefix(sub, prefix[i])) {
731 int prefix_len = strlen(prefix[i]);
732 if (sub[prefix_len] == ' ')
733 ++prefix_len; /* ignore space after prefix as well */
743 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
748 /* work even when s1 and/or s2 == NULL */
749 if (G_UNLIKELY(s1 == s2))
752 /* if it's not case sensitive */
754 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
756 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
757 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
759 result = strcmp (n1, n2);
768 get_display_date_cache (void)
770 return modest_cache_mgr_get_cache (modest_runtime_get_cache_mgr (),
771 MODEST_CACHE_MGR_CACHE_TYPE_DATE_STRING);
777 modest_text_utils_get_display_date (time_t date)
779 static GHashTable *date_cache = NULL;
782 const guint BUF_SIZE = 64;
783 gchar date_buf[BUF_SIZE];
784 gchar now_buf [BUF_SIZE];
787 if (G_UNLIKELY(!date_cache))
788 date_cache = get_display_date_cache ();
790 cached_val = g_hash_table_lookup (date_cache, &date);
796 /* get today's date */
797 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
798 modest_text_utils_strftime (now_buf, BUF_SIZE, "%x", now);
801 /* if this is today, get the time instead of the date */
802 if (strcmp (date_buf, now_buf) == 0)
803 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
805 cached_val = g_strdup(date_buf);
806 g_hash_table_insert (date_cache, (gpointer)&date, (gpointer)cached_val);
812 modest_text_utils_validate_email_address (const gchar *email_address)
815 const gchar *c, *domain;
816 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
818 /* first we validate the name portion (name@domain) */
819 for (c = email_address; *c; c++) {
821 (c == email_address ||
827 if (*c == '\\' && (*++c == ' '))
829 if (*c <= ' ' || *c >= 127)
842 if (*c <= ' ' || *c >= 127)
844 if (strchr(rfc822_specials, *c))
847 if (c == email_address || *(c - 1) == '.')
850 /* next we validate the domain portion (name@domain) */
851 if (!*(domain = ++c))
855 if (c == domain || *(c - 1) == '.')
859 if (*c <= ' ' || *c >= 127)
861 if (strchr(rfc822_specials, *c))
865 return (count >= 1) ? TRUE : FALSE;
872 modest_text_utils_get_display_size (guint size)
875 const guint MB=1024 * KB;
876 const guint GB=1024 * MB;
877 const guint TB=1024 * GB;
880 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
882 return g_strdup_printf (_("%d Kb"), size / KB);
884 return g_strdup_printf (_("%d Mb"), size / MB);
886 return g_strdup_printf (_("%d Gb"), size/ GB);
888 return g_strdup_printf (_("Very big"));