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 #endif /*_GNU_SOURCE*/
35 #include <string.h> /* for strcasestr */
40 #include <glib/gi18n.h>
42 #include <modest-tny-platform-factory.h>
43 #include <modest-text-utils.h>
44 #include <modest-runtime.h>
49 #endif /*HAVE_CONFIG_H */
52 #define FORWARD_STRING _("mcen_ia_editor_original_message")
53 #define FROM_STRING _("mail_va_from")
54 #define SENT_STRING _("mcen_fi_message_properties_sent")
55 #define TO_STRING _("mail_va_to")
56 #define SUBJECT_STRING _("mail_va_subject")
57 #define EMPTY_STRING ""
60 * do the hyperlinkification only for texts < 50 Kb,
61 * as it's quite slow. Without this, e.g. mail with
62 * an uuencoded part (which is not recognized as attachment,
65 #define HYPERLINKIFY_MAX_LENGTH (1024*50)
66 #define SIGNATURE_MARKER "--"
70 * we need these regexps to find URLs in plain text e-mails
72 typedef struct _url_match_pattern_t url_match_pattern_t;
73 struct _url_match_pattern_t {
79 typedef struct _url_match_t url_match_t;
88 * we mark the ampersand with \007 when converting text->html
89 * because after text->html we do hyperlink detecting, which
90 * could be screwed up by the ampersand.
91 * ie. 1<3 ==> 1\007lt;3
93 #define MARK_AMP '\007'
94 #define MARK_AMP_STR "\007"
96 /* mark & separately, because they are parts of urls.
97 * ie. a&b => a\006amp;b, but a>b => a\007gt;b
99 * we need to handle '&' separately, because it can be part of URIs
100 * (as in href="http://foo.bar?a=1&b=1"), so inside those URIs
101 * we need to re-replace \006amp; with '&' again, while outside uri's
104 * yes, it's messy, but a consequence of doing text->html first, then hyperlinkify
106 #define MARK_AMP_URI '\006'
107 #define MARK_AMP_URI_STR "\006"
110 /* note: match MARK_AMP_URI_STR as well, because after txt->html, a '&' will look like $(MARK_AMP_URI_STR)"amp;" */
111 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
112 { "(file|rtsp|http|ftp|https|mms|mmsh|rtsp|rdp|lastfm)://[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR \
113 "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]", \
115 { "www\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
117 { "ftp\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
119 { "(jabberto|voipto|sipto|sip|chatto|xmpp):[-_a-z@0-9.+]+", \
121 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
123 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
127 const gchar account_title_forbidden_chars[] = {
128 '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
130 const gchar folder_name_forbidden_chars[] = {
131 '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$', '#', '&'
133 const gchar user_name_forbidden_chars[] = {
136 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
137 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
138 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
141 static gchar* cite (const time_t sent_date, const gchar *from);
142 static void hyperlinkify_plain_text (GString *txt, gint offset);
143 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
144 static GSList* get_url_matches (GString *txt, gint offset);
146 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
147 static int get_indent_level (const char *l);
148 static void unquote_line (GString * l, const gchar *quote_symbol);
149 static void append_quoted (GString * buf, const gchar *quote_symbol,
150 const int indent, const GString * str,
152 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
153 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
154 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
156 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
158 const gchar *signature,
162 static gchar* modest_text_utils_quote_html (const gchar *text,
164 const gchar *signature,
167 static gchar* get_email_from_address (const gchar *address);
170 /* ******************************************************************* */
171 /* ************************* PUBLIC FUNCTIONS ************************ */
172 /* ******************************************************************* */
175 modest_text_utils_quote (const gchar *text,
176 const gchar *content_type,
177 const gchar *signature,
179 const time_t sent_date,
183 gchar *retval, *cited;
185 g_return_val_if_fail (text, NULL);
186 g_return_val_if_fail (content_type, NULL);
188 cited = cite (sent_date, from);
190 if (content_type && strcmp (content_type, "text/html") == 0)
191 /* TODO: extract the <body> of the HTML and pass it to
193 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
195 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
204 modest_text_utils_cite (const gchar *text,
205 const gchar *content_type,
206 const gchar *signature,
213 g_return_val_if_fail (text, NULL);
214 g_return_val_if_fail (content_type, NULL);
217 retval = g_strdup ("");
218 else if (strcmp(content_type, "text/html") == 0) {
219 tmp_sig = g_strconcat ("\n", SIGNATURE_MARKER,"\n", signature, NULL);
220 retval = modest_text_utils_convert_to_html_body(tmp_sig, -1, TRUE);
223 retval = g_strconcat (text, "\n", SIGNATURE_MARKER, "\n", signature, NULL);
230 forward_cite (const gchar *from,
233 const gchar *subject)
235 g_return_val_if_fail (sent, NULL);
237 return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n",
239 FROM_STRING, (from)?from:"",
241 TO_STRING, (to)?to:"",
242 SUBJECT_STRING, (subject)?subject:"");
246 modest_text_utils_inline (const gchar *text,
247 const gchar *content_type,
248 const gchar *signature,
252 const gchar *subject)
258 g_return_val_if_fail (text, NULL);
259 g_return_val_if_fail (content_type, NULL);
261 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
263 cited = forward_cite (from, sent_str, to, subject);
265 if (content_type && strcmp (content_type, "text/html") == 0)
266 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
268 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
274 /* just to prevent warnings:
275 * warning: `%x' yields only last 2 digits of year in some locales
278 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
282 /* To prevent possible problems in strftime that could leave
283 garbage in the s variable */
287 /* does not work on old maemo glib:
288 * g_date_set_time_t (&date, timet);
290 localtime_r (&timet, &tm);
291 return strftime(s, max, fmt, &tm);
295 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
297 gchar *tmp, *subject_dup, *retval;
300 g_return_val_if_fail (prefix, NULL);
302 if (!subject || subject[0] == '\0')
303 subject = _("mail_va_no_subject");
305 subject_dup = g_strdup (subject);
306 tmp = g_strchug (subject_dup);
308 /* We do not want things like "Re: Re: Re:" or "Fw: Fw:" so
309 delete the previous ones */
310 prefix_len = strlen (prefix);
312 if (g_str_has_prefix (tmp, prefix)) {
314 tmp = g_strchug (tmp);
320 retval = g_strdup_printf ("%s %s", prefix, tmp);
321 g_free (subject_dup);
327 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
329 gchar *dup, *token, *ptr = NULL, *result;
330 GString *filtered_emails;
331 gchar *email_address;
333 g_return_val_if_fail (address_list, NULL);
336 return g_strdup (address_list);
338 email_address = get_email_from_address (address);
340 /* search for substring */
341 if (!strstr ((const char *) address_list, (const char *) email_address)) {
342 g_free (email_address);
343 return g_strdup (address_list);
346 dup = g_strdup (address_list);
347 filtered_emails = g_string_new (NULL);
349 token = strtok_r (dup, ",", &ptr);
351 while (token != NULL) {
352 /* Add to list if not found */
353 if (!strstr ((const char *) token, (const char *) email_address)) {
354 if (filtered_emails->len == 0)
355 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
357 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
359 token = strtok_r (NULL, ",", &ptr);
361 result = filtered_emails->str;
364 g_free (email_address);
366 g_string_free (filtered_emails, FALSE);
373 modest_text_utils_remove_duplicate_addresses (const gchar *address_list)
375 GSList *addresses, *cursor;
377 gchar *new_list = NULL;
379 g_return_val_if_fail (address_list, NULL);
381 table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
382 addresses = modest_text_utils_split_addresses_list (address_list);
386 const gchar* address = (const gchar*)cursor->data;
388 /* We need only the email to just compare it and not
389 the full address which would make "a <a@a.com>"
390 different from "a@a.com" */
391 const gchar *email = get_email_from_address (address);
393 /* ignore the address if already seen */
394 if (g_hash_table_lookup (table, email) == 0) {
397 /* Include the full address and not only the
398 email in the returned list */
400 tmp = g_strdup (address);
402 tmp = g_strjoin (",", new_list, address, NULL);
407 g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
409 cursor = g_slist_next (cursor);
412 g_hash_table_unref (table);
413 g_slist_foreach (addresses, (GFunc)g_free, NULL);
414 g_slist_free (addresses);
421 modest_text_utils_convert_buffer_to_html_start (GString *html, const gchar *data, gssize n)
424 gboolean space_seen = FALSE;
425 guint break_dist = 0; /* distance since last break point */
430 /* replace with special html chars where needed*/
431 for (i = 0; i != n; ++i) {
432 guchar kar = data[i];
434 if (space_seen && kar != ' ') {
435 g_string_append_c (html, ' ');
439 /* we artificially insert a breakpoint (newline)
440 * after 256, to make sure our lines are not so long
441 * they will DOS the regexping later
442 * Also, check that kar is ASCII to make sure that we
443 * don't break a UTF8 char in two
445 if (++break_dist >= 256 && kar < 127) {
446 g_string_append_c (html, '\n');
454 /* this is a temp place holder for '&'; we can only
455 * set the real '&' after hyperlink translation, otherwise
456 * we might screw that up */
457 break; /* ignore embedded \0s and MARK_AMP */
458 case '<' : g_string_append (html, MARK_AMP_STR "lt;"); break;
459 case '>' : g_string_append (html, MARK_AMP_STR "gt;"); break;
460 case '&' : g_string_append (html, MARK_AMP_URI_STR "amp;"); break; /* special case */
461 case '"' : g_string_append (html, MARK_AMP_STR "quot;"); break;
463 /* don't convert ' --> wpeditor will try to re-convert it... */
464 //case '\'' : g_string_append (html, "'"); break;
465 case '\n' : g_string_append (html, "<br>\n");break_dist= 0; break;
466 case '\t' : g_string_append (html, MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp; ");
467 break_dist=0; break; /* note the space at the end*/
470 if (space_seen) { /* second space in a row */
471 g_string_append (html, " ");
477 g_string_append_c (html, kar);
484 modest_text_utils_convert_buffer_to_html_finish (GString *html)
487 /* replace all our MARK_AMPs with real ones */
488 for (i = 0; i != html->len; ++i)
489 if ((html->str)[i] == MARK_AMP || (html->str)[i] == MARK_AMP_URI)
490 (html->str)[i] = '&';
495 modest_text_utils_convert_to_html (const gchar *data)
500 g_return_val_if_fail (data, NULL);
506 html = g_string_sized_new (1.5 * len); /* just a guess... */
508 g_string_append_printf (html,
510 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
514 modest_text_utils_convert_buffer_to_html_start (html, data, -1);
516 g_string_append (html, "</body></html>");
518 if (len <= HYPERLINKIFY_MAX_LENGTH)
519 hyperlinkify_plain_text (html, 0);
521 modest_text_utils_convert_buffer_to_html_finish (html);
523 return g_string_free (html, FALSE);
527 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
531 g_return_val_if_fail (data, NULL);
538 html = g_string_sized_new (1.5 * n); /* just a guess... */
540 modest_text_utils_convert_buffer_to_html_start (html, data, n);
542 if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
543 hyperlinkify_plain_text (html, 0);
545 modest_text_utils_convert_buffer_to_html_finish (html);
547 return g_string_free (html, FALSE);
551 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
553 gchar *current, *start, *last_blank;
554 gint start_offset = 0, current_offset = 0;
556 g_return_if_fail (start_indexes != NULL);
557 g_return_if_fail (end_indexes != NULL);
559 start = (gchar *) addresses;
563 while (*current != '\0') {
564 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
565 start = g_utf8_next_char (start);
567 last_blank = current;
568 } else if ((*current == ',')||(*current == ';')) {
569 gint *start_index, *end_index;
570 start_index = g_new0(gint, 1);
571 end_index = g_new0(gint, 1);
572 *start_index = start_offset;
573 *end_index = current_offset;
574 *start_indexes = g_slist_prepend (*start_indexes, start_index);
575 *end_indexes = g_slist_prepend (*end_indexes, end_index);
576 start = g_utf8_next_char (current);
577 start_offset = current_offset + 1;
579 } else if (*current == '"') {
580 current = g_utf8_next_char (current);
582 while ((*current != '"')&&(*current != '\0')) {
583 current = g_utf8_next_char (current);
588 current = g_utf8_next_char (current);
592 if (start != current) {
593 gint *start_index, *end_index;
594 start_index = g_new0(gint, 1);
595 end_index = g_new0(gint, 1);
596 *start_index = start_offset;
597 *end_index = current_offset;
598 *start_indexes = g_slist_prepend (*start_indexes, start_index);
599 *end_indexes = g_slist_prepend (*end_indexes, end_index);
602 *start_indexes = g_slist_reverse (*start_indexes);
603 *end_indexes = g_slist_reverse (*end_indexes);
610 modest_text_utils_split_addresses_list (const gchar *addresses)
613 const gchar *my_addrs = addresses;
616 gboolean after_at = FALSE;
618 g_return_val_if_fail (addresses, NULL);
620 /* skip any space, ',', ';' at the start */
621 while (my_addrs && (my_addrs[0] == ' ' || my_addrs[0] == ',' || my_addrs[0] == ';'))
624 /* are we at the end of addresses list? */
628 /* nope, we are at the start of some address
629 * now, let's find the end of the address */
631 while (end[0] && end[0] != ';' && !(after_at && end[0] == ',')) {
632 if (end[0] == '\"') {
633 while (end[0] && end[0] != '\"')
639 if ((end[0] && end[0] == '>')&&(end[1] && end[1] == ',')) {
646 /* we got the address; copy it and remove trailing whitespace */
647 addr = g_strndup (my_addrs, end - my_addrs);
650 head = g_slist_append (NULL, addr);
651 head->next = modest_text_utils_split_addresses_list (end); /* recurse */
658 modest_text_utils_address_range_at_position (const gchar *recipients_list,
663 gchar *current = NULL;
664 gint range_start = 0;
667 gboolean is_quoted = FALSE;
669 g_return_if_fail (recipients_list);
670 g_return_if_fail (position < g_utf8_strlen(recipients_list, -1));
673 for (current = (gchar *) recipients_list; *current != '\0';
674 current = g_utf8_find_next_char (current, NULL)) {
675 gunichar c = g_utf8_get_char (current);
677 if ((c == ',') && (!is_quoted)) {
678 if (index < position) {
679 range_start = index + 1;
683 } else if (c == '\"') {
684 is_quoted = !is_quoted;
685 } else if ((c == ' ') &&(range_start == index)) {
693 *start = range_start;
699 modest_text_utils_address_with_standard_length (const gchar *recipients_list)
703 GString *buffer = g_string_new ("");
705 splitted = g_strsplit (recipients_list, "\n", 0);
709 if (current != splitted)
710 buffer = g_string_append_c (buffer, '\n');
711 line = g_strndup (*splitted, 1000);
712 buffer = g_string_append (buffer, line);
717 g_strfreev (splitted);
719 return g_string_free (buffer, FALSE);
723 /* ******************************************************************* */
724 /* ************************* UTILIY FUNCTIONS ************************ */
725 /* ******************************************************************* */
728 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
734 return g_string_new("");
742 gs = g_string_new_len (i0, iter - i0);
746 get_indent_level (const char *l)
763 /* if we hit the signature marker "-- ", we return -(indent + 1). This
764 * stops reformatting.
766 if (strcmp (l, "-- ") == 0) {
774 unquote_line (GString * l, const gchar *quote_symbol)
780 quote_len = strlen (quote_symbol);
782 if (g_str_has_prefix (p, quote_symbol)) {
783 if (p[quote_len] == ' ') {
791 g_string_erase (l, 0, p - l->str);
795 append_quoted (GString * buf, const gchar *quote_symbol,
796 int indent, const GString * str,
802 indent = indent < 0 ? abs (indent) - 1 : indent;
803 quote_concat = g_strconcat (quote_symbol, " ", NULL);
804 for (i = 0; i <= indent; i++) {
805 g_string_append (buf, quote_concat);
807 g_free (quote_concat);
809 g_string_append_len (buf, str->str, cutpoint);
811 g_string_append (buf, str->str);
813 g_string_append (buf, "\n");
817 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
820 const gchar *pos, *last;
823 indent = indent < 0 ? abs (indent) - 1 : indent;
827 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
829 if ((index + 2 * indent > limit) && last) {
833 if (g_unichar_isspace (uni[index])) {
836 pos = g_utf8_next_char (pos);
844 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
849 if (last + 2 * indent < limit)
852 for (i = strlen (s); i > 0; i--) {
854 if (i + 2 * indent <= limit) {
865 get_breakpoint (const gchar * s, const gint indent, const gint limit)
868 if (g_utf8_validate (s, -1, NULL)) {
869 return get_breakpoint_utf8 (s, indent, limit);
870 } else { /* assume ASCII */
871 //g_warning("invalid UTF-8 in msg");
872 return get_breakpoint_ascii (s, indent, limit);
877 cite (const time_t sent_date, const gchar *from)
879 return g_strdup (_("mcen_ia_editor_original_message"));
883 quoted_attachments (GList *attachments)
886 GString *result = g_string_new ("");
887 for (node = attachments; node != NULL; node = g_list_next (node)) {
888 gchar *filename = (gchar *) node->data;
889 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
892 return g_string_free (result, FALSE);
897 modest_text_utils_quote_body (GString *output, const gchar *text,
898 const gchar *quote_symbol,
904 gint indent, breakpoint, rem_indent = 0;
905 GString *l, *remaining;
909 remaining = g_string_new ("");
911 l = get_next_line (text, len, iter);
912 iter = iter + l->len + 1;
913 indent = get_indent_level (l->str);
914 unquote_line (l, quote_symbol);
916 if (remaining->len) {
917 if (l->len && indent == rem_indent) {
918 g_string_prepend (l, " ");
919 g_string_prepend (l, remaining->str);
923 get_breakpoint (remaining->str,
926 append_quoted (output, quote_symbol, rem_indent,
927 remaining, breakpoint);
928 g_string_erase (remaining, 0,
930 if (remaining->str[0] == ' ') {
931 g_string_erase (remaining, 0,
934 } while (remaining->len);
937 g_string_free (remaining, TRUE);
938 breakpoint = get_breakpoint (l->str, indent, limit);
939 remaining = g_string_new (l->str + breakpoint);
940 if (remaining->str[0] == ' ') {
941 g_string_erase (remaining, 0, 1);
944 append_quoted (output, quote_symbol, indent, l, breakpoint);
945 g_string_free (l, TRUE);
946 } while ((iter < text + len) || (remaining->str[0]));
952 modest_text_utils_quote_plain_text (const gchar *text,
954 const gchar *signature,
959 gchar *attachments_string = NULL;
961 q = g_string_new ("");
963 if (signature != NULL) {
964 q = g_string_append (q, "\n--\n");
965 q = g_string_append (q, signature);
968 q = g_string_append (q, "\n");
969 q = g_string_append (q, cite);
970 q = g_string_append_c (q, '\n');
972 q = modest_text_utils_quote_body (q, text, ">", limit);
974 attachments_string = quoted_attachments (attachments);
975 q = g_string_append (q, attachments_string);
976 g_free (attachments_string);
978 return g_string_free (q, FALSE);
982 quote_html_add_to_gstring (GString *string,
985 if (text && strcmp (text, "")) {
986 gchar *html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
987 g_string_append_printf (string, "%s<br/>", html_text);
993 modest_text_utils_quote_html (const gchar *text,
995 const gchar *signature,
999 GString *result_string;
1003 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
1007 if (text || cite || signature) {
1008 GString *quoted_text;
1009 g_string_append (result_string, "<pre>\n");
1011 quote_html_add_to_gstring (result_string, SIGNATURE_MARKER);
1012 quote_html_add_to_gstring (result_string, signature);
1014 quote_html_add_to_gstring (result_string, cite);
1015 quoted_text = g_string_new ("");
1016 quoted_text = modest_text_utils_quote_body (quoted_text, text, ">", limit);
1017 quote_html_add_to_gstring (result_string, quoted_text->str);
1018 g_string_free (quoted_text, TRUE);
1020 gchar *attachments_string = quoted_attachments (attachments);
1021 quote_html_add_to_gstring (result_string, attachments_string);
1022 g_free (attachments_string);
1024 g_string_append (result_string, "</pre>");
1026 g_string_append (result_string, "</body>");
1027 g_string_append (result_string, "</html>");
1029 return g_string_free (result_string, FALSE);
1033 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
1035 return match2->offset - match1->offset;
1038 static gint url_matches_block = 0;
1039 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
1046 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1047 for (i = 0; i != pattern_num; ++i) {
1048 patterns[i].preg = g_slice_new0 (regex_t);
1050 /* this should not happen */
1051 if (regcomp (patterns[i].preg, patterns[i].regex,
1052 REG_ICASE|REG_EXTENDED|REG_NEWLINE) != 0) {
1053 g_warning ("%s: error in regexp:\n%s\n", __FUNCTION__, patterns[i].regex);
1064 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1065 for (i = 0; i != pattern_num; ++i) {
1066 regfree (patterns[i].preg);
1067 g_slice_free (regex_t, patterns[i].preg);
1068 } /* don't free patterns itself -- it's static */
1072 modest_text_utils_hyperlinkify_begin (void)
1074 if (url_matches_block == 0)
1075 compile_patterns ();
1076 url_matches_block ++;
1080 modest_text_utils_hyperlinkify_end (void)
1082 url_matches_block--;
1083 if (url_matches_block <= 0)
1089 get_url_matches (GString *txt, gint offset)
1092 guint rv, i, tmp_offset = 0;
1093 GSList *match_list = NULL;
1095 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1097 /* initalize the regexps */
1098 modest_text_utils_hyperlinkify_begin ();
1100 /* find all the matches */
1101 for (i = 0; i != pattern_num; ++i) {
1102 tmp_offset = offset;
1105 gboolean is_submatch;
1108 if ((rv = regexec (patterns[i].preg, txt->str + tmp_offset, 1, &rm, 0)) != 0) {
1109 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
1110 break; /* try next regexp */
1115 is_submatch = FALSE;
1116 /* check old matches to see if this has already been matched */
1117 cursor = match_list;
1118 while (cursor && !is_submatch) {
1119 const url_match_t *old_match =
1120 (const url_match_t *) cursor->data;
1121 guint new_offset = tmp_offset + rm.rm_so;
1122 is_submatch = (new_offset > old_match->offset &&
1123 new_offset < old_match->offset + old_match->len);
1124 cursor = g_slist_next (cursor);
1128 /* make a list of our matches (<offset, len, prefix> tupels)*/
1129 match = g_slice_new (url_match_t);
1130 match->offset = tmp_offset + rm.rm_so;
1131 match->len = rm.rm_eo - rm.rm_so;
1132 match->prefix = patterns[i].prefix;
1133 match_list = g_slist_prepend (match_list, match);
1135 tmp_offset += rm.rm_eo;
1139 modest_text_utils_hyperlinkify_end ();
1141 /* now sort the list, so the matches are in reverse order of occurence.
1142 * that way, we can do the replacements starting from the end, so we don't need
1143 * to recalculate the offsets
1145 match_list = g_slist_sort (match_list,
1146 (GCompareFunc)cmp_offsets_reverse);
1152 /* replace all occurences of needle in haystack with repl*/
1154 replace_string (const gchar *haystack, const gchar *needle, gchar repl)
1156 gchar *str, *cursor;
1158 if (!haystack || !needle || strlen(needle) == 0)
1159 return haystack ? g_strdup(haystack) : NULL;
1161 str = g_strdup (haystack);
1163 for (cursor = str; cursor && *cursor; ++cursor) {
1164 if (g_str_has_prefix (cursor, needle)) {
1166 memmove (cursor + 1,
1167 cursor + strlen (needle),
1168 strlen (cursor + strlen (needle)) + 1);
1176 hyperlinkify_plain_text (GString *txt, gint offset)
1179 GSList *match_list = get_url_matches (txt, offset);
1181 /* we will work backwards, so the offsets stay valid */
1182 for (cursor = match_list; cursor; cursor = cursor->next) {
1184 url_match_t *match = (url_match_t*) cursor->data;
1185 gchar *url = g_strndup (txt->str + match->offset, match->len);
1186 gchar *repl = NULL; /* replacement */
1188 /* the string still contains $(MARK_AMP_URI_STR)"amp;" for each
1189 * '&' in the original, because of the text->html conversion.
1190 * in the href-URL (and only there), we must convert that back to
1193 gchar *href_url = replace_string (url, MARK_AMP_URI_STR "amp;", '&');
1195 /* the prefix is NULL: use the one that is already there */
1196 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1197 match->prefix ? match->prefix : EMPTY_STRING,
1200 /* replace the old thing with our hyperlink
1201 * replacement thing */
1202 g_string_erase (txt, match->offset, match->len);
1203 g_string_insert (txt, match->offset, repl);
1209 g_slice_free (url_match_t, match);
1212 g_slist_free (match_list);
1216 modest_text_utils_hyperlinkify (GString *string_buffer)
1221 after_body = strstr (string_buffer->str, "<body>");
1222 if (after_body != NULL)
1223 offset = after_body - string_buffer->str;
1224 hyperlinkify_plain_text (string_buffer, offset);
1228 /* for optimization reasons, we change the string in-place */
1230 modest_text_utils_get_display_address (gchar *address)
1234 g_return_if_fail (address);
1239 /* should not be needed, and otherwise, we probably won't screw up the address
1240 * more than it already is :)
1241 * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1244 /* remove leading whitespace */
1245 if (address[0] == ' ')
1246 g_strchug (address);
1248 for (i = 0; address[i]; ++i) {
1249 if (address[i] == '<') {
1250 if (G_UNLIKELY(i == 0))
1251 return; /* there's nothing else, leave it */
1253 address[i] = '\0'; /* terminate the string here */
1265 modest_text_utils_get_email_address (const gchar *full_address)
1267 const gchar *left, *right;
1269 g_return_val_if_fail (full_address, NULL);
1274 g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1276 left = g_strrstr_len (full_address, strlen(full_address), "<");
1278 return g_strdup (full_address);
1280 right = g_strstr_len (left, strlen(left), ">");
1282 return g_strdup (full_address);
1284 return g_strndup (left + 1, right - left - 1);
1288 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1290 gint prefix_len = 0;
1292 g_return_val_if_fail (sub, 0);
1297 /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1298 if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1300 else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1307 /* skip over a [...] block */
1308 if (sub[prefix_len] == '[') {
1309 int c = prefix_len + 1;
1310 while (sub[c] && sub[c] != ']')
1313 return 0; /* no end to the ']' found */
1318 /* did we find the ':' ? */
1319 if (sub[prefix_len] == ':') {
1321 if (sub[prefix_len] == ' ')
1323 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1324 /* g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1332 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1335 /* work even when s1 and/or s2 == NULL */
1336 if (G_UNLIKELY(s1 == s2))
1338 if (G_UNLIKELY(!s1))
1340 if (G_UNLIKELY(!s2))
1343 /* if it's not case sensitive */
1346 /* optimization: shortcut if first char is ascii */
1347 if (((s1[0] & 0x80)== 0) && ((s2[0] & 0x80) == 0) &&
1349 return s1[0] - s2[0];
1351 return g_utf8_collate (s1, s2);
1357 /* optimization: shortcut if first char is ascii */
1358 if (((s1[0] & 0x80) == 0) && ((s2[0] & 0x80) == 0) &&
1359 (tolower(s1[0]) != tolower (s2[0])))
1360 return tolower(s1[0]) - tolower(s2[0]);
1362 n1 = g_utf8_strdown (s1, -1);
1363 n2 = g_utf8_strdown (s2, -1);
1365 result = g_utf8_collate (n1, n2);
1376 modest_text_utils_get_display_date (time_t date)
1378 #define DATE_BUF_SIZE 64
1379 static gchar date_buf[DATE_BUF_SIZE];
1381 /* calculate the # of days since epoch for
1382 * for today and for the date provided
1383 * based on idea from pvanhoof */
1384 int day = time(NULL) / (24 * 60 * 60);
1385 int date_day = date / (24 * 60 * 60);
1387 /* if it's today, show the time, if it's not today, show the date instead */
1389 /* TODO: take into account the system config for 24/12h */
1390 if (day == date_day) /* is the date today? */
1391 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_24h_time"), date);
1393 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_date"), date);
1395 return date_buf; /* this is a static buffer, don't free! */
1401 modest_text_utils_validate_folder_name (const gchar *folder_name)
1403 /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1404 * with some extras */
1408 const gchar **cursor = NULL;
1409 const gchar *forbidden_names[] = { /* windows does not like these */
1410 "CON", "PRN", "AUX", "NUL", ".", "..", "cur", "tmp", "new",
1411 NULL /* cur, tmp, new are reserved for Maildir */
1414 /* cannot be NULL */
1418 /* cannot be empty */
1419 len = strlen(folder_name);
1423 /* cannot start with a dot, vfat does not seem to like that */
1424 if (folder_name[0] == '.')
1427 /* cannot start or end with a space */
1428 if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1431 /* cannot contain a forbidden char */
1432 for (i = 0; i < len; i++)
1433 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1436 /* Cannot contain Windows port numbers. I'd like to use GRegex
1437 but it's still not available in Maemo. sergio */
1438 if (!g_ascii_strncasecmp (folder_name, "LPT", 3) ||
1439 !g_ascii_strncasecmp (folder_name, "COM", 3)) {
1443 /* We skip the first 3 characters for the
1445 val = strtol(folder_name+3, &endptr, 10);
1447 /* If the conversion to long succeeded then the string
1448 is not valid for us */
1449 if (*endptr == '\0')
1455 /* cannot contain a forbidden word */
1457 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1458 if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1463 return TRUE; /* it's valid! */
1469 modest_text_utils_validate_domain_name (const gchar *domain)
1471 gboolean valid = FALSE;
1473 const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1475 g_return_val_if_fail (domain, FALSE);
1480 memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1482 /* domain name: all alphanum or '-' or '.',
1483 * but beginning/ending in alphanum */
1484 if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1485 g_warning ("BUG: error in regexp");
1489 valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1498 modest_text_utils_validate_email_address (const gchar *email_address,
1499 const gchar **invalid_char_position)
1502 const gchar *c = NULL, *domain = NULL;
1503 static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1505 if (invalid_char_position)
1506 *invalid_char_position = NULL;
1508 g_return_val_if_fail (email_address, FALSE);
1510 /* check that the email adress contains exactly one @ */
1511 if (!strstr(email_address, "@") ||
1512 (strstr(email_address, "@") != g_strrstr(email_address, "@")))
1515 /* first we validate the name portion (name@domain) */
1516 for (c = email_address; *c; c++) {
1518 (c == email_address ||
1520 *(c - 1) == '\"')) {
1524 if (*c == '\\' && (*++c == ' '))
1526 if (*c <= ' ' || *c >= 127)
1539 if (*c <= ' ' || *c >= 127)
1541 if (strchr(rfc822_specials, *c)) {
1542 if (invalid_char_position)
1543 *invalid_char_position = c;
1547 if (c == email_address || *(c - 1) == '.')
1550 /* next we validate the domain portion (name@domain) */
1551 if (!*(domain = ++c))
1555 if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0')
1559 if (*c <= ' ' || *c >= 127)
1561 if (strchr(rfc822_specials, *c)) {
1562 if (invalid_char_position)
1563 *invalid_char_position = c;
1568 return (count >= 1) ? TRUE : FALSE;
1572 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1574 gchar *stripped, *current;
1576 gboolean has_error = FALSE;
1578 if (invalid_char_position)
1579 *invalid_char_position = NULL;
1581 g_return_val_if_fail (recipient, FALSE);
1583 if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1586 stripped = g_strdup (recipient);
1587 stripped = g_strstrip (stripped);
1590 if (*current == '\0') {
1596 if (*current == '\"') {
1597 current = g_utf8_next_char (current);
1599 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1600 if (*current == '\\') {
1601 /* TODO: This causes a warning, which breaks the build,
1602 * because a gchar cannot be < 0.
1604 if (current[1] <0) {
1609 } else if (*current == '\"') {
1611 current = g_utf8_next_char (current);
1617 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1618 if (*current == '<') {
1630 right_part = g_strdup (current);
1632 right_part = g_strstrip (right_part);
1634 if (g_str_has_prefix (right_part, "<") &&
1635 g_str_has_suffix (right_part, ">")) {
1639 address = g_strndup (right_part+1, strlen (right_part) - 2);
1640 g_free (right_part);
1641 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1645 g_free (right_part);
1652 modest_text_utils_get_display_size (guint64 size)
1654 const guint KB=1024;
1655 const guint MB=1024 * KB;
1656 const guint GB=1024 * MB;
1659 return g_strdup_printf (_FM("sfil_li_size_kb"));
1660 if (0 <= size && size < KB)
1661 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), 1);
1662 else if (KB <= size && size < 100 * KB)
1663 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1664 else if (100*KB <= size && size < MB)
1665 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1666 else if (MB <= size && size < 10*MB)
1667 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1668 else if (10*MB <= size && size < GB)
1669 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1671 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB);
1675 get_email_from_address (const gchar * address)
1677 gchar *left_limit, *right_limit;
1679 left_limit = strstr (address, "<");
1680 right_limit = g_strrstr (address, ">");
1682 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1683 return g_strdup (address);
1685 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1689 modest_text_utils_get_color_string (GdkColor *color)
1691 g_return_val_if_fail (color, NULL);
1693 return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1694 (color->red >> 12) & 0xf, (color->red >> 8) & 0xf,
1695 (color->red >> 4) & 0xf, (color->red) & 0xf,
1696 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1697 (color->green >> 4) & 0xf, (color->green) & 0xf,
1698 (color->blue >> 12) & 0xf, (color->blue >> 8) & 0xf,
1699 (color->blue >> 4) & 0xf, (color->blue) & 0xf);
1703 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1705 GtkTextIter start, end;
1706 gchar *slice, *current;
1707 GString *result = g_string_new ("");
1709 g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1711 gtk_text_buffer_get_start_iter (buffer, &start);
1712 gtk_text_buffer_get_end_iter (buffer, &end);
1714 slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1717 while (current && current != '\0') {
1718 if (g_utf8_get_char (current) == 0xFFFC) {
1719 result = g_string_append_c (result, ' ');
1720 current = g_utf8_next_char (current);
1722 gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1724 result = g_string_append (result, current);
1726 result = g_string_append_len (result, current, next - current);
1733 return g_string_free (result, FALSE);
1738 modest_text_utils_is_forbidden_char (const gchar character,
1739 ModestTextUtilsForbiddenCharType type)
1742 const gchar *forbidden_chars = NULL;
1744 /* We need to get the length in the switch because the
1745 compiler needs to know the size at compile time */
1747 case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1748 forbidden_chars = account_title_forbidden_chars;
1749 len = G_N_ELEMENTS (account_title_forbidden_chars);
1751 case FOLDER_NAME_FORBIDDEN_CHARS:
1752 forbidden_chars = folder_name_forbidden_chars;
1753 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1755 case USER_NAME_FORBIDDEN_NAMES:
1756 forbidden_chars = user_name_forbidden_chars;
1757 len = G_N_ELEMENTS (user_name_forbidden_chars);
1760 g_return_val_if_reached (TRUE);
1763 for (i = 0; i < len ; i++)
1764 if (forbidden_chars[i] == character)
1767 return FALSE; /* it's valid! */
1771 modest_text_utils_label_get_selection (GtkLabel *label)
1776 if (gtk_label_get_selection_bounds (GTK_LABEL (label), &start, &end)) {
1777 const gchar *start_offset;
1778 const gchar *end_offset;
1779 start_offset = gtk_label_get_text (GTK_LABEL (label));
1780 start_offset = g_utf8_offset_to_pointer (start_offset, start);
1781 end_offset = gtk_label_get_text (GTK_LABEL (label));
1782 end_offset = g_utf8_offset_to_pointer (end_offset, end);
1783 selection = g_strndup (start_offset, end_offset - start_offset);
1786 return g_strdup ("");
1791 _forward_search_image_char (gunichar ch,
1794 return (ch == 0xFFFC);
1798 modest_text_utils_buffer_selection_is_valid (GtkTextBuffer *buffer)
1801 GtkTextIter start, end;
1803 g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
1805 result = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (buffer));
1807 /* check there are no images in selection */
1809 gtk_text_buffer_get_selection_bounds (buffer, &start, &end);
1810 if (gtk_text_iter_get_char (&start)== 0xFFFC)
1813 gtk_text_iter_backward_char (&end);
1814 if (gtk_text_iter_forward_find_char (&start, _forward_search_image_char,
1825 modest_text_utils_escape_mnemonics (const gchar *text)
1828 GString *result = NULL;
1833 result = g_string_new ("");
1834 for (p = text; *p != '\0'; p++) {
1836 result = g_string_append (result, "__");
1838 result = g_string_append_c (result, *p);
1841 return g_string_free (result, FALSE);