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,
117 const gchar *signature,
119 const time_t sent_date,
122 gchar *retval, *cited;
124 g_return_val_if_fail (text, NULL);
125 g_return_val_if_fail (content_type, NULL);
127 cited = cite (sent_date, from);
129 if (content_type && strcmp (content_type, "text/html") == 0)
130 /* TODO: extract the <body> of the HTML and pass it to
132 retval = modest_text_utils_quote_html (text, cited, limit);
134 retval = modest_text_utils_quote_plain_text (text, cited, limit);
143 modest_text_utils_cite (const gchar *text,
144 const gchar *content_type,
145 const gchar *signature,
152 g_return_val_if_fail (text, NULL);
153 g_return_val_if_fail (content_type, NULL);
156 tmp_sig = g_strdup ("");
157 else if (!strcmp(content_type, "text/html")) {
158 tmp_sig = modest_text_utils_convert_to_html_body(signature);
160 tmp_sig = g_strdup (signature);
163 tmp = cite (sent_date, from);
164 retval = g_strdup_printf ("%s%s%s\n", tmp_sig, tmp, text);
172 modest_text_utils_inline (const gchar *text,
173 const gchar *content_type,
174 const gchar *signature,
178 const gchar *subject)
181 gchar *formatted_signature;
182 const gchar *plain_format = "%s%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
183 const gchar *html_format = \
184 "%s%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
185 "<tr><td>%s</td><td>%s</td></tr>\n" \
186 "<tr><td>%s</td><td>%s</td></tr>\n" \
187 "<tr><td>%s</td><td>%s</td></tr>\n" \
188 "<tr><td>%s</td><td>%s</td></tr>\n" \
192 g_return_val_if_fail (text, NULL);
193 g_return_val_if_fail (content_type, NULL);
194 g_return_val_if_fail (text, NULL);
196 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
198 if (!strcmp (content_type, "text/html"))
199 /* TODO: extract the <body> of the HTML and pass it to
201 format = html_format;
203 format = plain_format;
205 if (signature != NULL) {
206 if (!strcmp (content_type, "text/html")) {
207 formatted_signature = g_strconcat (signature, "<br/>", NULL);
209 formatted_signature = g_strconcat (signature, "\n");
212 formatted_signature = "";
215 return g_strdup_printf (format, formatted_signature,
217 FROM_STRING, (from) ? from : EMPTY_STRING,
218 SENT_STRING, sent_str,
219 TO_STRING, (to) ? to : EMPTY_STRING,
220 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
224 /* just to prevent warnings:
225 * warning: `%x' yields only last 2 digits of year in some locales
228 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
232 /* does not work on old maemo glib:
233 * g_date_set_time_t (&date, timet);
235 localtime_r (&timet, &tm);
237 return strftime(s, max, fmt, &tm);
241 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
245 g_return_val_if_fail (prefix, NULL);
248 return g_strdup (prefix);
250 tmp = g_strchug (g_strdup (subject));
252 if (!strncmp (tmp, prefix, strlen (prefix))) {
256 return g_strdup_printf ("%s %s", prefix, subject);
261 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
263 gchar *dup, *token, *ptr, *result;
264 GString *filtered_emails;
266 g_return_val_if_fail (address_list, NULL);
269 return g_strdup (address_list);
271 /* search for substring */
272 if (!strstr ((const char *) address_list, (const char *) address))
273 return g_strdup (address_list);
275 dup = g_strdup (address_list);
276 filtered_emails = g_string_new (NULL);
278 token = strtok_r (dup, ",", &ptr);
280 while (token != NULL) {
281 /* Add to list if not found */
282 if (!strstr ((const char *) token, (const char *) address)) {
283 if (filtered_emails->len == 0)
284 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
286 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
288 token = strtok_r (NULL, ",", &ptr);
290 result = filtered_emails->str;
294 g_string_free (filtered_emails, FALSE);
300 modest_text_utils_convert_buffer_to_html (GString *html, const gchar *data)
303 gboolean space_seen = FALSE;
308 /* replace with special html chars where needed*/
309 for (i = 0; i != len; ++i) {
312 if (space_seen && kar != ' ') {
313 g_string_append_c (html, ' ');
318 case 0: break; /* ignore embedded \0s */
319 case '<' : g_string_append (html, "<"); break;
320 case '>' : g_string_append (html, ">"); break;
321 case '&' : g_string_append (html, "&"); break;
322 case '"' : g_string_append (html, """); break;
323 case '\'' : g_string_append (html, "'"); break;
324 case '\n' : g_string_append (html, "<br>\n"); break;
325 case '\t' : g_string_append (html, " "); break; /* note the space at the end*/
327 if (space_seen) { /* second space in a row */
328 g_string_append (html, "  ");
334 g_string_append_c (html, kar);
340 modest_text_utils_convert_to_html (const gchar *data)
349 html = g_string_sized_new (1.5 * len); /* just a guess... */
351 g_string_append_printf (html,
353 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
357 modest_text_utils_convert_buffer_to_html (html, data);
359 g_string_append (html, "</body></html>");
360 hyperlinkify_plain_text (html);
362 return g_string_free (html, FALSE);
366 modest_text_utils_convert_to_html_body (const gchar *data)
375 html = g_string_sized_new (1.5 * len); /* just a guess... */
377 modest_text_utils_convert_buffer_to_html (html, data);
379 hyperlinkify_plain_text (html);
381 return g_string_free (html, FALSE);
386 modest_text_utils_split_addresses_list (const gchar *addresses)
388 gchar *current, *start, *last_blank;
389 GSList *result = NULL;
391 start = (gchar *) addresses;
395 while (*current != '\0') {
396 if ((start == current)&&((*current == ' ')||(*current == ','))) {
398 last_blank = current;
399 } else if (*current == ',') {
400 gchar *new_address = NULL;
401 new_address = g_strndup (start, current - last_blank);
402 result = g_slist_prepend (result, new_address);
405 } else if (*current == '\"') {
406 if (current == start) {
410 while ((*current != '\"')&&(*current != '\0'))
417 if (start != current) {
418 gchar *new_address = NULL;
419 new_address = g_strndup (start, current - last_blank);
420 result = g_slist_prepend (result, new_address);
423 result = g_slist_reverse (result);
429 modest_text_utils_address_range_at_position (const gchar *recipients_list,
434 gchar *current = NULL;
435 gint range_start = 0;
438 gboolean is_quoted = FALSE;
441 for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
442 gunichar c = g_utf8_get_char (current);
444 if ((c == ',') && (!is_quoted)) {
445 if (index < position) {
446 range_start = index + 1;
450 } else if (c == '\"') {
451 is_quoted = !is_quoted;
452 } else if ((c == ' ') &&(range_start == index)) {
460 *start = range_start;
466 /* ******************************************************************* */
467 /* ************************* UTILIY FUNCTIONS ************************ */
468 /* ******************************************************************* */
471 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
477 return g_string_new("");
485 gs = g_string_new_len (i0, iter - i0);
489 get_indent_level (const char *l)
506 /* if we hit the signature marker "-- ", we return -(indent + 1). This
507 * stops reformatting.
509 if (strcmp (l, "-- ") == 0) {
517 unquote_line (GString * l)
532 g_string_erase (l, 0, p - l->str);
536 append_quoted (GString * buf, int indent, const GString * str,
541 indent = indent < 0 ? abs (indent) - 1 : indent;
542 for (i = 0; i <= indent; i++) {
543 g_string_append (buf, "> ");
546 g_string_append_len (buf, str->str, cutpoint);
548 g_string_append (buf, str->str);
550 g_string_append (buf, "\n");
554 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
557 const gchar *pos, *last;
560 indent = indent < 0 ? abs (indent) - 1 : indent;
564 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
566 if ((index + 2 * indent > limit) && last) {
570 if (g_unichar_isspace (uni[index])) {
573 pos = g_utf8_next_char (pos);
581 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
586 if (last + 2 * indent < limit)
589 for (i = strlen (s); i > 0; i--) {
591 if (i + 2 * indent <= limit) {
602 get_breakpoint (const gchar * s, const gint indent, const gint limit)
605 if (g_utf8_validate (s, -1, NULL)) {
606 return get_breakpoint_utf8 (s, indent, limit);
607 } else { /* assume ASCII */
608 //g_warning("invalid UTF-8 in msg");
609 return get_breakpoint_ascii (s, indent, limit);
614 cite (const time_t sent_date, const gchar *from)
618 /* format sent_date */
619 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
620 return g_strdup_printf (N_("On %s, %s wrote:\n"),
622 (from) ? from : EMPTY_STRING);
627 modest_text_utils_quote_plain_text (const gchar *text,
632 gint indent, breakpoint, rem_indent = 0;
633 GString *q, *l, *remaining;
636 /* remaining will store the rest of the line if we have to break it */
637 q = g_string_new (cite);
638 remaining = g_string_new ("");
643 l = get_next_line (text, len, iter);
644 iter = iter + l->len + 1;
645 indent = get_indent_level (l->str);
648 if (remaining->len) {
649 if (l->len && indent == rem_indent) {
650 g_string_prepend (l, " ");
651 g_string_prepend (l, remaining->str);
655 get_breakpoint (remaining->str,
658 append_quoted (q, rem_indent,
659 remaining, breakpoint);
660 g_string_erase (remaining, 0,
662 if (remaining->str[0] == ' ') {
663 g_string_erase (remaining, 0,
666 } while (remaining->len);
669 g_string_free (remaining, TRUE);
670 breakpoint = get_breakpoint (l->str, indent, limit);
671 remaining = g_string_new (l->str + breakpoint);
672 if (remaining->str[0] == ' ') {
673 g_string_erase (remaining, 0, 1);
676 append_quoted (q, indent, l, breakpoint);
677 g_string_free (l, TRUE);
678 } while ((iter < text + len) || (remaining->str[0]));
680 return g_string_free (q, FALSE);
684 modest_text_utils_quote_html (const gchar *text,
688 const gchar *format = \
689 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
693 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
697 return g_strdup_printf (format, cite, text);
701 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
703 return match2->offset - match1->offset;
709 * check if the match is inside an existing match... */
711 chk_partial_match (const url_match_t *match, guint* offset)
713 if (*offset >= match->offset && *offset < match->offset + match->len)
718 get_url_matches (GString *txt)
721 guint rv, i, offset = 0;
722 GSList *match_list = NULL;
724 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
725 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
727 /* initalize the regexps */
728 for (i = 0; i != pattern_num; ++i) {
729 patterns[i].preg = g_slice_new0 (regex_t);
731 /* this should not happen */
732 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
733 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
735 /* find all the matches */
736 for (i = 0; i != pattern_num; ++i) {
740 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
741 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
742 break; /* try next regexp */
747 /* FIXME: optimize this */
748 /* to avoid partial matches on something that was already found... */
749 /* check_partial_match will put -1 in the data ptr if that is the case */
750 test_offset = offset + rm.rm_so;
751 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
753 /* make a list of our matches (<offset, len, prefix> tupels)*/
754 if (test_offset != -1) {
755 url_match_t *match = g_slice_new (url_match_t);
756 match->offset = offset + rm.rm_so;
757 match->len = rm.rm_eo - rm.rm_so;
758 match->prefix = patterns[i].prefix;
759 match_list = g_slist_prepend (match_list, match);
765 for (i = 0; i != pattern_num; ++i) {
766 regfree (patterns[i].preg);
767 g_slice_free (regex_t, patterns[i].preg);
768 } /* don't free patterns itself -- it's static */
770 /* now sort the list, so the matches are in reverse order of occurence.
771 * that way, we can do the replacements starting from the end, so we don't need
772 * to recalculate the offsets
774 match_list = g_slist_sort (match_list,
775 (GCompareFunc)cmp_offsets_reverse);
782 hyperlinkify_plain_text (GString *txt)
785 GSList *match_list = get_url_matches (txt);
787 /* we will work backwards, so the offsets stay valid */
788 for (cursor = match_list; cursor; cursor = cursor->next) {
790 url_match_t *match = (url_match_t*) cursor->data;
791 gchar *url = g_strndup (txt->str + match->offset, match->len);
792 gchar *repl = NULL; /* replacement */
794 /* the prefix is NULL: use the one that is already there */
795 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
796 match->prefix ? match->prefix : EMPTY_STRING,
799 /* replace the old thing with our hyperlink
800 * replacement thing */
801 g_string_erase (txt, match->offset, match->len);
802 g_string_insert (txt, match->offset, repl);
807 g_slice_free (url_match_t, match);
810 g_slist_free (match_list);
816 modest_text_utils_get_display_address (gchar *address)
823 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
825 g_strchug (address); /* remove leading whitespace */
827 /* <email@address> from display name */
828 cursor = g_strstr_len (address, strlen(address), "<");
829 if (cursor == address) /* there's nothing else? leave it */
834 /* remove (bla bla) from display name */
835 cursor = g_strstr_len (address, strlen(address), "(");
836 if (cursor == address) /* there's nothing else? leave it */
841 g_strchomp (address); /* remove trailing whitespace */
849 modest_text_utils_get_subject_prefix_len (const gchar *sub)
852 static const gchar* prefix[] = {
853 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
856 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
862 if (g_str_has_prefix(sub, prefix[i])) {
863 int prefix_len = strlen(prefix[i]);
864 if (sub[prefix_len] == ' ')
865 ++prefix_len; /* ignore space after prefix as well */
875 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
880 /* work even when s1 and/or s2 == NULL */
881 if (G_UNLIKELY(s1 == s2))
884 /* if it's not case sensitive */
886 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
888 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
889 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
891 result = strcmp (n1, n2);
901 modest_text_utils_get_display_date (time_t date)
904 const guint BUF_SIZE = 64;
905 gchar date_buf[BUF_SIZE];
906 gchar now_buf [BUF_SIZE];
910 modest_text_utils_strftime (date_buf, BUF_SIZE, "%d/%m/%Y", date);
911 modest_text_utils_strftime (now_buf, BUF_SIZE, "%d/%m/%Y", now); /* today */
912 /* modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date); */
913 /* modest_text_utils_strftime (now_buf, BUF_SIZE, "%x", now); /\* today *\/ */
915 /* if this is today, get the time instead of the date */
916 if (strcmp (date_buf, now_buf) == 0)
917 modest_text_utils_strftime (date_buf, BUF_SIZE, "%H:%M %P", date);
919 return g_strdup(date_buf);
923 modest_text_utils_validate_email_address (const gchar *email_address)
926 const gchar *c = NULL, *domain = NULL;
927 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
929 /* first we validate the name portion (name@domain) */
930 for (c = email_address; *c; c++) {
932 (c == email_address ||
938 if (*c == '\\' && (*++c == ' '))
940 if (*c <= ' ' || *c >= 127)
953 if (*c <= ' ' || *c >= 127)
955 if (strchr(rfc822_specials, *c))
958 if (c == email_address || *(c - 1) == '.')
961 /* next we validate the domain portion (name@domain) */
962 if (!*(domain = ++c))
966 if (c == domain || *(c - 1) == '.')
970 if (*c <= ' ' || *c >= 127)
972 if (strchr(rfc822_specials, *c))
976 return (count >= 1) ? TRUE : FALSE;
983 modest_text_utils_get_display_size (guint size)
986 const guint MB=1024 * KB;
987 const guint GB=1024 * MB;
988 const guint TB=1024 * GB;
991 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
993 return g_strdup_printf (_("%d Kb"), size / KB);
995 return g_strdup_printf (_("%d Mb"), size / MB);
997 return g_strdup_printf (_("%d Gb"), size/ GB);
999 return g_strdup_printf (_("Very big"));