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"
42 #endif /*HAVE_CONFIG_H */
45 #define FORWARD_STRING _("-----Forwarded Message-----")
46 #define FROM_STRING _("From:")
47 #define SENT_STRING _("Sent:")
48 #define TO_STRING _("To:")
49 #define SUBJECT_STRING _("Subject:")
52 * we need these regexps to find URLs in plain text e-mails
54 typedef struct _url_match_pattern_t url_match_pattern_t;
55 struct _url_match_pattern_t {
61 typedef struct _url_match_t url_match_t;
68 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
69 { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
71 { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
73 { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
75 { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
77 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
79 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
84 static gchar* cite (const time_t sent_date, const gchar *from);
85 static void hyperlinkify_plain_text (GString *txt);
86 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
87 static void chk_partial_match (const url_match_t *match, guint* offset);
88 static GSList* get_url_matches (GString *txt);
90 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
91 static int get_indent_level (const char *l);
92 static void unquote_line (GString * l);
93 static void append_quoted (GString * buf, const int indent, const GString * str,
95 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
96 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
97 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
99 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
103 static gchar* modest_text_utils_quote_html (const gchar *text,
108 /* ******************************************************************* */
109 /* ************************* PUBLIC FUNCTIONS ************************ */
110 /* ******************************************************************* */
113 modest_text_utils_quote (const gchar *text,
114 const gchar *content_type,
116 const time_t sent_date,
119 gchar *retval, *cited;
121 g_return_val_if_fail (text, NULL);
122 g_return_val_if_fail (content_type, NULL);
123 g_return_val_if_fail (from, NULL);
125 cited = cite (sent_date, from);
127 if (content_type && strcmp (content_type, "text/html") == 0)
128 /* TODO: extract the <body> of the HTML and pass it to
130 retval = modest_text_utils_quote_html (text, cited, limit);
132 retval = modest_text_utils_quote_plain_text (text, cited, limit);
141 modest_text_utils_cite (const gchar *text,
142 const gchar *content_type,
148 tmp = cite (sent_date, from);
149 retval = g_strdup_printf ("%s%s\n", tmp, text);
156 modest_text_utils_inline (const gchar *text,
157 const gchar *content_type,
161 const gchar *subject)
164 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
165 const gchar *html_format = \
166 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\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" \
170 "<tr><td>%s</td><td>%s</td></tr>\n" \
174 g_return_val_if_fail (text, NULL);
175 g_return_val_if_fail (content_type, NULL);
176 g_return_val_if_fail (from, NULL);
177 g_return_val_if_fail (text, NULL);
178 g_return_val_if_fail (to, NULL);
179 g_return_val_if_fail (subject, NULL);
181 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
183 if (!strcmp (content_type, "text/html"))
184 /* TODO: extract the <body> of the HTML and pass it to
186 format = html_format;
188 format = plain_format;
190 return g_strdup_printf (format,
193 SENT_STRING, sent_str,
195 SUBJECT_STRING, subject,
199 /* just to prevent warnings:
200 * warning: `%x' yields only last 2 digits of year in some locales
203 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
205 /* only since Gtk 2.10
208 *g_date_set_time_t (&date, timet);
209 *return g_date_strftime (s, max, fmt, (const GDate*) &date);
213 time_tm = localtime (&timet);
215 return strftime (s, max, fmt, time_tm);
219 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
223 g_return_val_if_fail (prefix, NULL);
226 return g_strdup (prefix);
228 tmp = g_strchug (g_strdup (subject));
230 if (!strncmp (tmp, prefix, strlen (prefix))) {
234 return g_strdup_printf ("%s %s", prefix, subject);
239 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
241 gchar *dup, *token, *ptr, *result;
242 GString *filtered_emails;
244 g_return_val_if_fail (address_list, NULL);
247 return g_strdup (address_list);
249 /* search for substring */
250 if (!strstr ((const char *) address_list, (const char *) address))
251 return g_strdup (address_list);
253 dup = g_strdup (address_list);
254 filtered_emails = g_string_new (NULL);
256 token = strtok_r (dup, ",", &ptr);
258 while (token != NULL) {
259 /* Add to list if not found */
260 if (!strstr ((const char *) token, (const char *) address)) {
261 if (filtered_emails->len == 0)
262 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
264 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
266 token = strtok_r (NULL, ",", &ptr);
268 result = filtered_emails->str;
272 g_string_free (filtered_emails, FALSE);
278 modest_text_utils_convert_to_html (const gchar *data)
281 gboolean first_space = TRUE;
289 html = g_string_sized_new (len + 100); /* just a guess... */
291 g_string_append_printf (html,
294 "<meta http-equiv=\"content-type\""
295 " content=\"text/html; charset=utf8\">"
299 /* replace with special html chars where needed*/
300 for (i = 0; i != len; ++i) {
304 case 0: break; /* ignore embedded \0s */
305 case '<' : g_string_append (html, "<"); break;
306 case '>' : g_string_append (html, ">"); break;
307 case '&' : g_string_append (html, """); break;
308 case '\n': g_string_append (html, "<br>\n"); break;
311 g_string_append (html, first_space ? " " : " ");
313 } else if (kar == '\t')
314 g_string_append (html, " ");
318 /* optimization trick: accumulate 'normal' chars, then copy */
320 kar = data [++charnum + i];
322 } while ((i + charnum < len) &&
323 (kar > '>' || (kar != '<' && kar != '>'
324 && kar != '&' && kar != ' '
325 && kar != '\n' && kar != '\t')));
326 g_string_append_len (html, &data[i], charnum);
332 g_string_append (html, "</tt></body></html>");
333 hyperlinkify_plain_text (html);
335 return g_string_free (html, FALSE);
338 /* ******************************************************************* */
339 /* ************************* UTILIY FUNCTIONS ************************ */
340 /* ******************************************************************* */
343 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
349 return g_string_new("");
357 gs = g_string_new_len (i0, iter - i0);
361 get_indent_level (const char *l)
378 /* if we hit the signature marker "-- ", we return -(indent + 1). This
379 * stops reformatting.
381 if (strcmp (l, "-- ") == 0) {
389 unquote_line (GString * l)
404 g_string_erase (l, 0, p - l->str);
408 append_quoted (GString * buf, int indent, const GString * str,
413 indent = indent < 0 ? abs (indent) - 1 : indent;
414 for (i = 0; i <= indent; i++) {
415 g_string_append (buf, "> ");
418 g_string_append_len (buf, str->str, cutpoint);
420 g_string_append (buf, str->str);
422 g_string_append (buf, "\n");
426 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
429 const gchar *pos, *last;
432 indent = indent < 0 ? abs (indent) - 1 : indent;
436 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
438 if ((index + 2 * indent > limit) && last) {
442 if (g_unichar_isspace (uni[index])) {
445 pos = g_utf8_next_char (pos);
453 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
458 if (last + 2 * indent < limit)
461 for (i = strlen (s); i > 0; i--) {
463 if (i + 2 * indent <= limit) {
474 get_breakpoint (const gchar * s, const gint indent, const gint limit)
477 if (g_utf8_validate (s, -1, NULL)) {
478 return get_breakpoint_utf8 (s, indent, limit);
479 } else { /* assume ASCII */
480 //g_warning("invalid UTF-8 in msg");
481 return get_breakpoint_ascii (s, indent, limit);
486 cite (const time_t sent_date, const gchar *from)
490 /* format sent_date */
491 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
492 return g_strdup_printf (N_("On %s, %s wrote:\n"), sent_str, from);
497 modest_text_utils_quote_plain_text (const gchar *text,
502 gint indent, breakpoint, rem_indent = 0;
503 GString *q, *l, *remaining;
506 /* remaining will store the rest of the line if we have to break it */
507 q = g_string_new (cite);
508 remaining = g_string_new ("");
513 l = get_next_line (text, len, iter);
514 iter = iter + l->len + 1;
515 indent = get_indent_level (l->str);
518 if (remaining->len) {
519 if (l->len && indent == rem_indent) {
520 g_string_prepend (l, " ");
521 g_string_prepend (l, remaining->str);
525 get_breakpoint (remaining-> str,
528 append_quoted (q, rem_indent,
529 remaining, breakpoint);
530 g_string_erase (remaining, 0,
532 if (remaining->str[0] == ' ') {
533 g_string_erase (remaining, 0,
536 } while (remaining->len);
539 g_string_free (remaining, TRUE);
540 breakpoint = get_breakpoint (l->str, indent, limit);
541 remaining = g_string_new (l->str + breakpoint);
542 if (remaining->str[0] == ' ') {
543 g_string_erase (remaining, 0, 1);
546 append_quoted (q, indent, l, breakpoint);
547 g_string_free (l, TRUE);
548 } while ((iter < text + len) || (remaining->str[0]));
550 return g_string_free (q, FALSE);
554 modest_text_utils_quote_html (const gchar *text,
558 const gchar *format = \
559 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
563 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
567 return g_strdup_printf (format, cite, text);
571 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
573 return match2->offset - match1->offset;
579 * check if the match is inside an existing match... */
581 chk_partial_match (const url_match_t *match, guint* offset)
583 if (*offset >= match->offset && *offset < match->offset + match->len)
588 get_url_matches (GString *txt)
591 guint rv, i, offset = 0;
592 GSList *match_list = NULL;
594 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
595 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
597 /* initalize the regexps */
598 for (i = 0; i != pattern_num; ++i) {
599 patterns[i].preg = g_new0 (regex_t,1);
600 g_assert(regcomp (patterns[i].preg, patterns[i].regex,
601 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0);
603 /* find all the matches */
604 for (i = 0; i != pattern_num; ++i) {
608 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
609 g_assert (rv == REG_NOMATCH); /* this should not happen */
610 break; /* try next regexp */
615 /* FIXME: optimize this */
616 /* to avoid partial matches on something that was already found... */
617 /* check_partial_match will put -1 in the data ptr if that is the case */
618 test_offset = offset + rm.rm_so;
619 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
621 /* make a list of our matches (<offset, len, prefix> tupels)*/
622 if (test_offset != -1) {
623 url_match_t *match = g_new (url_match_t,1);
624 match->offset = offset + rm.rm_so;
625 match->len = rm.rm_eo - rm.rm_so;
626 match->prefix = patterns[i].prefix;
627 match_list = g_slist_prepend (match_list, match);
633 for (i = 0; i != pattern_num; ++i) {
634 regfree (patterns[i].preg);
635 g_free (patterns[i].preg);
636 } /* don't free patterns itself -- it's static */
638 /* now sort the list, so the matches are in reverse order of occurence.
639 * that way, we can do the replacements starting from the end, so we don't need
640 * to recalculate the offsets
642 match_list = g_slist_sort (match_list,
643 (GCompareFunc)cmp_offsets_reverse);
650 hyperlinkify_plain_text (GString *txt)
653 GSList *match_list = get_url_matches (txt);
655 /* we will work backwards, so the offsets stay valid */
656 for (cursor = match_list; cursor; cursor = cursor->next) {
658 url_match_t *match = (url_match_t*) cursor->data;
659 gchar *url = g_strndup (txt->str + match->offset, match->len);
660 gchar *repl = NULL; /* replacement */
662 /* the prefix is NULL: use the one that is already there */
663 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
664 match->prefix ? match->prefix : "", url, url);
666 /* replace the old thing with our hyperlink
667 * replacement thing */
668 g_string_erase (txt, match->offset, match->len);
669 g_string_insert (txt, match->offset, repl);
674 g_free (cursor->data);
677 g_slist_free (match_list);
683 modest_text_utils_get_display_address (gchar *address)
690 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
692 g_strchug (address); /* remove leading whitespace */
694 /* <email@address> from display name */
695 cursor = g_strstr_len (address, strlen(address), "<");
696 if (cursor == address) /* there's nothing else? leave it */
701 /* remove (bla bla) from display name */
702 cursor = g_strstr_len (address, strlen(address), "(");
703 if (cursor == address) /* there's nothing else? leave it */
708 g_strchomp (address); /* remove trailing whitespace */
716 modest_text_utils_get_subject_prefix_len (const gchar *sub)
719 static const gchar* prefix[] = {
720 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
723 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
729 if (g_str_has_prefix(sub, prefix[i])) {
730 int prefix_len = strlen(prefix[i]);
731 if (sub[prefix_len] == ' ')
732 ++prefix_len; /* ignore space after prefix as well */
742 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
747 /* work even when s1 and/or s2 == NULL */
748 if (G_UNLIKELY(s1 == s2))
751 /* if it's not case sensitive */
753 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
755 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
756 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
758 result = strcmp (n1, n2);
767 get_display_date_cache (void)
769 TnyPlatformFactory *fakt;
770 ModestCacheMgr *cache_mgr;
772 fakt = modest_tny_platform_factory_get_instance ();
774 cache_mgr = modest_tny_platform_factory_get_cache_mgr_instance
775 (MODEST_TNY_PLATFORM_FACTORY(fakt));
777 return modest_cache_mgr_get_cache (cache_mgr,
778 MODEST_CACHE_MGR_CACHE_TYPE_DATE_STRING);
784 modest_text_utils_get_display_date (time_t date)
786 static GHashTable *date_cache = NULL;
789 const guint BUF_SIZE = 64;
790 gchar date_buf[BUF_SIZE];
791 gchar now_buf [BUF_SIZE];
794 if (G_UNLIKELY(!date_cache))
795 date_cache = get_display_date_cache ();
797 cached_val = g_hash_table_lookup (date_cache, &date);
803 /* get today's date */
804 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
805 modest_text_utils_strftime (now_buf, BUF_SIZE, "%x", now);
808 /* if this is today, get the time instead of the date */
809 if (strcmp (date_buf, now_buf) == 0)
810 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
812 cached_val = g_strdup(date_buf);
813 g_hash_table_insert (date_cache, (gpointer)&date, (gpointer)cached_val);
819 modest_text_utils_validate_email_address (const gchar *email_address)
822 const gchar *c, *domain;
823 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
825 /* first we validate the name portion (name@domain) */
826 for (c = email_address; *c; c++) {
828 (c == email_address ||
834 if (*c == '\\' && (*++c == ' '))
836 if (*c <= ' ' || *c >= 127)
849 if (*c <= ' ' || *c >= 127)
851 if (strchr(rfc822_specials, *c))
854 if (c == email_address || *(c - 1) == '.')
857 /* next we validate the domain portion (name@domain) */
858 if (!*(domain = ++c))
862 if (c == domain || *(c - 1) == '.')
866 if (*c <= ' ' || *c >= 127)
868 if (strchr(rfc822_specials, *c))
872 return (count >= 1) ? TRUE : FALSE;
879 modest_text_utils_get_display_size (guint size)
882 const guint MB=1024 * KB;
883 const guint GB=1024 * MB;
884 const guint TB=1024 * GB;
887 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
889 return g_strdup_printf (_("%d Kb"), size / KB);
891 return g_strdup_printf (_("%d Mb"), size / MB);
893 return g_strdup_printf (_("%d Gb"), size/ GB);
895 return g_strdup_printf (_("Very big"));