1 /* Copyright (c) 2006, Nokia Corporation
10 #include <glib/gi18n.h>
12 #include <modest-text-utils.h>
17 #endif /*HAVE_CONFIG_H */
20 #define FORWARD_STRING _("-----Forwarded Message-----")
21 #define FROM_STRING _("From:")
22 #define SENT_STRING _("Sent:")
23 #define TO_STRING _("To:")
24 #define SUBJECT_STRING _("Subject:")
25 #define EMPTY_STRING ""
28 * we need these regexps to find URLs in plain text e-mails
30 typedef struct _url_match_pattern_t url_match_pattern_t;
31 struct _url_match_pattern_t {
37 typedef struct _url_match_t url_match_t;
44 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
45 { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
47 { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
49 { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
51 { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
53 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
55 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
60 static gchar* cite (const time_t sent_date, const gchar *from);
61 static void hyperlinkify_plain_text (GString *txt);
62 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
63 static void chk_partial_match (const url_match_t *match, guint* offset);
64 static GSList* get_url_matches (GString *txt);
66 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
67 static int get_indent_level (const char *l);
68 static void unquote_line (GString * l);
69 static void append_quoted (GString * buf, const int indent, const GString * str,
71 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
72 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
73 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
75 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
79 static gchar* modest_text_utils_quote_html (const gchar *text,
84 /* ******************************************************************* */
85 /* ************************* PUBLIC FUNCTIONS ************************ */
86 /* ******************************************************************* */
89 modest_text_utils_quote (const gchar *text,
90 const gchar *content_type,
92 const time_t sent_date,
95 gchar *retval, *cited;
97 g_return_val_if_fail (text, NULL);
98 g_return_val_if_fail (content_type, NULL);
100 cited = cite (sent_date, from);
102 if (content_type && strcmp (content_type, "text/html") == 0)
103 /* TODO: extract the <body> of the HTML and pass it to
105 retval = modest_text_utils_quote_html (text, cited, limit);
107 retval = modest_text_utils_quote_plain_text (text, cited, limit);
116 modest_text_utils_cite (const gchar *text,
117 const gchar *content_type,
123 g_return_val_if_fail (text, NULL);
124 g_return_val_if_fail (content_type, NULL);
126 tmp = cite (sent_date, from);
127 retval = g_strdup_printf ("%s%s\n", tmp, text);
134 modest_text_utils_inline (const gchar *text,
135 const gchar *content_type,
139 const gchar *subject)
142 const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
143 const gchar *html_format = \
144 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
145 "<tr><td>%s</td><td>%s</td></tr>\n" \
146 "<tr><td>%s</td><td>%s</td></tr>\n" \
147 "<tr><td>%s</td><td>%s</td></tr>\n" \
148 "<tr><td>%s</td><td>%s</td></tr>\n" \
152 g_return_val_if_fail (text, NULL);
153 g_return_val_if_fail (content_type, NULL);
154 g_return_val_if_fail (text, NULL);
156 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
158 if (!strcmp (content_type, "text/html"))
159 /* TODO: extract the <body> of the HTML and pass it to
161 format = html_format;
163 format = plain_format;
165 return g_strdup_printf (format,
167 FROM_STRING, (from) ? from : EMPTY_STRING,
168 SENT_STRING, sent_str,
169 TO_STRING, (to) ? to : EMPTY_STRING,
170 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
174 /* just to prevent warnings:
175 * warning: `%x' yields only last 2 digits of year in some locales
178 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
182 /* does not work on old maemo glib:
183 * g_date_set_time_t (&date, timet);
185 g_date_set_time (&date, (GTime) timet);
187 return g_date_strftime (s, max, fmt, (const GDate*) &date);
191 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
195 g_return_val_if_fail (prefix, NULL);
198 return g_strdup (prefix);
200 tmp = g_strchug (g_strdup (subject));
202 if (!strncmp (tmp, prefix, strlen (prefix))) {
206 return g_strdup_printf ("%s %s", prefix, subject);
211 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
213 gchar *dup, *token, *ptr, *result;
214 GString *filtered_emails;
216 g_return_val_if_fail (address_list, NULL);
219 return g_strdup (address_list);
221 /* search for substring */
222 if (!strstr ((const char *) address_list, (const char *) address))
223 return g_strdup (address_list);
225 dup = g_strdup (address_list);
226 filtered_emails = g_string_new (NULL);
228 token = strtok_r (dup, ",", &ptr);
230 while (token != NULL) {
231 /* Add to list if not found */
232 if (!strstr ((const char *) token, (const char *) address)) {
233 if (filtered_emails->len == 0)
234 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
236 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
238 token = strtok_r (NULL, ",", &ptr);
240 result = filtered_emails->str;
244 g_string_free (filtered_emails, FALSE);
250 modest_text_utils_convert_to_html (const gchar *data)
253 gboolean first_space = TRUE;
261 html = g_string_sized_new (len + 100); /* just a guess... */
263 g_string_append_printf (html,
266 "<meta http-equiv=\"content-type\""
267 " content=\"text/html; charset=utf8\">"
271 /* replace with special html chars where needed*/
272 for (i = 0; i != len; ++i) {
276 case 0: break; /* ignore embedded \0s */
277 case '<' : g_string_append (html, "<"); break;
278 case '>' : g_string_append (html, ">"); break;
279 case '&' : g_string_append (html, """); break;
280 case '\n': g_string_append (html, "<br>\n"); break;
283 g_string_append (html, first_space ? " " : " ");
285 } else if (kar == '\t')
286 g_string_append (html, " ");
290 /* optimization trick: accumulate 'normal' chars, then copy */
292 kar = data [++charnum + i];
294 } while ((i + charnum < len) &&
295 (kar > '>' || (kar != '<' && kar != '>'
296 && kar != '&' && kar != ' '
297 && kar != '\n' && kar != '\t')));
298 g_string_append_len (html, &data[i], charnum);
304 g_string_append (html, "</tt></body></html>");
305 hyperlinkify_plain_text (html);
307 return g_string_free (html, FALSE);
311 modest_text_utils_split_addresses_list (const gchar *addresses)
313 gchar *current, *start, *last_blank;
314 GSList *result = NULL;
316 start = (gchar *) addresses;
320 while (*current != '\0') {
321 if ((start == current)&&((*current == ' ')||(*current == ','))) {
323 last_blank = current;
324 } else if (*current == ',') {
325 gchar *new_address = NULL;
326 new_address = g_strndup (start, current - last_blank);
327 result = g_slist_prepend (result, new_address);
330 } else if (*current == '\"') {
331 if (current == start) {
335 while ((*current != '\"')&&(*current != '\0'))
342 if (start != current) {
343 gchar *new_address = NULL;
344 new_address = g_strndup (start, current - last_blank);
345 result = g_slist_prepend (result, new_address);
348 result = g_slist_reverse (result);
354 modest_text_utils_address_range_at_position (const gchar *recipients_list,
359 gchar *current = NULL;
360 gint range_start = 0;
363 gboolean is_quoted = FALSE;
366 for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
367 gunichar c = g_utf8_get_char (current);
369 if ((c == ',') && (!is_quoted)) {
370 if (index < position) {
371 range_start = index + 1;
375 } else if (c == '\"') {
376 is_quoted = !is_quoted;
377 } else if ((c == ' ') &&(range_start == index)) {
385 *start = range_start;
391 /* ******************************************************************* */
392 /* ************************* UTILIY FUNCTIONS ************************ */
393 /* ******************************************************************* */
396 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
402 return g_string_new("");
410 gs = g_string_new_len (i0, iter - i0);
414 get_indent_level (const char *l)
431 /* if we hit the signature marker "-- ", we return -(indent + 1). This
432 * stops reformatting.
434 if (strcmp (l, "-- ") == 0) {
442 unquote_line (GString * l)
457 g_string_erase (l, 0, p - l->str);
461 append_quoted (GString * buf, int indent, const GString * str,
466 indent = indent < 0 ? abs (indent) - 1 : indent;
467 for (i = 0; i <= indent; i++) {
468 g_string_append (buf, "> ");
471 g_string_append_len (buf, str->str, cutpoint);
473 g_string_append (buf, str->str);
475 g_string_append (buf, "\n");
479 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
482 const gchar *pos, *last;
485 indent = indent < 0 ? abs (indent) - 1 : indent;
489 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
491 if ((index + 2 * indent > limit) && last) {
495 if (g_unichar_isspace (uni[index])) {
498 pos = g_utf8_next_char (pos);
506 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
511 if (last + 2 * indent < limit)
514 for (i = strlen (s); i > 0; i--) {
516 if (i + 2 * indent <= limit) {
527 get_breakpoint (const gchar * s, const gint indent, const gint limit)
530 if (g_utf8_validate (s, -1, NULL)) {
531 return get_breakpoint_utf8 (s, indent, limit);
532 } else { /* assume ASCII */
533 //g_warning("invalid UTF-8 in msg");
534 return get_breakpoint_ascii (s, indent, limit);
539 cite (const time_t sent_date, const gchar *from)
543 /* format sent_date */
544 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
545 return g_strdup_printf (N_("On %s, %s wrote:\n"),
547 (from) ? from : EMPTY_STRING);
552 modest_text_utils_quote_plain_text (const gchar *text,
557 gint indent, breakpoint, rem_indent = 0;
558 GString *q, *l, *remaining;
561 /* remaining will store the rest of the line if we have to break it */
562 q = g_string_new (cite);
563 remaining = g_string_new ("");
568 l = get_next_line (text, len, iter);
569 iter = iter + l->len + 1;
570 indent = get_indent_level (l->str);
573 if (remaining->len) {
574 if (l->len && indent == rem_indent) {
575 g_string_prepend (l, " ");
576 g_string_prepend (l, remaining->str);
580 get_breakpoint (remaining->str,
583 append_quoted (q, rem_indent,
584 remaining, breakpoint);
585 g_string_erase (remaining, 0,
587 if (remaining->str[0] == ' ') {
588 g_string_erase (remaining, 0,
591 } while (remaining->len);
594 g_string_free (remaining, TRUE);
595 breakpoint = get_breakpoint (l->str, indent, limit);
596 remaining = g_string_new (l->str + breakpoint);
597 if (remaining->str[0] == ' ') {
598 g_string_erase (remaining, 0, 1);
601 append_quoted (q, indent, l, breakpoint);
602 g_string_free (l, TRUE);
603 } while ((iter < text + len) || (remaining->str[0]));
605 return g_string_free (q, FALSE);
609 modest_text_utils_quote_html (const gchar *text,
613 const gchar *format = \
614 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
618 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
622 return g_strdup_printf (format, cite, text);
626 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
628 return match2->offset - match1->offset;
634 * check if the match is inside an existing match... */
636 chk_partial_match (const url_match_t *match, guint* offset)
638 if (*offset >= match->offset && *offset < match->offset + match->len)
643 get_url_matches (GString *txt)
646 guint rv, i, offset = 0;
647 GSList *match_list = NULL;
649 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
650 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
652 /* initalize the regexps */
653 for (i = 0; i != pattern_num; ++i) {
654 patterns[i].preg = g_slice_new0 (regex_t);
656 /* this should not happen */
657 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
658 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
660 /* find all the matches */
661 for (i = 0; i != pattern_num; ++i) {
665 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
666 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
667 break; /* try next regexp */
672 /* FIXME: optimize this */
673 /* to avoid partial matches on something that was already found... */
674 /* check_partial_match will put -1 in the data ptr if that is the case */
675 test_offset = offset + rm.rm_so;
676 g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
678 /* make a list of our matches (<offset, len, prefix> tupels)*/
679 if (test_offset != -1) {
680 url_match_t *match = g_slice_new (url_match_t);
681 match->offset = offset + rm.rm_so;
682 match->len = rm.rm_eo - rm.rm_so;
683 match->prefix = patterns[i].prefix;
684 match_list = g_slist_prepend (match_list, match);
690 for (i = 0; i != pattern_num; ++i) {
691 regfree (patterns[i].preg);
692 g_slice_free (regex_t, patterns[i].preg);
693 } /* don't free patterns itself -- it's static */
695 /* now sort the list, so the matches are in reverse order of occurence.
696 * that way, we can do the replacements starting from the end, so we don't need
697 * to recalculate the offsets
699 match_list = g_slist_sort (match_list,
700 (GCompareFunc)cmp_offsets_reverse);
707 hyperlinkify_plain_text (GString *txt)
710 GSList *match_list = get_url_matches (txt);
712 /* we will work backwards, so the offsets stay valid */
713 for (cursor = match_list; cursor; cursor = cursor->next) {
715 url_match_t *match = (url_match_t*) cursor->data;
716 gchar *url = g_strndup (txt->str + match->offset, match->len);
717 gchar *repl = NULL; /* replacement */
719 /* the prefix is NULL: use the one that is already there */
720 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
721 match->prefix ? match->prefix : EMPTY_STRING,
724 /* replace the old thing with our hyperlink
725 * replacement thing */
726 g_string_erase (txt, match->offset, match->len);
727 g_string_insert (txt, match->offset, repl);
732 g_slice_free (url_match_t, match);
735 g_slist_free (match_list);
741 modest_text_utils_get_display_address (gchar *address)
748 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
750 g_strchug (address); /* remove leading whitespace */
752 /* <email@address> from display name */
753 cursor = g_strstr_len (address, strlen(address), "<");
754 if (cursor == address) /* there's nothing else? leave it */
759 /* remove (bla bla) from display name */
760 cursor = g_strstr_len (address, strlen(address), "(");
761 if (cursor == address) /* there's nothing else? leave it */
766 g_strchomp (address); /* remove trailing whitespace */
774 modest_text_utils_get_subject_prefix_len (const gchar *sub)
777 static const gchar* prefix[] = {
778 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
781 if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
787 if (g_str_has_prefix(sub, prefix[i])) {
788 int prefix_len = strlen(prefix[i]);
789 if (sub[prefix_len] == ' ')
790 ++prefix_len; /* ignore space after prefix as well */
800 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
805 /* work even when s1 and/or s2 == NULL */
806 if (G_UNLIKELY(s1 == s2))
809 /* if it's not case sensitive */
811 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
813 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
814 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
816 result = strcmp (n1, n2);
826 modest_text_utils_get_display_date (time_t date)
829 const guint BUF_SIZE = 64;
830 gchar date_buf[BUF_SIZE];
831 gchar now_buf [BUF_SIZE];
835 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
836 modest_text_utils_strftime (now_buf, BUF_SIZE, "%x", now); /* today */
838 /* if this is today, get the time instead of the date */
839 if (strcmp (date_buf, now_buf) == 0)
840 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
842 return g_strdup(date_buf);
846 modest_text_utils_validate_email_address (const gchar *email_address)
849 const gchar *c = NULL, *domain = NULL;
850 static gchar *rfc822_specials = "()<>@,;:\\\"[]";
852 /* first we validate the name portion (name@domain) */
853 for (c = email_address; *c; c++) {
855 (c == email_address ||
861 if (*c == '\\' && (*++c == ' '))
863 if (*c <= ' ' || *c >= 127)
876 if (*c <= ' ' || *c >= 127)
878 if (strchr(rfc822_specials, *c))
881 if (c == email_address || *(c - 1) == '.')
884 /* next we validate the domain portion (name@domain) */
885 if (!*(domain = ++c))
889 if (c == domain || *(c - 1) == '.')
893 if (*c <= ' ' || *c >= 127)
895 if (strchr(rfc822_specials, *c))
899 return (count >= 1) ? TRUE : FALSE;
906 modest_text_utils_get_display_size (guint size)
909 const guint MB=1024 * KB;
910 const guint GB=1024 * MB;
911 const guint TB=1024 * GB;
914 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
916 return g_strdup_printf (_("%d Kb"), size / KB);
918 return g_strdup_printf (_("%d Mb"), size / MB);
920 return g_strdup_printf (_("%d Gb"), size/ GB);
922 return g_strdup_printf (_("Very big"));