1 /* Copyright (c) 2006, Nokia Corporation
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of the Nokia Corporation nor the names of its
14 * contributors may be used to endorse or promote products derived from
15 * this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #endif /*_GNU_SOURCE*/
35 #include <string.h> /* for strcasestr */
40 #include <glib/gi18n.h>
42 #include <modest-tny-platform-factory.h>
43 #include <modest-text-utils.h>
44 #include <modest-runtime.h>
49 #endif /*HAVE_CONFIG_H */
52 #define FORWARD_STRING _("mcen_ia_editor_original_message")
53 #define FROM_STRING _("mail_va_from")
54 #define SENT_STRING _("mcen_fi_message_properties_sent")
55 #define TO_STRING _("mail_va_to")
56 #define SUBJECT_STRING _("mail_va_subject")
57 #define EMPTY_STRING ""
60 * do the hyperlinkification only for texts < 50 Kb,
61 * as it's quite slow. Without this, e.g. mail with
62 * an uuencoded part (which is not recognized as attachment,
65 #define HYPERLINKIFY_MAX_LENGTH (1024*50)
68 * we need these regexps to find URLs in plain text e-mails
70 typedef struct _url_match_pattern_t url_match_pattern_t;
71 struct _url_match_pattern_t {
77 typedef struct _url_match_t url_match_t;
84 #define MAIL_VIEWER_URL_MATCH_PATTERNS { \
85 { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
87 { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
89 { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
91 { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
93 { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+", \
95 { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
99 const gchar account_title_forbidden_chars[] = {
100 '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
102 const gchar folder_name_forbidden_chars[] = {
103 '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$'
105 const gchar user_name_forbidden_chars[] = {
108 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
109 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
110 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
113 static gchar* cite (const time_t sent_date, const gchar *from);
114 static void hyperlinkify_plain_text (GString *txt);
115 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
116 static GSList* get_url_matches (GString *txt);
118 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
119 static int get_indent_level (const char *l);
120 static void unquote_line (GString * l);
121 static void append_quoted (GString * buf, const int indent, const GString * str,
123 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
124 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
125 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
127 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
129 const gchar *signature,
133 static gchar* modest_text_utils_quote_html (const gchar *text,
135 const gchar *signature,
138 static gchar* get_email_from_address (const gchar *address);
141 /* ******************************************************************* */
142 /* ************************* PUBLIC FUNCTIONS ************************ */
143 /* ******************************************************************* */
146 modest_text_utils_quote (const gchar *text,
147 const gchar *content_type,
148 const gchar *signature,
150 const time_t sent_date,
154 gchar *retval, *cited;
156 g_return_val_if_fail (text, NULL);
157 g_return_val_if_fail (content_type, NULL);
159 cited = cite (sent_date, from);
161 if (content_type && strcmp (content_type, "text/html") == 0)
162 /* TODO: extract the <body> of the HTML and pass it to
164 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
166 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
175 modest_text_utils_cite (const gchar *text,
176 const gchar *content_type,
177 const gchar *signature,
184 g_return_val_if_fail (text, NULL);
185 g_return_val_if_fail (content_type, NULL);
188 retval = g_strdup ("");
189 else if (strcmp(content_type, "text/html") == 0) {
190 tmp_sig = g_strconcat ("\n", signature, NULL);
191 retval = modest_text_utils_convert_to_html_body(tmp_sig, -1, TRUE);
194 retval = g_strconcat (text, "\n", signature, NULL);
201 forward_cite (const gchar *from,
204 const gchar *subject)
206 return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n",
208 FROM_STRING, (from)?from:"",
210 TO_STRING, (to)?to:"",
211 SUBJECT_STRING, (subject)?subject:"");
215 modest_text_utils_inline (const gchar *text,
216 const gchar *content_type,
217 const gchar *signature,
221 const gchar *subject)
227 g_return_val_if_fail (text, NULL);
228 g_return_val_if_fail (content_type, NULL);
230 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
232 cited = forward_cite (from, sent_str, to, subject);
234 if (content_type && strcmp (content_type, "text/html") == 0)
235 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
237 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
243 /* just to prevent warnings:
244 * warning: `%x' yields only last 2 digits of year in some locales
247 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
251 /* does not work on old maemo glib:
252 * g_date_set_time_t (&date, timet);
254 localtime_r (&timet, &tm);
255 return strftime(s, max, fmt, &tm);
259 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
263 g_return_val_if_fail (prefix, NULL);
265 if (!subject || subject[0] == '\0')
266 subject = _("mail_va_no_subject");
268 tmp = g_strchug (g_strdup (subject));
270 if (!strncmp (tmp, prefix, strlen (prefix))) {
274 return g_strdup_printf ("%s %s", prefix, subject);
279 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
281 gchar *dup, *token, *ptr, *result;
282 GString *filtered_emails;
283 gchar *email_address;
285 g_return_val_if_fail (address_list, NULL);
288 return g_strdup (address_list);
290 email_address = get_email_from_address (address);
292 /* search for substring */
293 if (!strstr ((const char *) address_list, (const char *) email_address)) {
294 g_free (email_address);
295 return g_strdup (address_list);
298 dup = g_strdup (address_list);
299 filtered_emails = g_string_new (NULL);
301 token = strtok_r (dup, ",", &ptr);
303 while (token != NULL) {
304 /* Add to list if not found */
305 if (!strstr ((const char *) token, (const char *) email_address)) {
306 if (filtered_emails->len == 0)
307 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
309 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
311 token = strtok_r (NULL, ",", &ptr);
313 result = filtered_emails->str;
316 g_free (email_address);
318 g_string_free (filtered_emails, FALSE);
324 modest_text_utils_convert_buffer_to_html (GString *html, const gchar *data, gssize n)
327 gboolean space_seen = FALSE;
328 guint break_dist = 0; /* distance since last break point */
333 /* replace with special html chars where needed*/
334 for (i = 0; i != n; ++i) {
337 if (space_seen && kar != ' ') {
338 g_string_append_c (html, ' ');
342 /* we artificially insert a breakpoint (newline)
343 * after 256, to make sure our lines are not so long
344 * they will DOS the regexping later
346 if (++break_dist == 256) {
347 g_string_append_c (html, '\n');
352 case 0: break; /* ignore embedded \0s */
353 case '<' : g_string_append (html, "<"); break;
354 case '>' : g_string_append (html, ">"); break;
355 case '&' : g_string_append (html, "&"); break;
356 case '"' : g_string_append (html, """); break;
358 /* don't convert ' --> wpeditor will try to re-convert it... */
359 //case '\'' : g_string_append (html, "'"); break;
360 case '\n' : g_string_append (html, "<br>\n"); break_dist= 0; break;
361 case '\t' : g_string_append (html, " "); break_dist=0; break; /* note the space at the end*/
364 if (space_seen) { /* second space in a row */
365 g_string_append (html, " ");
371 g_string_append_c (html, kar);
377 modest_text_utils_convert_to_html (const gchar *data)
386 html = g_string_sized_new (1.5 * len); /* just a guess... */
388 g_string_append_printf (html,
390 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
394 modest_text_utils_convert_buffer_to_html (html, data, -1);
396 g_string_append (html, "</body></html>");
398 if (len <= HYPERLINKIFY_MAX_LENGTH)
399 hyperlinkify_plain_text (html);
401 return g_string_free (html, FALSE);
405 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
414 html = g_string_sized_new (1.5 * n); /* just a guess... */
416 modest_text_utils_convert_buffer_to_html (html, data, n);
418 if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
419 hyperlinkify_plain_text (html);
421 return g_string_free (html, FALSE);
425 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
427 gchar *current, *start, *last_blank;
428 gint start_offset = 0, current_offset = 0;
430 g_return_if_fail (start_indexes != NULL);
431 g_return_if_fail (end_indexes != NULL);
433 start = (gchar *) addresses;
437 while (*current != '\0') {
438 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
439 start = g_utf8_next_char (start);
441 last_blank = current;
442 } else if ((*current == ',')||(*current == ';')) {
443 gint *start_index, *end_index;
444 start_index = g_new0(gint, 1);
445 end_index = g_new0(gint, 1);
446 *start_index = start_offset;
447 *end_index = current_offset;
448 *start_indexes = g_slist_prepend (*start_indexes, start_index);
449 *end_indexes = g_slist_prepend (*end_indexes, end_index);
450 start = g_utf8_next_char (current);
451 start_offset = current_offset + 1;
453 } else if (*current == '"') {
454 current = g_utf8_next_char (current);
456 while ((*current != '"')&&(*current != '\0')) {
457 current = g_utf8_next_char (current);
462 current = g_utf8_next_char (current);
466 if (start != current) {
467 gint *start_index, *end_index;
468 start_index = g_new0(gint, 1);
469 end_index = g_new0(gint, 1);
470 *start_index = start_offset;
471 *end_index = current_offset;
472 *start_indexes = g_slist_prepend (*start_indexes, start_index);
473 *end_indexes = g_slist_prepend (*end_indexes, end_index);
476 *start_indexes = g_slist_reverse (*start_indexes);
477 *end_indexes = g_slist_reverse (*end_indexes);
483 modest_text_utils_split_addresses_list (const gchar *addresses)
485 gchar *current, *start, *last_blank;
486 GSList *result = NULL;
488 start = (gchar *) addresses;
492 while (*current != '\0') {
493 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
494 start = g_utf8_next_char (start);
495 last_blank = current;
496 } else if ((*current == ',')||(*current == ';')) {
497 gchar *new_address = NULL;
498 new_address = g_strndup (start, current - last_blank);
499 result = g_slist_prepend (result, new_address);
500 start = g_utf8_next_char (current);
502 } else if (*current == '\"') {
503 if (current == start) {
504 current = g_utf8_next_char (current);
505 start = g_utf8_next_char (start);
507 while ((*current != '\"')&&(*current != '\0'))
508 current = g_utf8_next_char (current);
511 current = g_utf8_next_char (current);
514 if (start != current) {
515 gchar *new_address = NULL;
516 new_address = g_strndup (start, current - last_blank);
517 result = g_slist_prepend (result, new_address);
520 result = g_slist_reverse (result);
526 modest_text_utils_address_range_at_position (const gchar *recipients_list,
531 gchar *current = NULL;
532 gint range_start = 0;
535 gboolean is_quoted = FALSE;
538 for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
539 gunichar c = g_utf8_get_char (current);
541 if ((c == ',') && (!is_quoted)) {
542 if (index < position) {
543 range_start = index + 1;
547 } else if (c == '\"') {
548 is_quoted = !is_quoted;
549 } else if ((c == ' ') &&(range_start == index)) {
557 *start = range_start;
563 /* ******************************************************************* */
564 /* ************************* UTILIY FUNCTIONS ************************ */
565 /* ******************************************************************* */
568 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
574 return g_string_new("");
582 gs = g_string_new_len (i0, iter - i0);
586 get_indent_level (const char *l)
603 /* if we hit the signature marker "-- ", we return -(indent + 1). This
604 * stops reformatting.
606 if (strcmp (l, "-- ") == 0) {
614 unquote_line (GString * l)
629 g_string_erase (l, 0, p - l->str);
633 append_quoted (GString * buf, int indent, const GString * str,
638 indent = indent < 0 ? abs (indent) - 1 : indent;
639 for (i = 0; i <= indent; i++) {
640 g_string_append (buf, "> ");
643 g_string_append_len (buf, str->str, cutpoint);
645 g_string_append (buf, str->str);
647 g_string_append (buf, "\n");
651 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
654 const gchar *pos, *last;
657 indent = indent < 0 ? abs (indent) - 1 : indent;
661 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
663 if ((index + 2 * indent > limit) && last) {
667 if (g_unichar_isspace (uni[index])) {
670 pos = g_utf8_next_char (pos);
678 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
683 if (last + 2 * indent < limit)
686 for (i = strlen (s); i > 0; i--) {
688 if (i + 2 * indent <= limit) {
699 get_breakpoint (const gchar * s, const gint indent, const gint limit)
702 if (g_utf8_validate (s, -1, NULL)) {
703 return get_breakpoint_utf8 (s, indent, limit);
704 } else { /* assume ASCII */
705 //g_warning("invalid UTF-8 in msg");
706 return get_breakpoint_ascii (s, indent, limit);
711 cite (const time_t sent_date, const gchar *from)
713 return g_strdup (_("mcen_ia_editor_original_message"));
717 quoted_attachments (GList *attachments)
720 GString *result = g_string_new ("");
721 for (node = attachments; node != NULL; node = g_list_next (node)) {
722 gchar *filename = (gchar *) node->data;
723 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
726 return g_string_free (result, FALSE);
731 modest_text_utils_quote_plain_text (const gchar *text,
733 const gchar *signature,
738 gint indent, breakpoint, rem_indent = 0;
739 GString *q, *l, *remaining;
741 gchar *attachments_string = NULL;
743 /* remaining will store the rest of the line if we have to break it */
744 q = g_string_new ("\n");
745 q = g_string_append (q, cite);
746 q = g_string_append_c (q, '\n');
747 remaining = g_string_new ("");
752 l = get_next_line (text, len, iter);
753 iter = iter + l->len + 1;
754 indent = get_indent_level (l->str);
757 if (remaining->len) {
758 if (l->len && indent == rem_indent) {
759 g_string_prepend (l, " ");
760 g_string_prepend (l, remaining->str);
764 get_breakpoint (remaining->str,
767 append_quoted (q, rem_indent,
768 remaining, breakpoint);
769 g_string_erase (remaining, 0,
771 if (remaining->str[0] == ' ') {
772 g_string_erase (remaining, 0,
775 } while (remaining->len);
778 g_string_free (remaining, TRUE);
779 breakpoint = get_breakpoint (l->str, indent, limit);
780 remaining = g_string_new (l->str + breakpoint);
781 if (remaining->str[0] == ' ') {
782 g_string_erase (remaining, 0, 1);
785 append_quoted (q, indent, l, breakpoint);
786 g_string_free (l, TRUE);
787 } while ((iter < text + len) || (remaining->str[0]));
789 attachments_string = quoted_attachments (attachments);
790 q = g_string_append (q, attachments_string);
791 g_free (attachments_string);
793 if (signature != NULL) {
794 q = g_string_append_c (q, '\n');
795 q = g_string_append (q, signature);
798 return g_string_free (q, FALSE);
802 modest_text_utils_quote_html (const gchar *text,
804 const gchar *signature,
808 gchar *result = NULL;
809 gchar *signature_result = NULL;
810 const gchar *format = \
811 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
815 "<pre>%s<br/>%s<br/>%s</pre>\n" \
818 gchar *attachments_string = NULL;
819 gchar *q_attachments_string = NULL;
820 gchar *q_cite = NULL;
821 gchar *html_text = NULL;
823 if (signature == NULL)
824 signature_result = g_strdup ("");
826 signature_result = modest_text_utils_convert_to_html_body (signature, -1, TRUE);
828 attachments_string = quoted_attachments (attachments);
829 q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string, -1, TRUE);
830 q_cite = modest_text_utils_convert_to_html_body (cite, -1, TRUE);
831 html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
832 result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
835 g_free (attachments_string);
836 g_free (q_attachments_string);
837 g_free (signature_result);
843 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
845 return match2->offset - match1->offset;
848 static gboolean url_matches_block = 0;
849 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
856 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
857 for (i = 0; i != pattern_num; ++i) {
858 patterns[i].preg = g_slice_new0 (regex_t);
860 /* this should not happen */
861 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
862 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, FALSE);
871 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
872 for (i = 0; i != pattern_num; ++i) {
873 regfree (patterns[i].preg);
874 g_slice_free (regex_t, patterns[i].preg);
875 } /* don't free patterns itself -- it's static */
879 modest_text_utils_hyperlinkify_begin (void)
881 if (url_matches_block == 0)
883 url_matches_block ++;
887 modest_text_utils_hyperlinkify_end (void)
890 if (url_matches_block <= 0)
896 get_url_matches (GString *txt)
899 guint rv, i, offset = 0;
900 GSList *match_list = NULL;
902 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
904 /* initalize the regexps */
905 modest_text_utils_hyperlinkify_begin ();
907 /* find all the matches */
908 for (i = 0; i != pattern_num; ++i) {
912 gboolean is_submatch;
915 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
916 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
917 break; /* try next regexp */
923 /* check old matches to see if this has already been matched */
925 while (cursor && !is_submatch) {
926 const url_match_t *old_match =
927 (const url_match_t *) cursor->data;
928 guint new_offset = offset + rm.rm_so;
929 is_submatch = (new_offset > old_match->offset &&
930 new_offset < old_match->offset + old_match->len);
931 cursor = g_slist_next (cursor);
935 /* make a list of our matches (<offset, len, prefix> tupels)*/
936 match = g_slice_new (url_match_t);
937 match->offset = offset + rm.rm_so;
938 match->len = rm.rm_eo - rm.rm_so;
939 match->prefix = patterns[i].prefix;
940 match_list = g_slist_prepend (match_list, match);
947 modest_text_utils_hyperlinkify_end ();
949 /* now sort the list, so the matches are in reverse order of occurence.
950 * that way, we can do the replacements starting from the end, so we don't need
951 * to recalculate the offsets
953 match_list = g_slist_sort (match_list,
954 (GCompareFunc)cmp_offsets_reverse);
961 hyperlinkify_plain_text (GString *txt)
964 GSList *match_list = get_url_matches (txt);
966 /* we will work backwards, so the offsets stay valid */
967 for (cursor = match_list; cursor; cursor = cursor->next) {
969 url_match_t *match = (url_match_t*) cursor->data;
970 gchar *url = g_strndup (txt->str + match->offset, match->len);
971 gchar *repl = NULL; /* replacement */
973 /* the prefix is NULL: use the one that is already there */
974 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
975 match->prefix ? match->prefix : EMPTY_STRING,
978 /* replace the old thing with our hyperlink
979 * replacement thing */
980 g_string_erase (txt, match->offset, match->len);
981 g_string_insert (txt, match->offset, repl);
986 g_slice_free (url_match_t, match);
989 g_slist_free (match_list);
993 /* for optimization reasons, we change the string in-place */
995 modest_text_utils_get_display_address (gchar *address)
1002 /* should not be needed, and otherwise, we probably won't screw up the address
1003 * more than it already is :)
1004 * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1007 /* remove leading whitespace */
1008 if (address[0] == ' ')
1009 g_strchug (address);
1011 for (i = 0; address[i]; ++i) {
1012 if (address[i] == '<') {
1013 if (G_UNLIKELY(i == 0))
1014 return; /* there's nothing else, leave it */
1016 address[i] = '\0'; /* terminate the string here */
1028 modest_text_utils_get_email_address (const gchar *full_address)
1030 const gchar *left, *right;
1035 g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1037 left = g_strrstr_len (full_address, strlen(full_address), "<");
1039 return g_strdup (full_address);
1041 right = g_strstr_len (left, strlen(left), ">");
1043 return g_strdup (full_address);
1045 return g_strndup (left + 1, right - left - 1);
1049 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1052 static const gchar* prefix[] = {
1053 "Re:", "RE:", "RV:", "re:"
1054 "Fwd:", "FWD:", "FW:", "fwd:", "Fw:", "fw:", NULL
1057 if (!sub || (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')) /* optimization */
1063 if (g_str_has_prefix(sub, prefix[i])) {
1064 int prefix_len = strlen(prefix[i]);
1065 if (sub[prefix_len] == ' ')
1066 ++prefix_len; /* ignore space after prefix as well */
1076 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1081 /* work even when s1 and/or s2 == NULL */
1082 if (G_UNLIKELY(s1 == s2))
1085 /* if it's not case sensitive */
1087 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
1089 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
1090 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
1092 result = strcmp (n1, n2);
1102 modest_text_utils_get_display_date (time_t date)
1105 static const guint BUF_SIZE = 64;
1106 static const guint ONE_DAY = 24 * 60 * 60; /* seconds in one day */
1107 gchar date_buf[BUF_SIZE];
1108 gchar today_buf [BUF_SIZE];
1110 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
1114 /* we check if the date is within the last 24h, if not, we don't
1115 * have to do the extra, expensive strftime, which was very visible
1118 if (abs(now - date) < ONE_DAY) {
1120 /* it's within the last 24 hours, but double check */
1121 /* use the localized dates */
1122 modest_text_utils_strftime (today_buf, BUF_SIZE, "%x", now);
1124 /* if it's today, use the time instead */
1125 if (strcmp (date_buf, today_buf) == 0)
1126 modest_text_utils_strftime (date_buf, BUF_SIZE, "%X", date);
1129 return g_strdup(date_buf);
1134 modest_text_utils_validate_folder_name (const gchar *folder_name)
1136 /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1137 * with some extras */
1141 const gchar **cursor = NULL;
1142 const gchar *forbidden_names[] = { /* windows does not like these */
1143 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
1144 "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1148 /* cannot be NULL */
1152 /* cannot be empty */
1153 len = strlen(folder_name);
1157 /* cannot start or end with a space */
1158 if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1161 /* cannot contain a forbidden char */
1162 for (i = 0; i < len; i++)
1163 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1166 /* cannot contain a forbidden word */
1168 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1169 if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1173 return TRUE; /* it's valid! */
1179 modest_text_utils_validate_domain_name (const gchar *domain)
1181 gboolean valid = FALSE;
1183 const gchar* domain_regex = "^[a-z0-9]([.]?[a-z0-9-])*[a-z0-9]$";
1185 memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1190 /* domain name: all alphanum or '-' or '.',
1191 * but beginning/ending in alphanum */
1192 if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1193 g_warning ("BUG: error in regexp");
1197 valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1206 modest_text_utils_validate_email_address (const gchar *email_address, const gchar **invalid_char_position)
1209 const gchar *c = NULL, *domain = NULL;
1210 static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1212 if (invalid_char_position != NULL)
1213 *invalid_char_position = NULL;
1215 /* check that the email adress contains exactly one @ */
1216 if (!strstr(email_address, "@") ||
1217 (strstr(email_address, "@") != g_strrstr(email_address, "@")))
1222 /* first we validate the name portion (name@domain) */
1223 for (c = email_address; *c; c++) {
1225 (c == email_address ||
1227 *(c - 1) == '\"')) {
1231 if (*c == '\\' && (*++c == ' '))
1233 if (*c <= ' ' || *c >= 127)
1246 if (*c <= ' ' || *c >= 127)
1248 if (strchr(rfc822_specials, *c)) {
1249 if (invalid_char_position)
1250 *invalid_char_position = c;
1254 if (c == email_address || *(c - 1) == '.')
1257 /* next we validate the domain portion (name@domain) */
1258 if (!*(domain = ++c))
1262 if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0')
1266 if (*c <= ' ' || *c >= 127)
1268 if (strchr(rfc822_specials, *c)) {
1269 if (invalid_char_position)
1270 *invalid_char_position = c;
1275 return (count >= 1) ? TRUE : FALSE;
1279 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1281 gchar *stripped, *current;
1283 gboolean has_error = FALSE;
1285 if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1287 stripped = g_strdup (recipient);
1288 stripped = g_strstrip (stripped);
1291 if (*current == '\0') {
1297 if (*current == '\"') {
1298 current = g_utf8_next_char (current);
1300 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1301 if (*current == '\\') {
1302 /* TODO: This causes a warning, which breaks the build,
1303 * because a gchar cannot be < 0.
1305 if (current[1] <0) {
1310 } else if (*current == '\"') {
1312 current = g_utf8_next_char (current);
1318 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1319 if (*current == '<') {
1331 right_part = g_strdup (current);
1333 right_part = g_strstrip (right_part);
1335 if (g_str_has_prefix (right_part, "<") &&
1336 g_str_has_suffix (right_part, ">")) {
1340 address = g_strndup (right_part+1, strlen (right_part) - 2);
1341 g_free (right_part);
1342 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1346 g_free (right_part);
1353 modest_text_utils_get_display_size (guint64 size)
1355 const guint KB=1024;
1356 const guint MB=1024 * KB;
1357 const guint GB=1024 * MB;
1360 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1361 if (0 < size && size < KB)
1362 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1363 else if (KB <= size && size < 100 * KB)
1364 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1365 else if (100*KB <= size && size < MB)
1366 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1367 else if (MB <= size && size < 10*MB)
1368 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1369 else if (10*MB <= size && size < GB)
1370 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1372 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB);
1376 get_email_from_address (const gchar * address)
1378 gchar *left_limit, *right_limit;
1380 left_limit = strstr (address, "<");
1381 right_limit = g_strrstr (address, ">");
1383 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1384 return g_strdup (address);
1386 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1390 modest_text_utils_get_color_string (GdkColor *color)
1393 return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1394 (color->red >> 12) & 0xf, (color->red >> 8) & 0xf,
1395 (color->red >> 4) & 0xf, (color->red) & 0xf,
1396 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1397 (color->green >> 4) & 0xf, (color->green) & 0xf,
1398 (color->blue >> 12) & 0xf, (color->blue >> 8) & 0xf,
1399 (color->blue >> 4) & 0xf, (color->blue) & 0xf);
1403 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1405 GtkTextIter start, end;
1406 gchar *slice, *current;
1407 GString *result = g_string_new ("");
1409 g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1411 gtk_text_buffer_get_start_iter (buffer, &start);
1412 gtk_text_buffer_get_end_iter (buffer, &end);
1414 slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1417 while (current && current != '\0') {
1418 if (g_utf8_get_char (current) == 0xFFFC) {
1419 result = g_string_append_c (result, ' ');
1420 current = g_utf8_next_char (current);
1422 gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1424 result = g_string_append (result, current);
1426 result = g_string_append_len (result, current, next - current);
1433 return g_string_free (result, FALSE);
1438 modest_text_utils_is_forbidden_char (const gchar character,
1439 ModestTextUtilsForbiddenCharType type)
1442 const gchar *forbidden_chars = NULL;
1444 /* We need to get the length in the switch because the
1445 compiler needs to know the size at compile time */
1447 case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1448 forbidden_chars = account_title_forbidden_chars;
1449 len = G_N_ELEMENTS (account_title_forbidden_chars);
1451 case FOLDER_NAME_FORBIDDEN_CHARS:
1452 forbidden_chars = folder_name_forbidden_chars;
1453 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1455 case USER_NAME_FORBIDDEN_NAMES:
1456 forbidden_chars = user_name_forbidden_chars;
1457 len = G_N_ELEMENTS (user_name_forbidden_chars);
1460 g_return_val_if_reached (TRUE);
1463 for (i = 0; i < len ; i++)
1464 if (forbidden_chars[i] == character)
1467 return FALSE; /* it's valid! */