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:")
51 #define EMPTY_STRING ""
54 * we need these regexps to find URLs in plain text e-mails
56 typedef struct _url_match_pattern_t url_match_pattern_t;
57 struct _url_match_pattern_t {
63 typedef struct _url_match_t url_match_t;
70 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
71 { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
73 { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
75 { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
77 { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
79 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
81 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
86 static gchar* cite (const time_t sent_date, const gchar *from);
87 static void hyperlinkify_plain_text (GString *txt);
88 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
89 static void chk_partial_match (const url_match_t *match, guint* offset);
90 static GSList* get_url_matches (GString *txt);
92 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
93 static int get_indent_level (const char *l);
94 static void unquote_line (GString * l);
95 static void append_quoted (GString * buf, const int indent, const GString * str,
97 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
98 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
99 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
101 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
105 static gchar* modest_text_utils_quote_html (const gchar *text,
110 /* ******************************************************************* */
111 /* ************************* PUBLIC FUNCTIONS ************************ */
112 /* ******************************************************************* */
115 modest_text_utils_quote (const gchar *text,
116 const gchar *content_type,
118 const time_t sent_date,
121 gchar *retval, *cited;
123 g_return_val_if_fail (text, NULL);
124 g_return_val_if_fail (content_type, 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);
152 tmp = cite (sent_date, from);
153 retval = g_strdup_printf ("%s%s\n", tmp, text);
160 modest_text_utils_inline (const gchar *text,
161 const gchar *content_type,
165 const gchar *subject)
168 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
169 const gchar *html_format = \
170 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
171 "<tr><td>%s</td><td>%s</td></tr>\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" \
178 g_return_val_if_fail (text, NULL);
179 g_return_val_if_fail (content_type, NULL);
180 g_return_val_if_fail (text, 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,
193 FROM_STRING, (from) ? from : EMPTY_STRING,
194 SENT_STRING, sent_str,
195 TO_STRING, (to) ? to : EMPTY_STRING,
196 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
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)
208 /* does not work on old maemo glib:
209 * g_date_set_time_t (&date, timet);
211 g_date_set_time (&date, (GTime) timet);
213 return g_date_strftime (s, max, fmt, (const GDate*) &date);
217 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
221 g_return_val_if_fail (prefix, NULL);
224 return g_strdup (prefix);
226 tmp = g_strchug (g_strdup (subject));
228 if (!strncmp (tmp, prefix, strlen (prefix))) {
232 return g_strdup_printf ("%s %s", prefix, subject);
237 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
239 gchar *dup, *token, *ptr, *result;
240 GString *filtered_emails;
242 g_return_val_if_fail (address_list, NULL);
245 return g_strdup (address_list);
247 /* search for substring */
248 if (!strstr ((const char *) address_list, (const char *) address))
249 return g_strdup (address_list);
251 dup = g_strdup (address_list);
252 filtered_emails = g_string_new (NULL);
254 token = strtok_r (dup, ",", &ptr);
256 while (token != NULL) {
257 /* Add to list if not found */
258 if (!strstr ((const char *) token, (const char *) address)) {
259 if (filtered_emails->len == 0)
260 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
262 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
264 token = strtok_r (NULL, ",", &ptr);
266 result = filtered_emails->str;
270 g_string_free (filtered_emails, FALSE);
276 modest_text_utils_convert_to_html (const gchar *data)
279 gboolean first_space = TRUE;
287 html = g_string_sized_new (len + 100); /* just a guess... */
289 g_string_append_printf (html,
292 "<meta http-equiv=\"content-type\""
293 " content=\"text/html; charset=utf8\">"
297 /* replace with special html chars where needed*/
298 for (i = 0; i != len; ++i) {
302 case 0: break; /* ignore embedded \0s */
303 case '<' : g_string_append (html, "<"); break;
304 case '>' : g_string_append (html, ">"); break;
305 case '&' : g_string_append (html, """); break;
306 case '\n': g_string_append (html, "<br>\n"); break;
309 g_string_append (html, first_space ? " " : " ");
311 } else if (kar == '\t')
312 g_string_append (html, " ");
316 /* optimization trick: accumulate 'normal' chars, then copy */
318 kar = data [++charnum + i];
320 } while ((i + charnum < len) &&
321 (kar > '>' || (kar != '<' && kar != '>'
322 && kar != '&' && kar != ' '
323 && kar != '\n' && kar != '\t')));
324 g_string_append_len (html, &data[i], charnum);
330 g_string_append (html, "</tt></body></html>");
331 hyperlinkify_plain_text (html);
333 return g_string_free (html, FALSE);
337 modest_text_utils_split_addresses_list (const gchar *addresses)
339 gchar *current, *start, *last_blank;
340 GSList *result = NULL;
342 start = (gchar *) addresses;
346 while (*current != '\0') {
347 if ((start == current)&&((*current == ' ')||(*current == ','))) {
349 last_blank = current;
350 } else if (*current == ',') {
351 gchar *new_address = NULL;
352 new_address = g_strndup (start, current - last_blank);
353 result = g_slist_prepend (result, new_address);
356 } else if (*current == '\"') {
357 if (current == start) {
361 while ((*current != '\"')&&(*current != '\0'))
368 if (start != current) {
369 gchar *new_address = NULL;
370 new_address = g_strndup (start, current - last_blank);
371 result = g_slist_prepend (result, new_address);
374 result = g_slist_reverse (result);
380 modest_text_utils_address_range_at_position (const gchar *recipients_list,
385 gchar *current = NULL;
386 gint range_start = 0;
389 gboolean is_quoted = FALSE;
392 for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
393 gunichar c = g_utf8_get_char (current);
395 if ((c == ',') && (!is_quoted)) {
396 if (index < position) {
397 range_start = index + 1;
401 } else if (c == '\"') {
402 is_quoted = !is_quoted;
403 } else if ((c == ' ') &&(range_start == index)) {
411 *start = range_start;
417 /* ******************************************************************* */
418 /* ************************* UTILIY FUNCTIONS ************************ */
419 /* ******************************************************************* */
422 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
428 return g_string_new("");
436 gs = g_string_new_len (i0, iter - i0);
440 get_indent_level (const char *l)
457 /* if we hit the signature marker "-- ", we return -(indent + 1). This
458 * stops reformatting.
460 if (strcmp (l, "-- ") == 0) {
468 unquote_line (GString * l)
483 g_string_erase (l, 0, p - l->str);
487 append_quoted (GString * buf, int indent, const GString * str,
492 indent = indent < 0 ? abs (indent) - 1 : indent;
493 for (i = 0; i <= indent; i++) {
494 g_string_append (buf, "> ");
497 g_string_append_len (buf, str->str, cutpoint);
499 g_string_append (buf, str->str);
501 g_string_append (buf, "\n");
505 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
508 const gchar *pos, *last;
511 indent = indent < 0 ? abs (indent) - 1 : indent;
515 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
517 if ((index + 2 * indent > limit) && last) {
521 if (g_unichar_isspace (uni[index])) {
524 pos = g_utf8_next_char (pos);
532 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
537 if (last + 2 * indent < limit)
540 for (i = strlen (s); i > 0; i--) {
542 if (i + 2 * indent <= limit) {
553 get_breakpoint (const gchar * s, const gint indent, const gint limit)
556 if (g_utf8_validate (s, -1, NULL)) {
557 return get_breakpoint_utf8 (s, indent, limit);
558 } else { /* assume ASCII */
559 //g_warning("invalid UTF-8 in msg");
560 return get_breakpoint_ascii (s, indent, limit);
565 cite (const time_t sent_date, const gchar *from)
569 /* format sent_date */
570 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
571 return g_strdup_printf (N_("On %s, %s wrote:\n"),
573 (from) ? from : EMPTY_STRING);
578 modest_text_utils_quote_plain_text (const gchar *text,
583 gint indent, breakpoint, rem_indent = 0;
584 GString *q, *l, *remaining;
587 /* remaining will store the rest of the line if we have to break it */
588 q = g_string_new (cite);
589 remaining = g_string_new ("");
594 l = get_next_line (text, len, iter);
595 iter = iter + l->len + 1;
596 indent = get_indent_level (l->str);
599 if (remaining->len) {
600 if (l->len && indent == rem_indent) {
601 g_string_prepend (l, " ");
602 g_string_prepend (l, remaining->str);
606 get_breakpoint (remaining->str,
609 append_quoted (q, rem_indent,
610 remaining, breakpoint);
611 g_string_erase (remaining, 0,
613 if (remaining->str[0] == ' ') {
614 g_string_erase (remaining, 0,
617 } while (remaining->len);
620 g_string_free (remaining, TRUE);
621 breakpoint = get_breakpoint (l->str, indent, limit);
622 remaining = g_string_new (l->str + breakpoint);
623 if (remaining->str[0] == ' ') {
624 g_string_erase (remaining, 0, 1);
627 append_quoted (q, indent, l, breakpoint);
628 g_string_free (l, TRUE);
629 } while ((iter < text + len) || (remaining->str[0]));
631 return g_string_free (q, FALSE);
635 modest_text_utils_quote_html (const gchar *text,
639 const gchar *format = \
640 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
644 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
648 return g_strdup_printf (format, cite, text);
652 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
654 return match2->offset - match1->offset;
660 * check if the match is inside an existing match... */
662 chk_partial_match (const url_match_t *match, guint* offset)
664 if (*offset >= match->offset && *offset < match->offset + match->len)
669 get_url_matches (GString *txt)
672 guint rv, i, offset = 0;
673 GSList *match_list = NULL;
675 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
676 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
678 /* initalize the regexps */
679 for (i = 0; i != pattern_num; ++i) {
680 patterns[i].preg = g_slice_new0 (regex_t);
682 /* this should not happen */
683 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
684 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
686 /* find all the matches */
687 for (i = 0; i != pattern_num; ++i) {
691 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
692 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
693 break; /* try next regexp */
698 /* FIXME: optimize this */
699 /* to avoid partial matches on something that was already found... */
700 /* check_partial_match will put -1 in the data ptr if that is the case */
701 test_offset = offset + rm.rm_so;
702 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
704 /* make a list of our matches (<offset, len, prefix> tupels)*/
705 if (test_offset != -1) {
706 url_match_t *match = g_slice_new (url_match_t);
707 match->offset = offset + rm.rm_so;
708 match->len = rm.rm_eo - rm.rm_so;
709 match->prefix = patterns[i].prefix;
710 match_list = g_slist_prepend (match_list, match);
716 for (i = 0; i != pattern_num; ++i) {
717 regfree (patterns[i].preg);
718 g_slice_free (regex_t, patterns[i].preg);
719 } /* don't free patterns itself -- it's static */
721 /* now sort the list, so the matches are in reverse order of occurence.
722 * that way, we can do the replacements starting from the end, so we don't need
723 * to recalculate the offsets
725 match_list = g_slist_sort (match_list,
726 (GCompareFunc)cmp_offsets_reverse);
733 hyperlinkify_plain_text (GString *txt)
736 GSList *match_list = get_url_matches (txt);
738 /* we will work backwards, so the offsets stay valid */
739 for (cursor = match_list; cursor; cursor = cursor->next) {
741 url_match_t *match = (url_match_t*) cursor->data;
742 gchar *url = g_strndup (txt->str + match->offset, match->len);
743 gchar *repl = NULL; /* replacement */
745 /* the prefix is NULL: use the one that is already there */
746 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
747 match->prefix ? match->prefix : EMPTY_STRING,
750 /* replace the old thing with our hyperlink
751 * replacement thing */
752 g_string_erase (txt, match->offset, match->len);
753 g_string_insert (txt, match->offset, repl);
758 g_slice_free (url_match_t, match);
761 g_slist_free (match_list);
767 modest_text_utils_get_display_address (gchar *address)
774 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
776 g_strchug (address); /* remove leading whitespace */
778 /* <email@address> from display name */
779 cursor = g_strstr_len (address, strlen(address), "<");
780 if (cursor == address) /* there's nothing else? leave it */
785 /* remove (bla bla) from display name */
786 cursor = g_strstr_len (address, strlen(address), "(");
787 if (cursor == address) /* there's nothing else? leave it */
792 g_strchomp (address); /* remove trailing whitespace */
800 modest_text_utils_get_subject_prefix_len (const gchar *sub)
803 static const gchar* prefix[] = {
804 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
807 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
813 if (g_str_has_prefix(sub, prefix[i])) {
814 int prefix_len = strlen(prefix[i]);
815 if (sub[prefix_len] == ' ')
816 ++prefix_len; /* ignore space after prefix as well */
826 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
831 /* work even when s1 and/or s2 == NULL */
832 if (G_UNLIKELY(s1 == s2))
835 /* if it's not case sensitive */
837 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
839 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
840 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
842 result = strcmp (n1, n2);
852 modest_text_utils_get_display_date (time_t date)
855 const guint BUF_SIZE = 64;
856 gchar date_buf[BUF_SIZE];
857 gchar now_buf [BUF_SIZE];
861 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
862 modest_text_utils_strftime (now_buf, BUF_SIZE, "%x", now); /* today */
864 /* if this is today, get the time instead of the date */
865 if (strcmp (date_buf, now_buf) == 0)
866 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
868 return g_strdup(date_buf);
872 modest_text_utils_validate_email_address (const gchar *email_address)
875 const gchar *c = NULL, *domain = NULL;
876 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
878 /* first we validate the name portion (name@domain) */
879 for (c = email_address; *c; c++) {
881 (c == email_address ||
887 if (*c == '\\' && (*++c == ' '))
889 if (*c <= ' ' || *c >= 127)
902 if (*c <= ' ' || *c >= 127)
904 if (strchr(rfc822_specials, *c))
907 if (c == email_address || *(c - 1) == '.')
910 /* next we validate the domain portion (name@domain) */
911 if (!*(domain = ++c))
915 if (c == domain || *(c - 1) == '.')
919 if (*c <= ' ' || *c >= 127)
921 if (strchr(rfc822_specials, *c))
925 return (count >= 1) ? TRUE : FALSE;
932 modest_text_utils_get_display_size (guint size)
935 const guint MB=1024 * KB;
936 const guint GB=1024 * MB;
937 const guint TB=1024 * GB;
940 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
942 return g_strdup_printf (_("%d Kb"), size / KB);
944 return g_strdup_printf (_("%d Mb"), size / MB);
946 return g_strdup_printf (_("%d Gb"), size/ GB);
948 return g_strdup_printf (_("Very big"));