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 g_return_val_if_fail (text, NULL);
150 g_return_val_if_fail (content_type, NULL);
151 g_return_val_if_fail (from, NULL);
153 tmp = cite (sent_date, from);
154 retval = g_strdup_printf ("%s%s\n", tmp, text);
161 modest_text_utils_inline (const gchar *text,
162 const gchar *content_type,
166 const gchar *subject)
169 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
170 const gchar *html_format = \
171 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
172 "<tr><td>%s</td><td>%s</td></tr>\n" \
173 "<tr><td>%s</td><td>%s</td></tr>\n" \
174 "<tr><td>%s</td><td>%s</td></tr>\n" \
175 "<tr><td>%s</td><td>%s</td></tr>\n" \
179 g_return_val_if_fail (text, NULL);
180 g_return_val_if_fail (content_type, NULL);
181 g_return_val_if_fail (from, NULL);
182 g_return_val_if_fail (text, NULL);
183 g_return_val_if_fail (to, NULL);
185 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
187 if (!strcmp (content_type, "text/html"))
188 /* TODO: extract the <body> of the HTML and pass it to
190 format = html_format;
192 format = plain_format;
194 return g_strdup_printf (format,
197 SENT_STRING, sent_str,
199 SUBJECT_STRING, subject,
203 /* just to prevent warnings:
204 * warning: `%x' yields only last 2 digits of year in some locales
207 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
209 /* only since Gtk 2.10
212 *g_date_set_time_t (&date, timet);
213 *return g_date_strftime (s, max, fmt, (const GDate*) &date);
217 time_tm = localtime (&timet);
219 return strftime (s, max, fmt, time_tm);
223 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
227 g_return_val_if_fail (prefix, NULL);
230 return g_strdup (prefix);
232 tmp = g_strchug (g_strdup (subject));
234 if (!strncmp (tmp, prefix, strlen (prefix))) {
238 return g_strdup_printf ("%s %s", prefix, subject);
243 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
245 gchar *dup, *token, *ptr, *result;
246 GString *filtered_emails;
248 g_return_val_if_fail (address_list, NULL);
251 return g_strdup (address_list);
253 /* search for substring */
254 if (!strstr ((const char *) address_list, (const char *) address))
255 return g_strdup (address_list);
257 dup = g_strdup (address_list);
258 filtered_emails = g_string_new (NULL);
260 token = strtok_r (dup, ",", &ptr);
262 while (token != NULL) {
263 /* Add to list if not found */
264 if (!strstr ((const char *) token, (const char *) address)) {
265 if (filtered_emails->len == 0)
266 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
268 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
270 token = strtok_r (NULL, ",", &ptr);
272 result = filtered_emails->str;
276 g_string_free (filtered_emails, FALSE);
282 modest_text_utils_convert_to_html (const gchar *data)
285 gboolean first_space = TRUE;
293 html = g_string_sized_new (len + 100); /* just a guess... */
295 g_string_append_printf (html,
298 "<meta http-equiv=\"content-type\""
299 " content=\"text/html; charset=utf8\">"
303 /* replace with special html chars where needed*/
304 for (i = 0; i != len; ++i) {
308 case 0: break; /* ignore embedded \0s */
309 case '<' : g_string_append (html, "<"); break;
310 case '>' : g_string_append (html, ">"); break;
311 case '&' : g_string_append (html, """); break;
312 case '\n': g_string_append (html, "<br>\n"); break;
315 g_string_append (html, first_space ? " " : " ");
317 } else if (kar == '\t')
318 g_string_append (html, " ");
322 /* optimization trick: accumulate 'normal' chars, then copy */
324 kar = data [++charnum + i];
326 } while ((i + charnum < len) &&
327 (kar > '>' || (kar != '<' && kar != '>'
328 && kar != '&' && kar != ' '
329 && kar != '\n' && kar != '\t')));
330 g_string_append_len (html, &data[i], charnum);
336 g_string_append (html, "</tt></body></html>");
337 hyperlinkify_plain_text (html);
339 return g_string_free (html, FALSE);
342 /* ******************************************************************* */
343 /* ************************* UTILIY FUNCTIONS ************************ */
344 /* ******************************************************************* */
347 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
353 return g_string_new("");
361 gs = g_string_new_len (i0, iter - i0);
365 get_indent_level (const char *l)
382 /* if we hit the signature marker "-- ", we return -(indent + 1). This
383 * stops reformatting.
385 if (strcmp (l, "-- ") == 0) {
393 unquote_line (GString * l)
408 g_string_erase (l, 0, p - l->str);
412 append_quoted (GString * buf, int indent, const GString * str,
417 indent = indent < 0 ? abs (indent) - 1 : indent;
418 for (i = 0; i <= indent; i++) {
419 g_string_append (buf, "> ");
422 g_string_append_len (buf, str->str, cutpoint);
424 g_string_append (buf, str->str);
426 g_string_append (buf, "\n");
430 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
433 const gchar *pos, *last;
436 indent = indent < 0 ? abs (indent) - 1 : indent;
440 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
442 if ((index + 2 * indent > limit) && last) {
446 if (g_unichar_isspace (uni[index])) {
449 pos = g_utf8_next_char (pos);
457 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
462 if (last + 2 * indent < limit)
465 for (i = strlen (s); i > 0; i--) {
467 if (i + 2 * indent <= limit) {
478 get_breakpoint (const gchar * s, const gint indent, const gint limit)
481 if (g_utf8_validate (s, -1, NULL)) {
482 return get_breakpoint_utf8 (s, indent, limit);
483 } else { /* assume ASCII */
484 //g_warning("invalid UTF-8 in msg");
485 return get_breakpoint_ascii (s, indent, limit);
490 cite (const time_t sent_date, const gchar *from)
494 /* format sent_date */
495 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
496 return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
501 modest_text_utils_quote_plain_text (const gchar *text,
506 gint indent, breakpoint, rem_indent = 0;
507 GString *q, *l, *remaining;
510 /* remaining will store the rest of the line if we have to break it */
511 q = g_string_new (cite);
512 remaining = g_string_new ("");
517 l = get_next_line (text, len, iter);
518 iter = iter + l->len + 1;
519 indent = get_indent_level (l->str);
522 if (remaining->len) {
523 if (l->len && indent == rem_indent) {
524 g_string_prepend (l, " ");
525 g_string_prepend (l, remaining->str);
529 get_breakpoint (remaining->str,
532 append_quoted (q, rem_indent,
533 remaining, breakpoint);
534 g_string_erase (remaining, 0,
536 if (remaining->str[0] == ' ') {
537 g_string_erase (remaining, 0,
540 } while (remaining->len);
543 g_string_free (remaining, TRUE);
544 breakpoint = get_breakpoint (l->str, indent, limit);
545 remaining = g_string_new (l->str + breakpoint);
546 if (remaining->str[0] == ' ') {
547 g_string_erase (remaining, 0, 1);
550 append_quoted (q, indent, l, breakpoint);
551 g_string_free (l, TRUE);
552 } while ((iter < text + len) || (remaining->str[0]));
554 return g_string_free (q, FALSE);
558 modest_text_utils_quote_html (const gchar *text,
562 const gchar *format = \
563 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
567 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
571 return g_strdup_printf (format, cite, text);
575 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
577 return match2->offset - match1->offset;
583 * check if the match is inside an existing match... */
585 chk_partial_match (const url_match_t *match, guint* offset)
587 if (*offset >= match->offset && *offset < match->offset + match->len)
592 get_url_matches (GString *txt)
595 guint rv, i, offset = 0;
596 GSList *match_list = NULL;
598 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
599 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
601 /* initalize the regexps */
602 for (i = 0; i != pattern_num; ++i) {
603 patterns[i].preg = g_slice_new0 (regex_t);
605 /* this should not happen */
606 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
607 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
609 /* find all the matches */
610 for (i = 0; i != pattern_num; ++i) {
614 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
615 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
616 break; /* try next regexp */
621 /* FIXME: optimize this */
622 /* to avoid partial matches on something that was already found... */
623 /* check_partial_match will put -1 in the data ptr if that is the case */
624 test_offset = offset + rm.rm_so;
625 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
627 /* make a list of our matches (<offset, len, prefix> tupels)*/
628 if (test_offset != -1) {
629 url_match_t *match = g_slice_new (url_match_t);
630 match->offset = offset + rm.rm_so;
631 match->len = rm.rm_eo - rm.rm_so;
632 match->prefix = patterns[i].prefix;
633 match_list = g_slist_prepend (match_list, match);
639 for (i = 0; i != pattern_num; ++i) {
640 regfree (patterns[i].preg);
641 g_slice_free (regex_t, patterns[i].preg);
642 } /* don't free patterns itself -- it's static */
644 /* now sort the list, so the matches are in reverse order of occurence.
645 * that way, we can do the replacements starting from the end, so we don't need
646 * to recalculate the offsets
648 match_list = g_slist_sort (match_list,
649 (GCompareFunc)cmp_offsets_reverse);
656 hyperlinkify_plain_text (GString *txt)
659 GSList *match_list = get_url_matches (txt);
661 /* we will work backwards, so the offsets stay valid */
662 for (cursor = match_list; cursor; cursor = cursor->next) {
664 url_match_t *match = (url_match_t*) cursor->data;
665 gchar *url = g_strndup (txt->str + match->offset, match->len);
666 gchar *repl = NULL; /* replacement */
668 /* the prefix is NULL: use the one that is already there */
669 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
670 match->prefix ? match->prefix : "", url, url);
672 /* replace the old thing with our hyperlink
673 * replacement thing */
674 g_string_erase (txt, match->offset, match->len);
675 g_string_insert (txt, match->offset, repl);
680 g_slice_free (url_match_t, match);
683 g_slist_free (match_list);
689 modest_text_utils_get_display_address (gchar *address)
696 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
698 g_strchug (address); /* remove leading whitespace */
700 /* <email@address> from display name */
701 cursor = g_strstr_len (address, strlen(address), "<");
702 if (cursor == address) /* there's nothing else? leave it */
707 /* remove (bla bla) from display name */
708 cursor = g_strstr_len (address, strlen(address), "(");
709 if (cursor == address) /* there's nothing else? leave it */
714 g_strchomp (address); /* remove trailing whitespace */
722 modest_text_utils_get_subject_prefix_len (const gchar *sub)
725 static const gchar* prefix[] = {
726 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
729 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
735 if (g_str_has_prefix(sub, prefix[i])) {
736 int prefix_len = strlen(prefix[i]);
737 if (sub[prefix_len] == ' ')
738 ++prefix_len; /* ignore space after prefix as well */
748 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
753 /* work even when s1 and/or s2 == NULL */
754 if (G_UNLIKELY(s1 == s2))
757 /* if it's not case sensitive */
759 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
761 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
762 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
764 result = strcmp (n1, n2);
773 get_display_date_cache (void)
775 return modest_cache_mgr_get_cache (modest_runtime_get_cache_mgr (),
776 MODEST_CACHE_MGR_CACHE_TYPE_DATE_STRING);
782 modest_text_utils_get_display_date (time_t date)
784 static GHashTable *date_cache = NULL;
787 const guint BUF_SIZE = 64;
788 gchar date_buf[BUF_SIZE];
789 gchar now_buf [BUF_SIZE];
792 if (G_UNLIKELY(!date_cache))
793 date_cache = get_display_date_cache ();
795 cached_val = g_hash_table_lookup (date_cache, &date);
801 /* get today's date */
802 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
803 modest_text_utils_strftime (now_buf, BUF_SIZE, "%x", now);
806 /* if this is today, get the time instead of the date */
807 if (strcmp (date_buf, now_buf) == 0)
808 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
810 cached_val = g_strdup(date_buf);
811 g_hash_table_insert (date_cache, (gpointer)&date, (gpointer)cached_val);
817 modest_text_utils_validate_email_address (const gchar *email_address)
820 const gchar *c, *domain;
821 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
823 /* first we validate the name portion (name@domain) */
824 for (c = email_address; *c; c++) {
826 (c == email_address ||
832 if (*c == '\\' && (*++c == ' '))
834 if (*c <= ' ' || *c >= 127)
847 if (*c <= ' ' || *c >= 127)
849 if (strchr(rfc822_specials, *c))
852 if (c == email_address || *(c - 1) == '.')
855 /* next we validate the domain portion (name@domain) */
856 if (!*(domain = ++c))
860 if (c == domain || *(c - 1) == '.')
864 if (*c <= ' ' || *c >= 127)
866 if (strchr(rfc822_specials, *c))
870 return (count >= 1) ? TRUE : FALSE;
877 modest_text_utils_get_display_size (guint size)
880 const guint MB=1024 * KB;
881 const guint GB=1024 * MB;
882 const guint TB=1024 * GB;
885 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
887 return g_strdup_printf (_("%d Kb"), size / KB);
889 return g_strdup_printf (_("%d Mb"), size / MB);
891 return g_strdup_printf (_("%d Gb"), size/ GB);
893 return g_strdup_printf (_("Very big"));