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)) {
886 if (p[quote_len] == ' ') {
894 g_string_erase (l, 0, p - l->str);
898 append_quoted (GString * buf, const gchar *quote_symbol,
899 int indent, const GString * str,
905 indent = indent < 0 ? abs (indent) - 1 : indent;
906 quote_concat = g_strconcat (quote_symbol, " ", NULL);
907 for (i = 0; i <= indent; i++) {
908 g_string_append (buf, quote_concat);
910 g_free (quote_concat);
912 g_string_append_len (buf, str->str, cutpoint);
914 g_string_append (buf, str->str);
916 g_string_append (buf, "\n");
920 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
923 const gchar *pos, *last;
926 if (2*indent >= limit)
929 indent = indent < 0 ? abs (indent) - 1 : indent;
933 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
935 if ((index + 2 * indent > limit) && last) {
939 if (g_unichar_isspace (uni[index])) {
942 pos = g_utf8_next_char (pos);
950 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
955 if (last + 2 * indent < limit)
958 for (i = strlen (s); i > 0; i--) {
960 if (i + 2 * indent <= limit) {
971 get_breakpoint (const gchar * s, const gint indent, const gint limit)
974 if (g_utf8_validate (s, -1, NULL)) {
975 return get_breakpoint_utf8 (s, indent, limit);
976 } else { /* assume ASCII */
977 //g_warning("invalid UTF-8 in msg");
978 return get_breakpoint_ascii (s, indent, limit);
983 cite (const time_t sent_date, const gchar *from)
985 return g_strdup (_("mcen_ia_editor_original_message"));
989 quoted_attachments (GList *attachments)
992 GString *result = g_string_new ("");
993 for (node = attachments; node != NULL; node = g_list_next (node)) {
994 gchar *filename = (gchar *) node->data;
995 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
998 return g_string_free (result, FALSE);
1003 modest_text_utils_quote_body (GString *output, const gchar *text,
1004 const gchar *quote_symbol,
1010 gint indent = 0, breakpoint, rem_indent = 0;
1011 GString *l, *remaining;
1012 gchar *forced_wrap_append;
1016 remaining = g_string_new ("");
1017 forced_wrap_append = NULL;
1020 if (forced_wrap_append) {
1021 gint next_line_indent;
1022 gint l_len_with_indent;
1024 g_string_erase (remaining, 0, -1);
1025 next_line_indent = get_indent_level (iter);
1026 l = get_next_line (text, len, iter);
1027 l_len_with_indent = l->len;
1028 unquote_line (l, quote_symbol);
1029 if ((l->str && l->str[0] == '\0') || (next_line_indent != indent)) {
1030 g_string_free (l, TRUE);
1031 l = g_string_new (forced_wrap_append);
1033 gunichar first_in_l;
1034 iter = iter + l_len_with_indent + 1;
1035 first_in_l = g_utf8_get_char_validated (l->str, l->len);
1036 if (!g_unichar_isspace (first_in_l))
1037 l = g_string_prepend (l, " ");
1038 l = g_string_prepend (l, forced_wrap_append);
1040 g_free (forced_wrap_append);
1041 forced_wrap_append = NULL;
1043 l = get_next_line (text, len, iter);
1044 iter = iter + l->len + 1;
1045 indent = get_indent_level (l->str);
1046 unquote_line (l, quote_symbol);
1049 if (remaining->len) {
1050 if (l->len && indent == rem_indent) {
1051 g_string_prepend (l, " ");
1052 g_string_prepend (l, remaining->str);
1055 gunichar remaining_first;
1057 get_breakpoint (remaining->str,
1060 if (breakpoint < remaining->len) {
1061 g_free (forced_wrap_append);
1062 forced_wrap_append = g_strdup (remaining->str + breakpoint);
1064 if (!forced_wrap_append)
1065 append_quoted (output, quote_symbol, rem_indent,
1066 remaining, breakpoint);
1068 g_string_erase (remaining, 0,
1070 remaining_first = g_utf8_get_char_validated (remaining->str, remaining->len);
1071 if (remaining_first != ((gunichar) -1)) {
1072 if (g_unichar_isspace (remaining_first)) {
1073 g_string_erase (remaining, 0, g_utf8_next_char (remaining->str) - remaining->str);
1076 } while (remaining->len);
1079 g_string_free (remaining, TRUE);
1080 breakpoint = get_breakpoint (l->str, indent, limit);
1081 remaining = g_string_new (l->str + breakpoint);
1082 if (remaining->str[0] == ' ') {
1083 g_string_erase (remaining, 0, 1);
1085 rem_indent = indent;
1086 if (remaining->len > 0) {
1087 g_free (forced_wrap_append);
1088 forced_wrap_append = g_strdup (remaining->str);
1090 append_quoted (output, quote_symbol, indent, l, breakpoint);
1091 g_string_free (l, TRUE);
1092 } while ((iter < text + len) || (remaining->str[0]) || forced_wrap_append);
1098 modest_text_utils_quote_plain_text (const gchar *text,
1100 const gchar *signature,
1105 gchar *attachments_string = NULL;
1107 q = g_string_new ("");
1109 if (signature != NULL) {
1110 g_string_append_printf (q, "\n%s\n", MODEST_TEXT_UTILS_SIGNATURE_MARKER);
1111 q = g_string_append (q, signature);
1114 q = g_string_append (q, "\n");
1115 q = g_string_append (q, cite);
1116 q = g_string_append_c (q, '\n');
1118 q = modest_text_utils_quote_body (q, text, ">", limit);
1120 attachments_string = quoted_attachments (attachments);
1121 q = g_string_append (q, attachments_string);
1122 g_free (attachments_string);
1124 return g_string_free (q, FALSE);
1128 quote_html_add_to_gstring (GString *string,
1131 if (text && strcmp (text, "")) {
1132 gchar *html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
1133 g_string_append_printf (string, "%s<br/>", html_text);
1139 modest_text_utils_quote_html (const gchar *text,
1141 const gchar *signature,
1145 GString *result_string;
1149 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
1153 if (text || cite || signature) {
1154 GString *quoted_text;
1155 g_string_append (result_string, "<pre>\n");
1157 gchar *colored_signature = modest_text_utils_create_colored_signature (signature);
1158 g_string_append_printf (result_string, "%s<br/>", colored_signature);
1159 g_free (colored_signature);
1161 quote_html_add_to_gstring (result_string, cite);
1162 quoted_text = g_string_new ("");
1163 quoted_text = modest_text_utils_quote_body (quoted_text, (text) ? text : "", ">", limit);
1164 quote_html_add_to_gstring (result_string, quoted_text->str);
1165 g_string_free (quoted_text, TRUE);
1167 gchar *attachments_string = quoted_attachments (attachments);
1168 quote_html_add_to_gstring (result_string, attachments_string);
1169 g_free (attachments_string);
1171 g_string_append (result_string, "</pre>");
1173 g_string_append (result_string, "</body>");
1174 g_string_append (result_string, "</html>");
1176 return g_string_free (result_string, FALSE);
1180 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
1182 return match2->offset - match1->offset;
1185 static gint url_matches_block = 0;
1186 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
1187 static GMutex *url_patterns_mutex = NULL;
1194 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1195 for (i = 0; i != pattern_num; ++i) {
1196 patterns[i].preg = g_slice_new0 (regex_t);
1198 /* this should not happen */
1199 if (regcomp (patterns[i].preg, patterns[i].regex,
1200 REG_ICASE|REG_EXTENDED|REG_NEWLINE) != 0) {
1201 g_warning ("%s: error in regexp:\n%s\n", __FUNCTION__, patterns[i].regex);
1212 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1213 for (i = 0; i != pattern_num; ++i) {
1214 regfree (patterns[i].preg);
1215 g_slice_free (regex_t, patterns[i].preg);
1216 } /* don't free patterns itself -- it's static */
1220 modest_text_utils_hyperlinkify_begin (void)
1223 if (url_patterns_mutex == NULL) {
1224 url_patterns_mutex = g_mutex_new ();
1226 g_mutex_lock (url_patterns_mutex);
1227 if (url_matches_block == 0)
1228 compile_patterns ();
1229 url_matches_block ++;
1230 g_mutex_unlock (url_patterns_mutex);
1234 modest_text_utils_hyperlinkify_end (void)
1236 g_mutex_lock (url_patterns_mutex);
1237 url_matches_block--;
1238 if (url_matches_block <= 0)
1240 g_mutex_unlock (url_patterns_mutex);
1245 get_url_matches (GString *txt, gint offset)
1248 guint rv, i, tmp_offset = 0;
1249 GSList *match_list = NULL;
1251 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1253 /* initalize the regexps */
1254 modest_text_utils_hyperlinkify_begin ();
1256 /* find all the matches */
1257 for (i = 0; i != pattern_num; ++i) {
1258 tmp_offset = offset;
1261 gboolean is_submatch;
1264 if ((rv = regexec (patterns[i].preg, txt->str + tmp_offset, 1, &rm, 0)) != 0) {
1265 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
1266 break; /* try next regexp */
1271 is_submatch = FALSE;
1272 /* check old matches to see if this has already been matched */
1273 cursor = match_list;
1274 while (cursor && !is_submatch) {
1275 const url_match_t *old_match =
1276 (const url_match_t *) cursor->data;
1277 guint new_offset = tmp_offset + rm.rm_so;
1278 is_submatch = (new_offset > old_match->offset &&
1279 new_offset < old_match->offset + old_match->len);
1280 cursor = g_slist_next (cursor);
1284 /* make a list of our matches (<offset, len, prefix> tupels)*/
1285 match = g_slice_new (url_match_t);
1286 match->offset = tmp_offset + rm.rm_so;
1287 match->len = rm.rm_eo - rm.rm_so;
1288 match->prefix = patterns[i].prefix;
1289 match_list = g_slist_prepend (match_list, match);
1291 tmp_offset += rm.rm_eo;
1295 modest_text_utils_hyperlinkify_end ();
1297 /* now sort the list, so the matches are in reverse order of occurence.
1298 * that way, we can do the replacements starting from the end, so we don't need
1299 * to recalculate the offsets
1301 match_list = g_slist_sort (match_list,
1302 (GCompareFunc)cmp_offsets_reverse);
1308 /* replace all occurences of needle in haystack with repl*/
1310 replace_string (const gchar *haystack, const gchar *needle, gchar repl)
1312 gchar *str, *cursor;
1314 if (!haystack || !needle || strlen(needle) == 0)
1315 return haystack ? g_strdup(haystack) : NULL;
1317 str = g_strdup (haystack);
1319 for (cursor = str; cursor && *cursor; ++cursor) {
1320 if (g_str_has_prefix (cursor, needle)) {
1322 memmove (cursor + 1,
1323 cursor + strlen (needle),
1324 strlen (cursor + strlen (needle)) + 1);
1332 hyperlinkify_plain_text (GString *txt, gint offset)
1335 GSList *match_list = get_url_matches (txt, offset);
1337 /* we will work backwards, so the offsets stay valid */
1338 for (cursor = match_list; cursor; cursor = cursor->next) {
1340 url_match_t *match = (url_match_t*) cursor->data;
1341 gchar *url = g_strndup (txt->str + match->offset, match->len);
1342 gchar *repl = NULL; /* replacement */
1344 /* the string still contains $(MARK_AMP_URI_STR)"amp;" for each
1345 * '&' in the original, because of the text->html conversion.
1346 * in the href-URL (and only there), we must convert that back to
1349 gchar *href_url = replace_string (url, MARK_AMP_URI_STR "amp;", '&');
1351 /* the prefix is NULL: use the one that is already there */
1352 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1353 match->prefix ? match->prefix : EMPTY_STRING,
1356 /* replace the old thing with our hyperlink
1357 * replacement thing */
1358 g_string_erase (txt, match->offset, match->len);
1359 g_string_insert (txt, match->offset, repl);
1365 g_slice_free (url_match_t, match);
1368 g_slist_free (match_list);
1372 modest_text_utils_hyperlinkify (GString *string_buffer)
1377 after_body = strstr (string_buffer->str, "<body>");
1378 if (after_body != NULL)
1379 offset = after_body - string_buffer->str;
1380 hyperlinkify_plain_text (string_buffer, offset);
1384 /* for optimization reasons, we change the string in-place */
1386 modest_text_utils_get_display_address (gchar *address)
1390 g_return_if_fail (address);
1395 /* should not be needed, and otherwise, we probably won't screw up the address
1396 * more than it already is :)
1397 * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1400 /* remove leading whitespace */
1401 if (address[0] == ' ')
1402 g_strchug (address);
1404 for (i = 0; address[i]; ++i) {
1405 if (address[i] == '<') {
1406 if (G_UNLIKELY(i == 0)) {
1407 break; /* there's nothing else, leave it */
1409 address[i] = '\0'; /* terminate the string here */
1415 g_strchomp (address);
1420 modest_text_utils_get_display_addresses (const gchar *recipients)
1423 GSList *recipient_list;
1426 recipient_list = modest_text_utils_split_addresses_list (recipients);
1427 if (recipient_list) {
1428 GString *add_string = g_string_sized_new (strlen (recipients));
1429 GSList *iter = recipient_list;
1430 gboolean first = TRUE;
1433 /* Strings are changed in place */
1434 modest_text_utils_get_display_address ((gchar *) iter->data);
1435 if (G_UNLIKELY (first)) {
1436 g_string_append_printf (add_string, "%s", (gchar *) iter->data);
1439 g_string_append_printf (add_string, ", %s", (gchar *) iter->data);
1441 iter = g_slist_next (iter);
1443 g_slist_foreach (recipient_list, (GFunc) g_free, NULL);
1444 g_slist_free (recipient_list);
1445 addresses = g_string_free (add_string, FALSE);
1453 modest_text_utils_get_email_address (const gchar *full_address)
1455 const gchar *left, *right;
1457 g_return_val_if_fail (full_address, NULL);
1462 g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1464 left = g_strrstr_len (full_address, strlen(full_address), "<");
1466 return g_strdup (full_address);
1468 right = g_strstr_len (left, strlen(left), ">");
1470 return g_strdup (full_address);
1472 return g_strndup (left + 1, right - left - 1);
1476 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1478 gint prefix_len = 0;
1480 g_return_val_if_fail (sub, 0);
1485 /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1486 if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1488 else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1495 /* skip over a [...] block */
1496 if (sub[prefix_len] == '[') {
1497 int c = prefix_len + 1;
1498 while (sub[c] && sub[c] != ']')
1501 return 0; /* no end to the ']' found */
1506 /* did we find the ':' ? */
1507 if (sub[prefix_len] == ':') {
1509 if (sub[prefix_len] == ' ')
1511 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1512 /* g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1520 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1523 /* work even when s1 and/or s2 == NULL */
1524 if (G_UNLIKELY(s1 == s2))
1526 if (G_UNLIKELY(!s1))
1528 if (G_UNLIKELY(!s2))
1531 /* if it's not case sensitive */
1534 /* optimization: shortcut if first char is ascii */
1535 if (((s1[0] & 0x80)== 0) && ((s2[0] & 0x80) == 0) &&
1537 return s1[0] - s2[0];
1539 return g_utf8_collate (s1, s2);
1545 /* optimization: shortcut if first char is ascii */
1546 if (((s1[0] & 0x80) == 0) && ((s2[0] & 0x80) == 0) &&
1547 (tolower(s1[0]) != tolower (s2[0])))
1548 return tolower(s1[0]) - tolower(s2[0]);
1550 n1 = g_utf8_strdown (s1, -1);
1551 n2 = g_utf8_strdown (s2, -1);
1553 result = g_utf8_collate (n1, n2);
1564 modest_text_utils_get_display_date (time_t date)
1566 #define DATE_BUF_SIZE 64
1567 static gchar date_buf[DATE_BUF_SIZE];
1569 /* calculate the # of days since epoch for
1570 * for today and for the date provided
1571 * based on idea from pvanhoof */
1572 int day = time(NULL) / (24 * 60 * 60);
1573 int date_day = date / (24 * 60 * 60);
1575 /* if it's today, show the time, if it's not today, show the date instead */
1577 /* TODO: take into account the system config for 24/12h */
1578 #ifdef MODEST_TOOLKIT_HILDON2
1579 if (day == date_day) /* is the date today? */
1580 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_24h_time"), date);
1582 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_date"), date);
1584 if (day == date_day) /* is the date today? */
1585 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%X", date);
1587 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, "%x", date);
1590 return date_buf; /* this is a static buffer, don't free! */
1596 modest_text_utils_validate_folder_name (const gchar *folder_name)
1598 /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1599 * with some extras */
1603 const gchar **cursor = NULL;
1604 const gchar *forbidden_names[] = { /* windows does not like these */
1605 "CON", "PRN", "AUX", "NUL", ".", "..", "cur", "tmp", "new",
1606 NULL /* cur, tmp, new are reserved for Maildir */
1609 /* cannot be NULL */
1613 /* cannot be empty */
1614 len = strlen(folder_name);
1618 /* cannot start with a dot, vfat does not seem to like that */
1619 if (folder_name[0] == '.')
1622 /* cannot start or end with a space */
1623 if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1626 /* cannot contain a forbidden char */
1627 for (i = 0; i < len; i++)
1628 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1631 /* Cannot contain Windows port numbers. I'd like to use GRegex
1632 but it's still not available in Maemo. sergio */
1633 if (!g_ascii_strncasecmp (folder_name, "LPT", 3) ||
1634 !g_ascii_strncasecmp (folder_name, "COM", 3)) {
1638 /* We skip the first 3 characters for the
1640 val = strtol(folder_name+3, &endptr, 10);
1642 /* If the conversion to long succeeded then the string
1643 is not valid for us */
1644 if (*endptr == '\0')
1650 /* cannot contain a forbidden word */
1652 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1653 if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1658 return TRUE; /* it's valid! */
1664 modest_text_utils_validate_domain_name (const gchar *domain)
1666 gboolean valid = FALSE;
1668 const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1670 g_return_val_if_fail (domain, FALSE);
1675 memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1677 /* domain name: all alphanum or '-' or '.',
1678 * but beginning/ending in alphanum */
1679 if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1680 g_warning ("BUG: error in regexp");
1684 valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1693 modest_text_utils_validate_email_address (const gchar *email_address,
1694 const gchar **invalid_char_position)
1697 const gchar *c = NULL, *domain = NULL;
1698 static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1700 if (invalid_char_position)
1701 *invalid_char_position = NULL;
1703 g_return_val_if_fail (email_address, FALSE);
1705 /* check that the email adress contains exactly one @ */
1706 if (!strstr(email_address, "@") ||
1707 (strstr(email_address, "@") != g_strrstr(email_address, "@")))
1710 /* first we validate the name portion (name@domain) */
1711 for (c = email_address; *c; c++) {
1713 (c == email_address ||
1715 *(c - 1) == '\"')) {
1719 if (*c == '\\' && (*++c == ' '))
1721 if (*c <= ' ' || *c >= 127)
1734 if (*c <= ' ' || *c >= 127)
1736 if (strchr(rfc822_specials, *c)) {
1737 if (invalid_char_position)
1738 *invalid_char_position = c;
1742 if (c == email_address || *(c - 1) == '.')
1745 /* next we validate the domain portion (name@domain) */
1746 if (!*(domain = ++c))
1750 if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0')
1754 if (*c <= ' ' || *c >= 127)
1756 if (strchr(rfc822_specials, *c)) {
1757 if (invalid_char_position)
1758 *invalid_char_position = c;
1763 return (count >= 1) ? TRUE : FALSE;
1767 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1769 gchar *stripped, *current;
1771 gboolean has_error = FALSE;
1773 if (invalid_char_position)
1774 *invalid_char_position = NULL;
1776 g_return_val_if_fail (recipient, FALSE);
1778 if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1781 stripped = g_strdup (recipient);
1782 stripped = g_strstrip (stripped);
1785 if (*current == '\0') {
1791 if (*current == '\"') {
1792 gchar *last_quote = NULL;
1793 current = g_utf8_next_char (current);
1795 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1796 if (*current == '\\') {
1797 /* TODO: This causes a warning, which breaks the build,
1798 * because a gchar cannot be < 0.
1800 if (current[1] <0) {
1805 } else if (*current == '\"') {
1807 current = g_utf8_next_char (current);
1808 last_quote = current;
1812 current = g_utf8_next_char (last_quote);
1815 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1816 if (*current == '<') {
1828 right_part = g_strdup (current);
1830 right_part = g_strstrip (right_part);
1832 if (g_str_has_suffix (right_part, ",") || g_str_has_suffix (right_part, ";"))
1833 right_part [(strlen (right_part) - 1)] = '\0';
1835 if (g_str_has_prefix (right_part, "<") &&
1836 g_str_has_suffix (right_part, ">")) {
1840 address = g_strndup (right_part+1, strlen (right_part) - 2);
1841 g_free (right_part);
1842 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1846 g_free (right_part);
1853 modest_text_utils_get_display_size (guint64 size)
1855 const guint KB=1024;
1856 const guint MB=1024 * KB;
1857 const guint GB=1024 * MB;
1860 return g_strdup_printf (_FM("sfil_li_size_kb"), (int) 0);
1861 if (0 <= size && size < KB)
1862 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), (int) 1);
1863 else if (KB <= size && size < 100 * KB)
1864 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), (int) size / KB);
1865 else if (100*KB <= size && size < MB)
1866 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (int) size / KB);
1867 else if (MB <= size && size < 10*MB)
1868 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1869 else if (10*MB <= size && size < GB)
1870 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), (float) size / MB);
1872 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB);
1876 get_email_from_address (const gchar * address)
1878 gchar *left_limit, *right_limit;
1880 left_limit = strstr (address, "<");
1881 right_limit = g_strrstr (address, ">");
1883 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1884 return g_strdup (address);
1886 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1890 modest_text_utils_get_color_string (GdkColor *color)
1892 g_return_val_if_fail (color, NULL);
1894 return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1895 (color->red >> 12) & 0xf, (color->red >> 8) & 0xf,
1896 (color->red >> 4) & 0xf, (color->red) & 0xf,
1897 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1898 (color->green >> 4) & 0xf, (color->green) & 0xf,
1899 (color->blue >> 12) & 0xf, (color->blue >> 8) & 0xf,
1900 (color->blue >> 4) & 0xf, (color->blue) & 0xf);
1904 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1906 GtkTextIter start, end;
1907 gchar *slice, *current;
1908 GString *result = g_string_new ("");
1910 g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1912 gtk_text_buffer_get_start_iter (buffer, &start);
1913 gtk_text_buffer_get_end_iter (buffer, &end);
1915 slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1918 while (current && current != '\0') {
1919 if (g_utf8_get_char (current) == 0xFFFC) {
1920 result = g_string_append_c (result, ' ');
1921 current = g_utf8_next_char (current);
1923 gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1925 result = g_string_append (result, current);
1927 result = g_string_append_len (result, current, next - current);
1934 return g_string_free (result, FALSE);
1939 modest_text_utils_is_forbidden_char (const gchar character,
1940 ModestTextUtilsForbiddenCharType type)
1943 const gchar *forbidden_chars = NULL;
1945 /* We need to get the length in the switch because the
1946 compiler needs to know the size at compile time */
1948 case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1949 forbidden_chars = account_title_forbidden_chars;
1950 len = G_N_ELEMENTS (account_title_forbidden_chars);
1952 case FOLDER_NAME_FORBIDDEN_CHARS:
1953 forbidden_chars = folder_name_forbidden_chars;
1954 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1956 case USER_NAME_FORBIDDEN_NAMES:
1957 forbidden_chars = user_name_forbidden_chars;
1958 len = G_N_ELEMENTS (user_name_forbidden_chars);
1961 g_return_val_if_reached (TRUE);
1964 for (i = 0; i < len ; i++)
1965 if (forbidden_chars[i] == character)
1968 return FALSE; /* it's valid! */
1972 modest_text_utils_label_get_selection (GtkLabel *label)
1977 if (gtk_label_get_selection_bounds (GTK_LABEL (label), &start, &end)) {
1978 const gchar *start_offset;
1979 const gchar *end_offset;
1980 start_offset = gtk_label_get_text (GTK_LABEL (label));
1981 start_offset = g_utf8_offset_to_pointer (start_offset, start);
1982 end_offset = gtk_label_get_text (GTK_LABEL (label));
1983 end_offset = g_utf8_offset_to_pointer (end_offset, end);
1984 selection = g_strndup (start_offset, end_offset - start_offset);
1987 return g_strdup ("");
1992 _forward_search_image_char (gunichar ch,
1995 return (ch == 0xFFFC);
1999 modest_text_utils_buffer_selection_is_valid (GtkTextBuffer *buffer)
2002 GtkTextIter start, end;
2004 g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2006 result = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (buffer));
2008 /* check there are no images in selection */
2010 gtk_text_buffer_get_selection_bounds (buffer, &start, &end);
2011 if (gtk_text_iter_get_char (&start)== 0xFFFC)
2014 gtk_text_iter_backward_char (&end);
2015 if (gtk_text_iter_forward_find_char (&start, _forward_search_image_char,
2026 remove_quotes (gchar **quotes)
2028 if (g_str_has_prefix (*quotes, "\"") && g_str_has_suffix (*quotes, "\"")) {
2030 result = g_strndup ((*quotes)+1, strlen (*quotes) - 2);
2037 remove_extra_spaces (gchar *string)
2042 while (start && start[0] != '\0') {
2043 if ((start[0] == ' ') && (start[1] == ' ')) {
2044 g_strchug (start+1);
2051 modest_text_utils_escape_mnemonics (const gchar *text)
2054 GString *result = NULL;
2059 result = g_string_new ("");
2060 for (p = text; *p != '\0'; p++) {
2062 result = g_string_append (result, "__");
2064 result = g_string_append_c (result, *p);
2067 return g_string_free (result, FALSE);
2071 modest_text_utils_simplify_recipients (const gchar *recipients)
2073 GSList *addresses, *node;
2075 gboolean is_first = TRUE;
2077 if (recipients == NULL)
2078 return g_strdup ("");
2080 addresses = modest_text_utils_split_addresses_list (recipients);
2081 result = g_string_new ("");
2083 for (node = addresses; node != NULL; node = g_slist_next (node)) {
2084 const gchar *address = (const gchar *) node->data;
2085 gchar *left_limit, *right_limit;
2087 left_limit = strstr (address, "<");
2088 right_limit = g_strrstr (address, ">");
2093 result = g_string_append (result, ", ");
2095 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit)) {
2096 result = g_string_append (result, address);
2100 name_side = g_strndup (address, left_limit - address);
2101 name_side = g_strstrip (name_side);
2102 remove_quotes (&name_side);
2103 email_side = get_email_from_address (address);
2104 if (name_side && email_side && !strcmp (name_side, email_side)) {
2105 result = g_string_append (result, email_side);
2107 result = g_string_append (result, address);
2110 g_free (email_side);
2114 g_slist_foreach (addresses, (GFunc)g_free, NULL);
2115 g_slist_free (addresses);
2117 return g_string_free (result, FALSE);
2122 modest_text_utils_remove_duplicate_addresses_list (GSList *address_list)
2124 GSList *new_list, *iter;
2127 g_return_val_if_fail (address_list, NULL);
2129 table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2131 new_list = address_list;
2132 iter = address_list;
2134 const gchar* address = (const gchar*)iter->data;
2136 /* We need only the email to just compare it and not
2137 the full address which would make "a <a@a.com>"
2138 different from "a@a.com" */
2139 const gchar *email = get_email_from_address (address);
2141 /* ignore the address if already seen */
2142 if (g_hash_table_lookup (table, email) == 0) {
2143 g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
2144 iter = g_slist_next (iter);
2146 GSList *tmp = g_slist_next (iter);
2147 new_list = g_slist_delete_link (new_list, iter);
2152 g_hash_table_unref (table);
2158 modest_text_utils_get_secure_header (const gchar *value,
2159 const gchar *header)
2161 const gint max_len = 16384;
2162 gchar *new_value = NULL;
2163 gchar *needle = g_strrstr (value, header);
2165 if (needle && value != needle)
2166 new_value = g_strdup (needle + strlen (header));
2169 new_value = g_strdup (value);
2171 /* Do a max length check to prevent DoS attacks caused by huge
2172 malformed headers */
2173 if (g_utf8_validate (new_value, -1, NULL)) {
2174 if (g_utf8_strlen (new_value, -1) > max_len) {
2175 gchar *tmp = g_malloc0 (max_len * 4);
2176 g_utf8_strncpy (tmp, (const gchar *) new_value, max_len);
2181 if (strlen (new_value) > max_len) {
2182 gchar *tmp = g_malloc0 (max_len);
2183 strncpy (new_value, tmp, max_len);
2193 is_quoted (const char *start, const gchar *end)
2197 c = (gchar *) start;
2199 c = g_utf8_next_char (c);
2201 if (*c == '\0' || *c != '\"')
2205 while (*c == ' ' && c != start)
2206 c = g_utf8_prev_char (c);
2208 if (c == start || *c != '\"')
2216 quote_name_part (GString **str, gchar **cur, gchar **start)
2219 gint str_len = *cur - *start;
2221 while (**start == ' ') {
2222 *start = g_utf8_next_char (*start);
2226 blank = g_utf8_strrchr (*start, str_len, g_utf8_get_char (" "));
2227 if (blank && (blank != *start)) {
2228 if (is_quoted (*start, blank - 1)) {
2229 *str = g_string_append_len (*str, *start, str_len);
2230 *str = g_string_append (*str, ";");
2231 *start = g_utf8_next_char (*cur);
2233 *str = g_string_append_c (*str, '"');
2234 *str = g_string_append_len (*str, *start, (blank - *start));
2235 *str = g_string_append_c (*str, '"');
2236 *str = g_string_append_len (*str, blank, (*cur - blank));
2237 *str = g_string_append (*str, ";");
2238 *start = g_utf8_next_char (*cur);
2241 *str = g_string_append_len (*str, *start, str_len);
2242 *str = g_string_append (*str, ";");
2243 *start = g_utf8_next_char (*cur);
2248 modest_text_utils_quote_names (const gchar *recipients)
2253 str = g_string_new ("");
2254 start = (gchar*) recipients;
2255 cur = (gchar*) recipients;
2257 for (cur = start; *cur != '\0'; cur = g_utf8_next_char (cur)) {
2258 if (*cur == ',' || *cur == ';') {
2259 if (!g_utf8_strchr (start, (cur - start + 1), g_utf8_get_char ("@")))
2261 quote_name_part (&str, &cur, &start);
2265 quote_name_part (&str, &cur, &start);
2267 return g_string_free (str, FALSE);
2270 /* Returns TRUE if there is no recipients in the text buffer. Note
2271 that strings like " ; , " contain only separators and thus no
2274 modest_text_utils_no_recipient (GtkTextBuffer *buffer)
2276 gboolean retval = TRUE;
2278 GtkTextIter start, end;
2280 if (gtk_text_buffer_get_char_count (buffer) == 0)
2283 gtk_text_buffer_get_start_iter (buffer, &start);
2284 gtk_text_buffer_get_end_iter (buffer, &end);
2286 text = g_strstrip (gtk_text_buffer_get_text (buffer, &start, &end, FALSE));
2287 if (!g_strcmp0 (text, ""))
2291 while (tmp && *tmp != '\0') {
2292 if ((*tmp != ',') && (*tmp != ';') &&
2293 (*tmp != '\r') && (*tmp != '\n') &&
2307 modest_text_utils_create_colored_signature (const gchar *signature)
2309 gchar *gray_color_markup = NULL, *retval;
2313 /* Get color from widgets */
2314 widget = (GtkWidget *) modest_window_mgr_get_current_top (modest_runtime_get_window_mgr ());
2315 if (widget && gtk_style_lookup_color (gtk_widget_get_style (widget), "SecondaryTextColor", &color))
2316 gray_color_markup = modest_text_utils_get_color_string (&color);
2318 retval = g_strdup_printf ("<br/>\n<font color=\"%s\">%s<br/>\n%s<br/>\n</font>",
2319 (gray_color_markup) ? gray_color_markup : "#babababababa",
2320 MODEST_TEXT_UTILS_SIGNATURE_MARKER,
2323 if (gray_color_markup)
2324 g_free (gray_color_markup);
2330 modest_text_utils_live_search_find (const gchar *haystack, const gchar *needles)
2332 gchar *haystack_fold;
2333 gchar *needles_fold;
2334 gchar **needle, **current;
2339 haystack_fold = g_utf8_casefold (haystack, -1);
2340 needles_fold = g_utf8_casefold (needles, -1);
2342 needle = g_strsplit (needles_fold, " ", -1);
2345 while (current && *current != NULL) {
2347 if (g_strstr_len (haystack_fold, -1, *current) != NULL) {
2356 g_strfreev (needle);
2357 g_free (needles_fold);
2358 g_free (haystack_fold);