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-account-mgr-helpers.h>
45 #include <modest-runtime.h>
50 #endif /*HAVE_CONFIG_H */
53 #define FORWARD_STRING _("mcen_ia_editor_original_message")
54 #define FROM_STRING _("mail_va_from")
55 #define SENT_STRING _("mcen_fi_message_properties_sent")
56 #define TO_STRING _("mail_va_to")
57 #define SUBJECT_STRING _("mail_va_subject")
58 #define EMPTY_STRING ""
61 * do the hyperlinkification only for texts < 50 Kb,
62 * as it's quite slow. Without this, e.g. mail with
63 * an uuencoded part (which is not recognized as attachment,
66 #define HYPERLINKIFY_MAX_LENGTH (1024*50)
69 * we need these regexps to find URLs in plain text e-mails
71 typedef struct _url_match_pattern_t url_match_pattern_t;
72 struct _url_match_pattern_t {
78 typedef struct _url_match_t url_match_t;
87 * we mark the ampersand with \007 when converting text->html
88 * because after text->html we do hyperlink detecting, which
89 * could be screwed up by the ampersand.
90 * ie. 1<3 ==> 1\007lt;3
92 #define MARK_AMP '\007'
93 #define MARK_AMP_STR "\007"
95 /* mark & separately, because they are parts of urls.
96 * ie. a&b => a\006amp;b, but a>b => a\007gt;b
98 * we need to handle '&' separately, because it can be part of URIs
99 * (as in href="http://foo.bar?a=1&b=1"), so inside those URIs
100 * we need to re-replace \006amp; with '&' again, while outside uri's
103 * yes, it's messy, but a consequence of doing text->html first, then hyperlinkify
105 #define MARK_AMP_URI '\006'
106 #define MARK_AMP_URI_STR "\006"
109 /* note: match MARK_AMP_URI_STR as well, because after txt->html, a '&' will look like $(MARK_AMP_URI_STR)"amp;" */
110 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
111 { "(feed:|)(file|rtsp|http|ftp|https|mms|mmsh|webcal|feed|rtsp|rdp|lastfm|sip)://[-a-z0-9_$.+!*(),;:@%=\?/~#&" MARK_AMP_URI_STR \
112 "]+[-a-z0-9_$%&" MARK_AMP_URI_STR "=?/~#]", \
114 { "www\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
116 { "ftp\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
118 { "(jabberto|voipto|sipto|sip|chatto|skype|xmpp):[-_a-z@0-9.+]+", \
120 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
122 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
126 const gchar account_title_forbidden_chars[] = {
127 '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
129 const gchar folder_name_forbidden_chars[] = {
130 '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$', '#', '&'
132 const gchar user_name_forbidden_chars[] = {
135 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
136 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
137 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
140 static gchar* cite (const time_t sent_date, const gchar *from);
141 static void hyperlinkify_plain_text (GString *txt, gint offset);
142 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
143 static GSList* get_url_matches (GString *txt, gint offset);
145 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
146 static int get_indent_level (const char *l);
147 static void unquote_line (GString * l, const gchar *quote_symbol);
148 static void append_quoted (GString * buf, const gchar *quote_symbol,
149 const int indent, const GString * str,
151 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
152 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
153 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
155 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
157 const gchar *signature,
161 static gchar* modest_text_utils_quote_html (const gchar *text,
163 const gchar *signature,
166 static gchar* get_email_from_address (const gchar *address);
167 static void remove_extra_spaces (gchar *string);
171 /* ******************************************************************* */
172 /* ************************* PUBLIC FUNCTIONS ************************ */
173 /* ******************************************************************* */
176 modest_text_utils_quote (const gchar *text,
177 const gchar *content_type,
178 const gchar *signature,
180 const time_t sent_date,
184 gchar *retval, *cited;
186 g_return_val_if_fail (text, NULL);
187 g_return_val_if_fail (content_type, NULL);
189 cited = cite (sent_date, from);
191 if (content_type && strcmp (content_type, "text/html") == 0)
192 /* TODO: extract the <body> of the HTML and pass it to
194 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
196 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
205 modest_text_utils_cite (const gchar *text,
206 const gchar *content_type,
207 const gchar *signature,
213 g_return_val_if_fail (text, NULL);
214 g_return_val_if_fail (content_type, NULL);
216 if (strcmp (content_type, "text/html") == 0) {
217 tmp = modest_text_utils_convert_to_html_body (text, -1, TRUE);
219 gchar *colored_signature = modest_text_utils_create_colored_signature (signature);
220 retval = g_strconcat (tmp, colored_signature, NULL);
221 g_free (colored_signature);
228 retval = g_strconcat (text, "\n", MODEST_TEXT_UTILS_SIGNATURE_MARKER, "\n", signature, NULL);
230 retval = g_strdup (text);
237 forward_cite (const gchar *from,
240 const gchar *subject)
242 g_return_val_if_fail (sent, NULL);
244 return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n",
246 FROM_STRING, (from)?from:"",
248 TO_STRING, (to)?to:"",
249 SUBJECT_STRING, (subject)?subject:"");
253 modest_text_utils_inline (const gchar *text,
254 const gchar *content_type,
255 const gchar *signature,
259 const gchar *subject)
265 g_return_val_if_fail (text, NULL);
266 g_return_val_if_fail (content_type, NULL);
268 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
270 cited = forward_cite (from, sent_str, to, subject);
272 if (content_type && strcmp (content_type, "text/html") == 0)
273 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
275 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
281 /* just to prevent warnings:
282 * warning: `%x' yields only last 2 digits of year in some locales
285 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
289 /* To prevent possible problems in strftime that could leave
290 garbage in the s variable */
296 /* does not work on old maemo glib:
297 * g_date_set_time_t (&date, timet);
299 localtime_r (&timet, &tm);
300 return strftime(s, max, fmt, &tm);
304 modest_text_utils_derived_subject (const gchar *subject, gboolean is_reply)
306 gchar *tmp, *subject_dup, *retval, *prefix;
307 const gchar *untranslated_prefix;
308 gint prefix_len, untranslated_prefix_len;
309 gboolean found = FALSE;
311 if (!subject || subject[0] == '\0')
312 subject = _("mail_va_no_subject");
314 subject_dup = g_strdup (subject);
315 tmp = g_strchug (subject_dup);
317 prefix = (is_reply) ? _("mail_va_re") : _("mail_va_fw");
318 prefix = g_strconcat (prefix, ":", NULL);
319 prefix_len = g_utf8_strlen (prefix, -1);
321 untranslated_prefix = (is_reply) ? "Re:" : "Fw:";
322 untranslated_prefix_len = 3;
324 if (g_str_has_prefix (tmp, prefix) ||
325 g_str_has_prefix (tmp, untranslated_prefix)) {
328 gchar *prefix_down, *tmp_down, *untranslated_down;
330 prefix_down = g_utf8_strdown (prefix, -1);
331 untranslated_down = g_utf8_strdown (untranslated_prefix, -1);
332 tmp_down = g_utf8_strdown (tmp, -1);
333 if (g_str_has_prefix (tmp_down, prefix_down) ||
334 g_str_has_prefix (tmp_down, untranslated_down) ||
335 (!is_reply && g_str_has_prefix (tmp_down, "fwd:")))
338 g_free (prefix_down);
339 g_free (untranslated_down);
344 /* If the prefix is already present do not touch the subject */
345 retval = subject_dup;
347 /* Normal case, add the prefix */
348 retval = g_strdup_printf ("%s %s", untranslated_prefix, tmp);
349 g_free (subject_dup);
357 /* Performs a case-insensitive strstr for ASCII strings */
359 ascii_stristr(const gchar *haystack, const gchar *needle)
364 const gchar *max_pos;
366 if (haystack == NULL || needle == NULL) {
367 return haystack; /* as in strstr */
370 needle_len = strlen(needle);
372 if (needle_len == 0) {
373 return haystack; /* as in strstr */
376 haystack_len = strlen(haystack);
377 max_pos = haystack + haystack_len - needle_len;
379 for (pos = haystack; pos <= max_pos; pos++) {
380 if (g_ascii_strncasecmp (pos, needle, needle_len) == 0) {
390 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
392 gchar *dup, *token, *ptr = NULL, *result;
393 GString *filtered_emails;
394 gchar *email_address;
396 g_return_val_if_fail (address_list, NULL);
399 return g_strdup (address_list);
401 email_address = get_email_from_address (address);
403 /* search for substring */
404 if (!ascii_stristr ((const char *) address_list, (const char *) email_address)) {
405 g_free (email_address);
406 return g_strdup (address_list);
409 dup = g_strdup (address_list);
410 filtered_emails = g_string_new (NULL);
412 token = strtok_r (dup, ",", &ptr);
414 while (token != NULL) {
415 /* Add to list if not found */
416 if (!ascii_stristr ((const char *) token, (const char *) email_address)) {
417 if (filtered_emails->len == 0)
418 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
420 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
422 token = strtok_r (NULL, ",", &ptr);
424 result = filtered_emails->str;
427 g_free (email_address);
429 g_string_free (filtered_emails, FALSE);
436 modest_text_utils_remove_duplicate_addresses (const gchar *address_list)
438 GSList *addresses, *cursor;
440 gchar *new_list = NULL;
442 g_return_val_if_fail (address_list, NULL);
444 table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
445 addresses = modest_text_utils_split_addresses_list (address_list);
449 const gchar* address = (const gchar*)cursor->data;
451 /* We need only the email to just compare it and not
452 the full address which would make "a <a@a.com>"
453 different from "a@a.com" */
454 const gchar *email = get_email_from_address (address);
456 /* ignore the address if already seen */
457 if (g_hash_table_lookup (table, email) == 0) {
460 /* Include the full address and not only the
461 email in the returned list */
463 tmp = g_strdup (address);
465 tmp = g_strjoin (",", new_list, address, NULL);
470 g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
472 cursor = g_slist_next (cursor);
475 g_hash_table_unref (table);
476 g_slist_foreach (addresses, (GFunc)g_free, NULL);
477 g_slist_free (addresses);
479 if (new_list == NULL)
480 new_list = g_strdup ("");
487 modest_text_utils_convert_buffer_to_html_start (GString *html, const gchar *data, gssize n)
490 gboolean space_seen = FALSE;
491 guint break_dist = 0; /* distance since last break point */
496 /* replace with special html chars where needed*/
497 for (i = 0; i != n; ++i) {
498 guchar kar = data[i];
500 if (space_seen && kar != ' ') {
501 g_string_append (html, " ");
505 /* we artificially insert a breakpoint (newline)
506 * after 256, to make sure our lines are not so long
507 * they will DOS the regexping later
508 * Also, check that kar is ASCII to make sure that we
509 * don't break a UTF8 char in two
511 if (++break_dist >= 256 && kar < 127) {
512 g_string_append_c (html, '\n');
520 /* this is a temp place holder for '&'; we can only
521 * set the real '&' after hyperlink translation, otherwise
522 * we might screw that up */
523 break; /* ignore embedded \0s and MARK_AMP */
524 case '<' : g_string_append (html, MARK_AMP_STR "lt;"); break;
525 case '>' : g_string_append (html, MARK_AMP_STR "gt;"); break;
526 case '&' : g_string_append (html, MARK_AMP_URI_STR "amp;"); break; /* special case */
527 case '"' : g_string_append (html, MARK_AMP_STR "quot;"); break;
529 /* don't convert ' --> wpeditor will try to re-convert it... */
530 //case '\'' : g_string_append (html, "'"); break;
531 case '\n' : g_string_append (html, "<br/>\n");break_dist= 0; break;
532 case '\t' : g_string_append (html, MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp; ");
533 break_dist=0; break; /* note the space at the end*/
536 if (space_seen) { /* second space in a row */
537 g_string_append (html, " ");
542 g_string_append_c (html, kar);
549 modest_text_utils_convert_buffer_to_html_finish (GString *html)
552 /* replace all our MARK_AMPs with real ones */
553 for (i = 0; i != html->len; ++i)
554 if ((html->str)[i] == MARK_AMP || (html->str)[i] == MARK_AMP_URI)
555 (html->str)[i] = '&';
560 modest_text_utils_convert_to_html (const gchar *data)
565 g_return_val_if_fail (data, NULL);
571 html = g_string_sized_new (1.5 * len); /* just a guess... */
573 g_string_append_printf (html,
575 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
579 modest_text_utils_convert_buffer_to_html_start (html, data, -1);
581 g_string_append (html, "</body></html>");
583 if (len <= HYPERLINKIFY_MAX_LENGTH)
584 hyperlinkify_plain_text (html, 0);
586 modest_text_utils_convert_buffer_to_html_finish (html);
588 return g_string_free (html, FALSE);
592 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
596 g_return_val_if_fail (data, NULL);
603 html = g_string_sized_new (1.5 * n); /* just a guess... */
605 modest_text_utils_convert_buffer_to_html_start (html, data, n);
607 if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
608 hyperlinkify_plain_text (html, 0);
610 modest_text_utils_convert_buffer_to_html_finish (html);
612 return g_string_free (html, FALSE);
616 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
624 if (strlen (addresses) == 0)
627 str = g_string_new ("");
628 start = (gchar*) addresses;
629 cur = (gchar*) addresses;
631 for (cur = start; *cur != '\0'; cur = g_utf8_next_char (cur)) {
632 if (*cur == ',' || *cur == ';') {
633 gint *start_index, *end_index;
634 gchar *next_char = g_utf8_next_char (cur);
636 if (!g_utf8_strchr (start, (cur - start + 1), g_utf8_get_char ("@")) &&
637 next_char && *next_char != '\n' && *next_char != '\0')
640 start_index = g_new0 (gint, 1);
641 end_index = g_new0 (gint, 1);
642 *start_index = g_utf8_pointer_to_offset (addresses, start);
643 *end_index = g_utf8_pointer_to_offset (addresses, cur);;
644 *start_indexes = g_slist_prepend (*start_indexes, start_index);
645 *end_indexes = g_slist_prepend (*end_indexes, end_index);
646 start = g_utf8_next_char (cur);
651 gint *start_index, *end_index;
652 start_index = g_new0 (gint, 1);
653 end_index = g_new0 (gint, 1);
654 *start_index = g_utf8_pointer_to_offset (addresses, start);
655 *end_index = g_utf8_pointer_to_offset (addresses, cur);;
656 *start_indexes = g_slist_prepend (*start_indexes, start_index);
657 *end_indexes = g_slist_prepend (*end_indexes, end_index);
661 *start_indexes = g_slist_reverse (*start_indexes);
663 *end_indexes = g_slist_reverse (*end_indexes);
668 modest_text_utils_split_addresses_list (const gchar *addresses)
671 const gchar *my_addrs = addresses;
674 gboolean after_at = FALSE;
676 g_return_val_if_fail (addresses, NULL);
678 /* skip any space, ',', ';' '\n' at the start */
679 while (my_addrs && (my_addrs[0] == ' ' || my_addrs[0] == ',' ||
680 my_addrs[0] == ';' || my_addrs[0] == '\n'))
683 /* are we at the end of addresses list? */
687 /* nope, we are at the start of some address
688 * now, let's find the end of the address */
690 while (end[0] && end[0] != ';' && !(after_at && end[0] == ',')) {
691 if (end[0] == '\"') {
692 while (end[0] && end[0] != '\"')
698 if ((end[0] && end[0] == '>')&&(end[1] && end[1] == ',')) {
705 /* we got the address; copy it and remove trailing whitespace */
706 addr = g_strndup (my_addrs, end - my_addrs);
709 remove_extra_spaces (addr);
711 head = g_slist_append (NULL, addr);
712 head->next = modest_text_utils_split_addresses_list (end); /* recurse */
718 modest_text_utils_join_addresses (const gchar *from,
724 gboolean add_separator = FALSE;
726 buffer = g_string_new ("");
728 if (from && strlen (from)) {
729 buffer = g_string_append (buffer, from);
730 add_separator = TRUE;
732 if (to && strlen (to)) {
734 buffer = g_string_append (buffer, "; ");
736 add_separator = TRUE;
738 buffer = g_string_append (buffer, to);
740 if (cc && strlen (cc)) {
742 buffer = g_string_append (buffer, "; ");
744 add_separator = TRUE;
746 buffer = g_string_append (buffer, cc);
748 if (bcc && strlen (bcc)) {
750 buffer = g_string_append (buffer, "; ");
752 add_separator = TRUE;
754 buffer = g_string_append (buffer, bcc);
757 return g_string_free (buffer, FALSE);
761 modest_text_utils_address_range_at_position (const gchar *recipients_list,
766 gchar *current = NULL;
767 gint range_start = 0;
770 gboolean is_quoted = FALSE;
772 g_return_if_fail (recipients_list);
773 g_return_if_fail (position < g_utf8_strlen(recipients_list, -1));
776 for (current = (gchar *) recipients_list; *current != '\0';
777 current = g_utf8_find_next_char (current, NULL)) {
778 gunichar c = g_utf8_get_char (current);
780 if ((c == ',') && (!is_quoted)) {
781 if (index < position) {
782 range_start = index + 1;
786 } else if (c == '\"') {
787 is_quoted = !is_quoted;
788 } else if ((c == ' ') &&(range_start == index)) {
796 *start = range_start;
802 modest_text_utils_address_with_standard_length (const gchar *recipients_list)
806 GString *buffer = g_string_new ("");
808 splitted = g_strsplit (recipients_list, "\n", 0);
812 if (current != splitted)
813 buffer = g_string_append_c (buffer, '\n');
814 line = g_strndup (*splitted, 1000);
815 buffer = g_string_append (buffer, line);
820 g_strfreev (splitted);
822 return g_string_free (buffer, FALSE);
826 /* ******************************************************************* */
827 /* ************************* UTILIY FUNCTIONS ************************ */
828 /* ******************************************************************* */
831 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
837 return g_string_new("");
845 gs = g_string_new_len (i0, iter - i0);
849 get_indent_level (const char *l)
866 /* if we hit the signature marker "-- ", we return -(indent + 1). This
867 * stops reformatting.
869 if (strcmp (l, MODEST_TEXT_UTILS_SIGNATURE_MARKER) == 0) {
877 unquote_line (GString * l, const gchar *quote_symbol)
883 quote_len = strlen (quote_symbol);
885 if (g_str_has_prefix (p, quote_symbol)) {
887 while (p[0] && p[0] == ' ') {
896 g_string_erase (l, 0, p - l->str);
900 append_quoted (GString * buf, const gchar *quote_symbol,
901 int indent, const GString * str,
907 indent = indent < 0 ? abs (indent) - 1 : indent;
908 quote_concat = g_strconcat (quote_symbol, " ", NULL);
909 for (i = 0; i <= indent; i++) {
910 g_string_append (buf, quote_concat);
912 g_free (quote_concat);
914 g_string_append_len (buf, str->str, cutpoint);
916 g_string_append (buf, str->str);
918 g_string_append (buf, "\n");
922 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
925 const gchar *pos, *last;
928 if (2*indent >= limit)
931 indent = indent < 0 ? abs (indent) - 1 : indent;
935 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
937 if ((index + 2 * indent > limit) && last) {
941 if (g_unichar_isspace (uni[index])) {
944 pos = g_utf8_next_char (pos);
952 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
957 if (last + 2 * indent < limit)
960 for (i = strlen (s); i > 0; i--) {
962 if (i + 2 * indent <= limit) {
973 get_breakpoint (const gchar * s, const gint indent, const gint limit)
976 if (g_utf8_validate (s, -1, NULL)) {
977 return get_breakpoint_utf8 (s, indent, limit);
978 } else { /* assume ASCII */
979 //g_warning("invalid UTF-8 in msg");
980 return get_breakpoint_ascii (s, indent, limit);
985 cite (const time_t sent_date, const gchar *from)
987 return g_strdup (_("mcen_ia_editor_original_message"));
991 quoted_attachments (GList *attachments)
994 GString *result = g_string_new ("");
995 for (node = attachments; node != NULL; node = g_list_next (node)) {
996 gchar *filename = (gchar *) node->data;
997 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
1000 return g_string_free (result, FALSE);
1005 modest_text_utils_quote_body (GString *output, const gchar *text,
1006 const gchar *quote_symbol,
1012 gint indent, breakpoint, rem_indent = 0;
1013 GString *l, *remaining;
1014 gchar *forced_wrap_append;
1018 remaining = g_string_new ("");
1019 forced_wrap_append = NULL;
1022 if (forced_wrap_append) {
1023 gint next_line_indent;
1024 gint l_len_with_indent;
1026 g_string_erase (remaining, 0, -1);
1027 next_line_indent = get_indent_level (iter);
1028 l = get_next_line (text, len, iter);
1029 l_len_with_indent = l->len;
1030 unquote_line (l, quote_symbol);
1031 if ((l->str && l->str[0] == '\0') || (next_line_indent != indent)) {
1032 g_string_free (l, TRUE);
1033 l = g_string_new (forced_wrap_append);
1035 gunichar first_in_l;
1036 iter = iter + l_len_with_indent + 1;
1037 first_in_l = g_utf8_get_char_validated (l->str, l->len);
1038 if (!g_unichar_isspace (first_in_l))
1039 l = g_string_prepend (l, " ");
1040 l = g_string_prepend (l, forced_wrap_append);
1042 g_free (forced_wrap_append);
1043 forced_wrap_append = NULL;
1045 l = get_next_line (text, len, iter);
1046 iter = iter + l->len + 1;
1047 indent = get_indent_level (l->str);
1048 unquote_line (l, quote_symbol);
1051 if (remaining->len) {
1052 if (l->len && indent == rem_indent) {
1053 g_string_prepend (l, " ");
1054 g_string_prepend (l, remaining->str);
1057 gunichar remaining_first;
1059 get_breakpoint (remaining->str,
1062 if (breakpoint < remaining->len) {
1063 g_free (forced_wrap_append);
1064 forced_wrap_append = g_strdup (remaining->str + breakpoint);
1066 if (!forced_wrap_append)
1067 append_quoted (output, quote_symbol, rem_indent,
1068 remaining, breakpoint);
1070 g_string_erase (remaining, 0,
1072 remaining_first = g_utf8_get_char_validated (remaining->str, remaining->len);
1073 if (remaining_first != ((gunichar) -1)) {
1074 if (g_unichar_isspace (remaining_first)) {
1075 g_string_erase (remaining, 0, g_utf8_next_char (remaining->str) - remaining->str);
1078 } while (remaining->len);
1081 g_string_free (remaining, TRUE);
1082 breakpoint = get_breakpoint (l->str, indent, limit);
1083 remaining = g_string_new (l->str + breakpoint);
1084 if (remaining->str[0] == ' ') {
1085 g_string_erase (remaining, 0, 1);
1087 rem_indent = indent;
1088 if (remaining->len > 0) {
1089 g_free (forced_wrap_append);
1090 forced_wrap_append = g_strdup (remaining->str);
1092 append_quoted (output, quote_symbol, indent, l, breakpoint);
1093 g_string_free (l, TRUE);
1094 } while ((iter < text + len) || (remaining->str[0]) || forced_wrap_append);
1100 modest_text_utils_quote_plain_text (const gchar *text,
1102 const gchar *signature,
1107 gchar *attachments_string = NULL;
1109 q = g_string_new ("");
1111 if (signature != NULL) {
1112 g_string_append_printf (q, "\n%s\n", MODEST_TEXT_UTILS_SIGNATURE_MARKER);
1113 q = g_string_append (q, signature);
1116 q = g_string_append (q, "\n");
1117 q = g_string_append (q, cite);
1118 q = g_string_append_c (q, '\n');
1120 q = modest_text_utils_quote_body (q, text, ">", limit);
1122 attachments_string = quoted_attachments (attachments);
1123 q = g_string_append (q, attachments_string);
1124 g_free (attachments_string);
1126 return g_string_free (q, FALSE);
1130 quote_html_add_to_gstring (GString *string,
1133 if (text && strcmp (text, "")) {
1134 gchar *html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
1135 g_string_append_printf (string, "%s<br/>", html_text);
1141 modest_text_utils_quote_html (const gchar *text,
1143 const gchar *signature,
1147 GString *result_string;
1151 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
1155 if (text || cite || signature) {
1156 GString *quoted_text;
1157 g_string_append (result_string, "<pre>\n");
1159 gchar *colored_signature = modest_text_utils_create_colored_signature (signature);
1160 g_string_append_printf (result_string, "%s<br/>", colored_signature);
1161 g_free (colored_signature);
1163 quote_html_add_to_gstring (result_string, cite);
1164 quoted_text = g_string_new ("");
1165 quoted_text = modest_text_utils_quote_body (quoted_text, (text) ? text : "", ">", limit);
1166 quote_html_add_to_gstring (result_string, quoted_text->str);
1167 g_string_free (quoted_text, TRUE);
1169 gchar *attachments_string = quoted_attachments (attachments);
1170 quote_html_add_to_gstring (result_string, attachments_string);
1171 g_free (attachments_string);
1173 g_string_append (result_string, "</pre>");
1175 g_string_append (result_string, "</body>");
1176 g_string_append (result_string, "</html>");
1178 return g_string_free (result_string, FALSE);
1182 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
1184 return match2->offset - match1->offset;
1187 static gint url_matches_block = 0;
1188 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
1189 static GMutex *url_patterns_mutex = NULL;
1196 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1197 for (i = 0; i != pattern_num; ++i) {
1198 patterns[i].preg = g_slice_new0 (regex_t);
1200 /* this should not happen */
1201 if (regcomp (patterns[i].preg, patterns[i].regex,
1202 REG_ICASE|REG_EXTENDED|REG_NEWLINE) != 0) {
1203 g_warning ("%s: error in regexp:\n%s\n", __FUNCTION__, patterns[i].regex);
1214 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1215 for (i = 0; i != pattern_num; ++i) {
1216 regfree (patterns[i].preg);
1217 g_slice_free (regex_t, patterns[i].preg);
1218 } /* don't free patterns itself -- it's static */
1222 modest_text_utils_hyperlinkify_begin (void)
1225 if (url_patterns_mutex == NULL) {
1226 url_patterns_mutex = g_mutex_new ();
1228 g_mutex_lock (url_patterns_mutex);
1229 if (url_matches_block == 0)
1230 compile_patterns ();
1231 url_matches_block ++;
1232 g_mutex_unlock (url_patterns_mutex);
1236 modest_text_utils_hyperlinkify_end (void)
1238 g_mutex_lock (url_patterns_mutex);
1239 url_matches_block--;
1240 if (url_matches_block <= 0)
1242 g_mutex_unlock (url_patterns_mutex);
1247 get_url_matches (GString *txt, gint offset)
1250 guint rv, i, tmp_offset = 0;
1251 GSList *match_list = NULL;
1253 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1255 /* initalize the regexps */
1256 modest_text_utils_hyperlinkify_begin ();
1258 /* find all the matches */
1259 for (i = 0; i != pattern_num; ++i) {
1260 tmp_offset = offset;
1263 gboolean is_submatch;
1266 if ((rv = regexec (patterns[i].preg, txt->str + tmp_offset, 1, &rm, 0)) != 0) {
1267 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
1268 break; /* try next regexp */
1273 is_submatch = FALSE;
1274 /* check old matches to see if this has already been matched */
1275 cursor = match_list;
1276 while (cursor && !is_submatch) {
1277 const url_match_t *old_match =
1278 (const url_match_t *) cursor->data;
1279 guint new_offset = tmp_offset + rm.rm_so;
1280 is_submatch = (new_offset > old_match->offset &&
1281 new_offset < old_match->offset + old_match->len);
1282 cursor = g_slist_next (cursor);
1286 /* make a list of our matches (<offset, len, prefix> tupels)*/
1287 match = g_slice_new (url_match_t);
1288 match->offset = tmp_offset + rm.rm_so;
1289 match->len = rm.rm_eo - rm.rm_so;
1290 match->prefix = patterns[i].prefix;
1291 match_list = g_slist_prepend (match_list, match);
1293 tmp_offset += rm.rm_eo;
1297 modest_text_utils_hyperlinkify_end ();
1299 /* now sort the list, so the matches are in reverse order of occurence.
1300 * that way, we can do the replacements starting from the end, so we don't need
1301 * to recalculate the offsets
1303 match_list = g_slist_sort (match_list,
1304 (GCompareFunc)cmp_offsets_reverse);
1310 /* replace all occurences of needle in haystack with repl*/
1312 replace_string (const gchar *haystack, const gchar *needle, gchar repl)
1314 gchar *str, *cursor;
1316 if (!haystack || !needle || strlen(needle) == 0)
1317 return haystack ? g_strdup(haystack) : NULL;
1319 str = g_strdup (haystack);
1321 for (cursor = str; cursor && *cursor; ++cursor) {
1322 if (g_str_has_prefix (cursor, needle)) {
1324 memmove (cursor + 1,
1325 cursor + strlen (needle),
1326 strlen (cursor + strlen (needle)) + 1);
1334 hyperlinkify_plain_text (GString *txt, gint offset)
1337 GSList *match_list = get_url_matches (txt, offset);
1339 /* we will work backwards, so the offsets stay valid */
1340 for (cursor = match_list; cursor; cursor = cursor->next) {
1342 url_match_t *match = (url_match_t*) cursor->data;
1343 gchar *url = g_strndup (txt->str + match->offset, match->len);
1344 gchar *repl = NULL; /* replacement */
1346 /* the string still contains $(MARK_AMP_URI_STR)"amp;" for each
1347 * '&' in the original, because of the text->html conversion.
1348 * in the href-URL (and only there), we must convert that back to
1351 gchar *href_url = replace_string (url, MARK_AMP_URI_STR "amp;", '&');
1353 /* the prefix is NULL: use the one that is already there */
1354 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1355 match->prefix ? match->prefix : EMPTY_STRING,
1358 /* replace the old thing with our hyperlink
1359 * replacement thing */
1360 g_string_erase (txt, match->offset, match->len);
1361 g_string_insert (txt, match->offset, repl);
1367 g_slice_free (url_match_t, match);
1370 g_slist_free (match_list);
1374 modest_text_utils_hyperlinkify (GString *string_buffer)
1379 after_body = strstr (string_buffer->str, "<body>");
1380 if (after_body != NULL)
1381 offset = after_body - string_buffer->str;
1382 hyperlinkify_plain_text (string_buffer, offset);
1386 /* for optimization reasons, we change the string in-place */
1388 modest_text_utils_get_display_address (gchar *address)
1392 g_return_if_fail (address);
1397 /* should not be needed, and otherwise, we probably won't screw up the address
1398 * more than it already is :)
1399 * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1402 /* remove leading whitespace */
1403 if (address[0] == ' ')
1404 g_strchug (address);
1406 for (i = 0; address[i]; ++i) {
1407 if (address[i] == '<') {
1408 if (G_UNLIKELY(i == 0)) {
1409 break; /* there's nothing else, leave it */
1411 address[i] = '\0'; /* terminate the string here */
1417 g_strchomp (address);
1422 modest_text_utils_get_display_addresses (const gchar *recipients)
1425 GSList *recipient_list;
1428 recipient_list = modest_text_utils_split_addresses_list (recipients);
1429 if (recipient_list) {
1430 GString *add_string = g_string_sized_new (strlen (recipients));
1431 GSList *iter = recipient_list;
1432 gboolean first = TRUE;
1435 /* Strings are changed in place */
1436 modest_text_utils_get_display_address ((gchar *) iter->data);
1437 if (G_UNLIKELY (first)) {
1438 g_string_append_printf (add_string, "%s", (gchar *) iter->data);
1441 g_string_append_printf (add_string, ", %s", (gchar *) iter->data);
1443 iter = g_slist_next (iter);
1445 g_slist_foreach (recipient_list, (GFunc) g_free, NULL);
1446 g_slist_free (recipient_list);
1447 addresses = g_string_free (add_string, FALSE);
1455 modest_text_utils_get_email_address (const gchar *full_address)
1457 const gchar *left, *right;
1459 g_return_val_if_fail (full_address, NULL);
1464 g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1466 left = g_strrstr_len (full_address, strlen(full_address), "<");
1468 return g_strdup (full_address);
1470 right = g_strstr_len (left, strlen(left), ">");
1472 return g_strdup (full_address);
1474 return g_strndup (left + 1, right - left - 1);
1478 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1480 gint prefix_len = 0;
1482 g_return_val_if_fail (sub, 0);
1487 /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1488 if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1490 else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1497 /* skip over a [...] block */
1498 if (sub[prefix_len] == '[') {
1499 int c = prefix_len + 1;
1500 while (sub[c] && sub[c] != ']')
1503 return 0; /* no end to the ']' found */
1508 /* did we find the ':' ? */
1509 if (sub[prefix_len] == ':') {
1511 if (sub[prefix_len] == ' ')
1513 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1514 /* g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1522 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1525 /* work even when s1 and/or s2 == NULL */
1526 if (G_UNLIKELY(s1 == s2))
1528 if (G_UNLIKELY(!s1))
1530 if (G_UNLIKELY(!s2))
1533 /* if it's not case sensitive */
1536 /* optimization: shortcut if first char is ascii */
1537 if (((s1[0] & 0x80)== 0) && ((s2[0] & 0x80) == 0) &&
1539 return s1[0] - s2[0];
1541 return g_utf8_collate (s1, s2);
1547 /* optimization: shortcut if first char is ascii */
1548 if (((s1[0] & 0x80) == 0) && ((s2[0] & 0x80) == 0) &&
1549 (tolower(s1[0]) != tolower (s2[0])))
1550 return tolower(s1[0]) - tolower(s2[0]);
1552 n1 = g_utf8_strdown (s1, -1);
1553 n2 = g_utf8_strdown (s2, -1);
1555 result = g_utf8_collate (n1, n2);
1566 modest_text_utils_get_display_date (time_t date)
1568 #define DATE_BUF_SIZE 64
1569 static gchar date_buf[DATE_BUF_SIZE];
1571 /* calculate the # of days since epoch for
1572 * for today and for the date provided
1573 * based on idea from pvanhoof */
1574 int day = time(NULL) / (24 * 60 * 60);
1575 int date_day = date / (24 * 60 * 60);
1577 /* if it's today, show the time, if it's not today, show the date instead */
1579 /* TODO: take into account the system config for 24/12h */
1580 #ifdef MODEST_TOOLKIT_HILDON2
1581 if (day == date_day) /* is the date today? */
1582 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_24h_time"), date);
1584 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_date"), date);
1586 if (day == date_day) /* is the date today? */
1587 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%X", date);
1589 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%x", date);
1592 return date_buf; /* this is a static buffer, don't free! */
1598 modest_text_utils_validate_folder_name (const gchar *folder_name)
1600 /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1601 * with some extras */
1605 const gchar **cursor = NULL;
1606 const gchar *forbidden_names[] = { /* windows does not like these */
1607 "CON", "PRN", "AUX", "NUL", ".", "..", "cur", "tmp", "new",
1608 NULL /* cur, tmp, new are reserved for Maildir */
1611 /* cannot be NULL */
1615 /* cannot be empty */
1616 len = strlen(folder_name);
1620 /* cannot start with a dot, vfat does not seem to like that */
1621 if (folder_name[0] == '.')
1624 /* cannot start or end with a space */
1625 if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1628 /* cannot contain a forbidden char */
1629 for (i = 0; i < len; i++)
1630 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1633 /* Cannot contain Windows port numbers. I'd like to use GRegex
1634 but it's still not available in Maemo. sergio */
1635 if (!g_ascii_strncasecmp (folder_name, "LPT", 3) ||
1636 !g_ascii_strncasecmp (folder_name, "COM", 3)) {
1640 /* We skip the first 3 characters for the
1642 val = strtol(folder_name+3, &endptr, 10);
1644 /* If the conversion to long succeeded then the string
1645 is not valid for us */
1646 if (*endptr == '\0')
1652 /* cannot contain a forbidden word */
1654 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1655 if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1660 return TRUE; /* it's valid! */
1666 modest_text_utils_validate_domain_name (const gchar *domain)
1668 gboolean valid = FALSE;
1670 const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1672 g_return_val_if_fail (domain, FALSE);
1677 memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1679 /* domain name: all alphanum or '-' or '.',
1680 * but beginning/ending in alphanum */
1681 if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1682 g_warning ("BUG: error in regexp");
1686 valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1695 modest_text_utils_validate_email_address (const gchar *email_address,
1696 const gchar **invalid_char_position)
1699 const gchar *c = NULL, *domain = NULL;
1700 static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1702 if (invalid_char_position)
1703 *invalid_char_position = NULL;
1705 g_return_val_if_fail (email_address, FALSE);
1707 /* check that the email adress contains exactly one @ */
1708 if (!strstr(email_address, "@") ||
1709 (strstr(email_address, "@") != g_strrstr(email_address, "@")))
1712 /* first we validate the name portion (name@domain) */
1713 for (c = email_address; *c; c++) {
1715 (c == email_address ||
1717 *(c - 1) == '\"')) {
1721 if (*c == '\\' && (*++c == ' '))
1723 if (*c <= ' ' || *c >= 127)
1736 if (*c <= ' ' || *c >= 127)
1738 if (strchr(rfc822_specials, *c)) {
1739 if (invalid_char_position)
1740 *invalid_char_position = c;
1744 if (c == email_address || *(c - 1) == '.')
1747 /* next we validate the domain portion (name@domain) */
1748 if (!*(domain = ++c))
1752 if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0')
1756 if (*c <= ' ' || *c >= 127)
1758 if (strchr(rfc822_specials, *c)) {
1759 if (invalid_char_position)
1760 *invalid_char_position = c;
1765 return (count >= 1) ? TRUE : FALSE;
1769 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1771 gchar *stripped, *current;
1773 gboolean has_error = FALSE;
1775 if (invalid_char_position)
1776 *invalid_char_position = NULL;
1778 g_return_val_if_fail (recipient, FALSE);
1780 if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1783 stripped = g_strdup (recipient);
1784 stripped = g_strstrip (stripped);
1787 if (*current == '\0') {
1793 if (*current == '\"') {
1794 gchar *last_quote = NULL;
1795 current = g_utf8_next_char (current);
1797 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1798 if (*current == '\\') {
1799 /* TODO: This causes a warning, which breaks the build,
1800 * because a gchar cannot be < 0.
1802 if (current[1] <0) {
1807 } else if (*current == '\"') {
1809 current = g_utf8_next_char (current);
1810 last_quote = current;
1814 current = g_utf8_next_char (last_quote);
1817 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1818 if (*current == '<') {
1830 right_part = g_strdup (current);
1832 right_part = g_strstrip (right_part);
1834 if (g_str_has_suffix (right_part, ",") || g_str_has_suffix (right_part, ";"))
1835 right_part [(strlen (right_part) - 1)] = '\0';
1837 if (g_str_has_prefix (right_part, "<") &&
1838 g_str_has_suffix (right_part, ">")) {
1842 address = g_strndup (right_part+1, strlen (right_part) - 2);
1843 g_free (right_part);
1844 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1848 g_free (right_part);
1855 modest_text_utils_get_display_size (guint64 size)
1857 const guint KB=1024;
1858 const guint MB=1024 * KB;
1859 const guint GB=1024 * MB;
1862 return g_strdup_printf (_FM_SIZE_KB, (int) 0);
1863 if (0 <= size && size < KB)
1864 return g_strdup_printf (_FM_SIZE_1KB_99KB, (int) 1);
1865 else if (KB <= size && size < 100 * KB)
1866 return g_strdup_printf (_FM_SIZE_1KB_99KB, (int) size / KB);
1867 else if (100*KB <= size && size < MB)
1868 return g_strdup_printf (_FM_SIZE_100KB_1MB, (int) size / KB);
1869 else if (MB <= size && size < 10*MB)
1870 return g_strdup_printf (_FM_SIZE_1MB_10MB, (float) size / MB);
1871 else if (10*MB <= size && size < GB)
1872 return g_strdup_printf (_FM_SIZE_10MB_1GB, (float) size / MB);
1874 return g_strdup_printf (_FM_SIZE_1GB_OR_GREATER, (float) size / GB);
1878 get_email_from_address (const gchar * address)
1880 gchar *left_limit, *right_limit;
1882 left_limit = strstr (address, "<");
1883 right_limit = g_strrstr (address, ">");
1885 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1886 return g_strdup (address);
1888 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1892 modest_text_utils_get_color_string (GdkColor *color)
1894 g_return_val_if_fail (color, NULL);
1896 return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1897 (color->red >> 12) & 0xf, (color->red >> 8) & 0xf,
1898 (color->red >> 4) & 0xf, (color->red) & 0xf,
1899 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1900 (color->green >> 4) & 0xf, (color->green) & 0xf,
1901 (color->blue >> 12) & 0xf, (color->blue >> 8) & 0xf,
1902 (color->blue >> 4) & 0xf, (color->blue) & 0xf);
1906 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1908 GtkTextIter start, end;
1909 gchar *slice, *current;
1910 GString *result = g_string_new ("");
1912 g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1914 gtk_text_buffer_get_start_iter (buffer, &start);
1915 gtk_text_buffer_get_end_iter (buffer, &end);
1917 slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1920 while (current && current != '\0') {
1921 if (g_utf8_get_char (current) == 0xFFFC) {
1922 result = g_string_append_c (result, ' ');
1923 current = g_utf8_next_char (current);
1925 gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1927 result = g_string_append (result, current);
1929 result = g_string_append_len (result, current, next - current);
1936 return g_string_free (result, FALSE);
1941 modest_text_utils_is_forbidden_char (const gchar character,
1942 ModestTextUtilsForbiddenCharType type)
1945 const gchar *forbidden_chars = NULL;
1947 /* We need to get the length in the switch because the
1948 compiler needs to know the size at compile time */
1950 case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1951 forbidden_chars = account_title_forbidden_chars;
1952 len = G_N_ELEMENTS (account_title_forbidden_chars);
1954 case FOLDER_NAME_FORBIDDEN_CHARS:
1955 forbidden_chars = folder_name_forbidden_chars;
1956 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1958 case USER_NAME_FORBIDDEN_NAMES:
1959 forbidden_chars = user_name_forbidden_chars;
1960 len = G_N_ELEMENTS (user_name_forbidden_chars);
1963 g_return_val_if_reached (TRUE);
1966 for (i = 0; i < len ; i++)
1967 if (forbidden_chars[i] == character)
1970 return FALSE; /* it's valid! */
1974 modest_text_utils_label_get_selection (GtkLabel *label)
1979 if (gtk_label_get_selection_bounds (GTK_LABEL (label), &start, &end)) {
1980 const gchar *start_offset;
1981 const gchar *end_offset;
1982 start_offset = gtk_label_get_text (GTK_LABEL (label));
1983 start_offset = g_utf8_offset_to_pointer (start_offset, start);
1984 end_offset = gtk_label_get_text (GTK_LABEL (label));
1985 end_offset = g_utf8_offset_to_pointer (end_offset, end);
1986 selection = g_strndup (start_offset, end_offset - start_offset);
1989 return g_strdup ("");
1994 _forward_search_image_char (gunichar ch,
1997 return (ch == 0xFFFC);
2001 modest_text_utils_buffer_selection_is_valid (GtkTextBuffer *buffer)
2004 GtkTextIter start, end;
2006 g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2008 result = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (buffer));
2010 /* check there are no images in selection */
2012 gtk_text_buffer_get_selection_bounds (buffer, &start, &end);
2013 if (gtk_text_iter_get_char (&start)== 0xFFFC)
2016 gtk_text_iter_backward_char (&end);
2017 if (gtk_text_iter_forward_find_char (&start, _forward_search_image_char,
2028 remove_quotes (gchar **quotes)
2030 if (g_str_has_prefix (*quotes, "\"") && g_str_has_suffix (*quotes, "\"")) {
2032 result = g_strndup ((*quotes)+1, strlen (*quotes) - 2);
2039 remove_extra_spaces (gchar *string)
2044 while (start && start[0] != '\0') {
2045 if ((start[0] == ' ') && (start[1] == ' ')) {
2046 g_strchug (start+1);
2053 modest_text_utils_escape_mnemonics (const gchar *text)
2056 GString *result = NULL;
2061 result = g_string_new ("");
2062 for (p = text; *p != '\0'; p++) {
2064 result = g_string_append (result, "__");
2066 result = g_string_append_c (result, *p);
2069 return g_string_free (result, FALSE);
2073 modest_text_utils_simplify_recipients (const gchar *recipients)
2075 GSList *addresses, *node;
2077 gboolean is_first = TRUE;
2079 if (recipients == NULL)
2080 return g_strdup ("");
2082 addresses = modest_text_utils_split_addresses_list (recipients);
2083 result = g_string_new ("");
2085 for (node = addresses; node != NULL; node = g_slist_next (node)) {
2086 const gchar *address = (const gchar *) node->data;
2087 gchar *left_limit, *right_limit;
2089 left_limit = strstr (address, "<");
2090 right_limit = g_strrstr (address, ">");
2095 result = g_string_append (result, ", ");
2097 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit)) {
2098 result = g_string_append (result, address);
2102 name_side = g_strndup (address, left_limit - address);
2103 name_side = g_strstrip (name_side);
2104 remove_quotes (&name_side);
2105 email_side = get_email_from_address (address);
2106 if (name_side && email_side && !strcmp (name_side, email_side)) {
2107 result = g_string_append (result, email_side);
2109 result = g_string_append (result, address);
2112 g_free (email_side);
2116 g_slist_foreach (addresses, (GFunc)g_free, NULL);
2117 g_slist_free (addresses);
2119 return g_string_free (result, FALSE);
2124 modest_text_utils_remove_duplicate_addresses_list (GSList *address_list)
2126 GSList *new_list, *iter;
2129 g_return_val_if_fail (address_list, NULL);
2131 table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2133 new_list = address_list;
2134 iter = address_list;
2136 const gchar* address = (const gchar*)iter->data;
2138 /* We need only the email to just compare it and not
2139 the full address which would make "a <a@a.com>"
2140 different from "a@a.com" */
2141 const gchar *email = get_email_from_address (address);
2143 /* ignore the address if already seen */
2144 if (g_hash_table_lookup (table, email) == 0) {
2145 g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
2146 iter = g_slist_next (iter);
2148 GSList *tmp = g_slist_next (iter);
2149 new_list = g_slist_delete_link (new_list, iter);
2154 g_hash_table_unref (table);
2160 modest_text_utils_get_secure_header (const gchar *value,
2161 const gchar *header)
2163 const gint max_len = 16384;
2164 gchar *new_value = NULL;
2165 gchar *needle = g_strrstr (value, header);
2167 if (needle && value != needle)
2168 new_value = g_strdup (needle + strlen (header));
2171 new_value = g_strdup (value);
2173 /* Do a max length check to prevent DoS attacks caused by huge
2174 malformed headers */
2175 if (g_utf8_validate (new_value, -1, NULL)) {
2176 if (g_utf8_strlen (new_value, -1) > max_len) {
2177 gchar *tmp = g_malloc0 (max_len * 4);
2178 g_utf8_strncpy (tmp, (const gchar *) new_value, max_len);
2183 if (strlen (new_value) > max_len) {
2184 gchar *tmp = g_malloc0 (max_len);
2185 strncpy (new_value, tmp, max_len);
2195 is_quoted (const char *start, const gchar *end)
2199 c = (gchar *) start;
2201 c = g_utf8_next_char (c);
2203 if (*c == '\0' || *c != '\"')
2207 while (*c == ' ' && c != start)
2208 c = g_utf8_prev_char (c);
2210 if (c == start || *c != '\"')
2218 quote_name_part (GString **str, gchar **cur, gchar **start)
2221 gint str_len = *cur - *start;
2223 while (**start == ' ') {
2224 *start = g_utf8_next_char (*start);
2228 blank = g_utf8_strrchr (*start, str_len, g_utf8_get_char (" "));
2229 if (blank && (blank != *start)) {
2230 if (is_quoted (*start, blank - 1)) {
2231 *str = g_string_append_len (*str, *start, str_len);
2232 *str = g_string_append (*str, ";");
2233 *start = g_utf8_next_char (*cur);
2235 *str = g_string_append_c (*str, '"');
2236 *str = g_string_append_len (*str, *start,
2237 (g_utf8_pointer_to_offset (*start, blank) -
2238 g_utf8_pointer_to_offset (*start, *start)));
2239 *str = g_string_append_c (*str, '"');
2240 *str = g_string_append_len (*str, blank,
2241 (g_utf8_pointer_to_offset (*start, *cur) -
2242 g_utf8_pointer_to_offset (*start, blank)));
2243 *str = g_string_append (*str, ";");
2244 *start = g_utf8_next_char (*cur);
2247 *str = g_string_append_len (*str, *start, str_len);
2248 *str = g_string_append (*str, ";");
2249 *start = g_utf8_next_char (*cur);
2254 modest_text_utils_quote_names (const gchar *recipients)
2259 str = g_string_new ("");
2260 start = (gchar*) recipients;
2261 cur = (gchar*) recipients;
2263 for (cur = start; *cur != '\0'; cur = g_utf8_next_char (cur)) {
2264 if (*cur == ',' || *cur == ';') {
2265 if (!g_utf8_strchr (start, (cur - start + 1), g_utf8_get_char ("@")))
2267 quote_name_part (&str, &cur, &start);
2271 quote_name_part (&str, &cur, &start);
2273 return g_string_free (str, FALSE);
2276 /* Returns TRUE if there is no recipients in the text buffer. Note
2277 that strings like " ; , " contain only separators and thus no
2280 modest_text_utils_no_recipient (GtkTextBuffer *buffer)
2282 gboolean retval = TRUE;
2284 GtkTextIter start, end;
2286 if (gtk_text_buffer_get_char_count (buffer) == 0)
2289 gtk_text_buffer_get_start_iter (buffer, &start);
2290 gtk_text_buffer_get_end_iter (buffer, &end);
2292 text = g_strstrip (gtk_text_buffer_get_text (buffer, &start, &end, FALSE));
2293 if (!g_strcmp0 (text, ""))
2297 while (tmp && *tmp != '\0') {
2298 if ((*tmp != ',') && (*tmp != ';') &&
2299 (*tmp != '\r') && (*tmp != '\n') &&
2313 modest_text_utils_create_colored_signature (const gchar *signature)
2315 gchar *gray_color_markup = NULL, *retval;
2319 /* Get color from widgets */
2320 widget = (GtkWidget *) modest_window_mgr_get_current_top (modest_runtime_get_window_mgr ());
2321 if (widget && gtk_style_lookup_color (gtk_widget_get_style (widget), "SecondaryTextColor", &color))
2322 gray_color_markup = modest_text_utils_get_color_string (&color);
2324 retval = g_strdup_printf ("<br/>\n<font color=\"%s\">%s<br/>\n%s<br/>\n</font>",
2325 (gray_color_markup) ? gray_color_markup : "#babababababa",
2326 MODEST_TEXT_UTILS_SIGNATURE_MARKER,
2329 if (gray_color_markup)
2330 g_free (gray_color_markup);
2336 modest_text_utils_live_search_find (const gchar *haystack, const gchar *needles)
2338 gchar *haystack_fold;
2339 gchar *needles_fold;
2340 gchar **needle, **current;
2345 haystack_fold = g_utf8_casefold (haystack, -1);
2346 needles_fold = g_utf8_casefold (needles, -1);
2348 needle = g_strsplit (needles_fold, " ", -1);
2351 while (current && *current != NULL) {
2353 if (g_strstr_len (haystack_fold, -1, *current) != NULL) {
2362 g_strfreev (needle);
2363 g_free (needles_fold);
2364 g_free (haystack_fold);