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 _("-----Forwarded Message-----")
53 #define FROM_STRING _("From:")
54 #define SENT_STRING _("Sent:")
55 #define TO_STRING _("To:")
56 #define SUBJECT_STRING _("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.]+",\
100 static gchar* cite (const time_t sent_date, const gchar *from);
101 static void hyperlinkify_plain_text (GString *txt);
102 static gint cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2);
103 static GSList* get_url_matches (GString *txt);
105 static GString* get_next_line (const char *b, const gsize blen, const gchar * iter);
106 static int get_indent_level (const char *l);
107 static void unquote_line (GString * l);
108 static void append_quoted (GString * buf, const int indent, const GString * str,
110 static int get_breakpoint_utf8 (const gchar * s, const gint indent, const gint limit);
111 static int get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit);
112 static int get_breakpoint (const gchar * s, const gint indent, const gint limit);
114 static gchar* modest_text_utils_quote_plain_text (const gchar *text,
116 const gchar *signature,
120 static gchar* modest_text_utils_quote_html (const gchar *text,
122 const gchar *signature,
125 static gchar* get_email_from_address (const gchar *address);
128 /* ******************************************************************* */
129 /* ************************* PUBLIC FUNCTIONS ************************ */
130 /* ******************************************************************* */
133 modest_text_utils_quote (const gchar *text,
134 const gchar *content_type,
135 const gchar *signature,
137 const time_t sent_date,
141 gchar *retval, *cited;
143 g_return_val_if_fail (text, NULL);
144 g_return_val_if_fail (content_type, NULL);
146 cited = cite (sent_date, from);
148 if (content_type && strcmp (content_type, "text/html") == 0)
149 /* TODO: extract the <body> of the HTML and pass it to
151 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
153 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
162 modest_text_utils_cite (const gchar *text,
163 const gchar *content_type,
164 const gchar *signature,
171 g_return_val_if_fail (text, NULL);
172 g_return_val_if_fail (content_type, NULL);
175 retval = g_strdup ("");
176 else if (!strcmp(content_type, "text/html")) {
177 tmp_sig = g_strconcat ("\n", signature, NULL);
178 retval = modest_text_utils_convert_to_html_body(tmp_sig);
181 retval = g_strconcat ("\n", signature, NULL);
188 forward_cite (const gchar *from,
191 const gchar *subject)
193 return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n",
195 FROM_STRING, (from)?from:"",
197 TO_STRING, (to)?to:"",
198 SUBJECT_STRING, (subject)?subject:"");
202 modest_text_utils_inline (const gchar *text,
203 const gchar *content_type,
204 const gchar *signature,
208 const gchar *subject)
214 g_return_val_if_fail (text, NULL);
215 g_return_val_if_fail (content_type, NULL);
217 modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
219 cited = forward_cite (from, sent_str, to, subject);
221 if (content_type && strcmp (content_type, "text/html") == 0)
222 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
224 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
230 /* just to prevent warnings:
231 * warning: `%x' yields only last 2 digits of year in some locales
234 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
238 /* does not work on old maemo glib:
239 * g_date_set_time_t (&date, timet);
241 localtime_r (&timet, &tm);
242 return strftime(s, max, fmt, &tm);
246 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
250 g_return_val_if_fail (prefix, NULL);
252 if (!subject || subject[0] == '\0')
253 subject = _("mail_va_no_subject");
255 tmp = g_strchug (g_strdup (subject));
257 if (!strncmp (tmp, prefix, strlen (prefix))) {
261 return g_strdup_printf ("%s %s", prefix, subject);
266 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
268 gchar *dup, *token, *ptr, *result;
269 GString *filtered_emails;
270 gchar *email_address;
272 g_return_val_if_fail (address_list, NULL);
275 return g_strdup (address_list);
277 email_address = get_email_from_address (address);
279 /* search for substring */
280 if (!strstr ((const char *) address_list, (const char *) email_address)) {
281 g_free (email_address);
282 return g_strdup (address_list);
285 dup = g_strdup (address_list);
286 filtered_emails = g_string_new (NULL);
288 token = strtok_r (dup, ",", &ptr);
290 while (token != NULL) {
291 /* Add to list if not found */
292 if (!strstr ((const char *) token, (const char *) email_address)) {
293 if (filtered_emails->len == 0)
294 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
296 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
298 token = strtok_r (NULL, ",", &ptr);
300 result = filtered_emails->str;
303 g_free (email_address);
305 g_string_free (filtered_emails, FALSE);
311 modest_text_utils_convert_buffer_to_html (GString *html, const gchar *data)
314 gboolean space_seen = FALSE;
316 guint break_dist = 0; /* distance since last break point */
320 /* replace with special html chars where needed*/
321 for (i = 0; i != len; ++i) {
324 if (space_seen && kar != ' ') {
325 g_string_append_c (html, ' ');
329 /* we artificially insert a breakpoint (newline)
330 * after 256, to make sure our lines are not so long
331 * they will DOS the regexping later
333 if (++break_dist == 256) {
334 g_string_append_c (html, '\n');
339 case 0: break; /* ignore embedded \0s */
340 case '<' : g_string_append (html, "<"); break;
341 case '>' : g_string_append (html, ">"); break;
342 case '&' : g_string_append (html, "&"); break;
343 case '"' : g_string_append (html, """); break;
344 case '\'' : g_string_append (html, "'"); break;
345 case '\n' : g_string_append (html, "<br>\n"); break_dist= 0; break;
346 case '\t' : g_string_append (html, " "); break_dist=0; break; /* note the space at the end*/
349 if (space_seen) { /* second space in a row */
350 g_string_append (html, " ");
356 g_string_append_c (html, kar);
362 modest_text_utils_convert_to_html (const gchar *data)
371 html = g_string_sized_new (1.5 * len); /* just a guess... */
373 g_string_append_printf (html,
375 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
379 modest_text_utils_convert_buffer_to_html (html, data);
381 g_string_append (html, "</body></html>");
383 if (len <= HYPERLINKIFY_MAX_LENGTH)
384 hyperlinkify_plain_text (html);
386 return g_string_free (html, FALSE);
390 modest_text_utils_convert_to_html_body (const gchar *data)
399 html = g_string_sized_new (1.5 * len); /* just a guess... */
401 modest_text_utils_convert_buffer_to_html (html, data);
403 if (len < HYPERLINKIFY_MAX_LENGTH)
404 hyperlinkify_plain_text (html);
406 return g_string_free (html, FALSE);
410 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
412 gchar *current, *start, *last_blank;
413 gint start_offset = 0, current_offset = 0;
415 g_return_if_fail (start_indexes != NULL);
416 g_return_if_fail (end_indexes != NULL);
418 start = (gchar *) addresses;
422 while (*current != '\0') {
423 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
424 start = g_utf8_next_char (start);
426 last_blank = current;
427 } else if ((*current == ',')||(*current == ';')) {
428 gint *start_index, *end_index;
429 start_index = g_new0(gint, 1);
430 end_index = g_new0(gint, 1);
431 *start_index = start_offset;
432 *end_index = current_offset;
433 *start_indexes = g_slist_prepend (*start_indexes, start_index);
434 *end_indexes = g_slist_prepend (*end_indexes, end_index);
435 start = g_utf8_next_char (current);
436 start_offset = current_offset + 1;
438 } else if (*current == '"') {
439 current = g_utf8_next_char (current);
441 while ((*current != '"')&&(*current != '\0')) {
442 current = g_utf8_next_char (current);
447 current = g_utf8_next_char (current);
451 if (start != current) {
452 gint *start_index, *end_index;
453 start_index = g_new0(gint, 1);
454 end_index = g_new0(gint, 1);
455 *start_index = start_offset;
456 *end_index = current_offset;
457 *start_indexes = g_slist_prepend (*start_indexes, start_index);
458 *end_indexes = g_slist_prepend (*end_indexes, end_index);
461 *start_indexes = g_slist_reverse (*start_indexes);
462 *end_indexes = g_slist_reverse (*end_indexes);
468 modest_text_utils_split_addresses_list (const gchar *addresses)
470 gchar *current, *start, *last_blank;
471 GSList *result = NULL;
473 start = (gchar *) addresses;
477 while (*current != '\0') {
478 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
479 start = g_utf8_next_char (start);
480 last_blank = current;
481 } else if ((*current == ',')||(*current == ';')) {
482 gchar *new_address = NULL;
483 new_address = g_strndup (start, current - last_blank);
484 result = g_slist_prepend (result, new_address);
485 start = g_utf8_next_char (current);
487 } else if (*current == '\"') {
488 if (current == start) {
489 current = g_utf8_next_char (current);
490 start = g_utf8_next_char (start);
492 while ((*current != '\"')&&(*current != '\0'))
493 current = g_utf8_next_char (current);
496 current = g_utf8_next_char (current);
499 if (start != current) {
500 gchar *new_address = NULL;
501 new_address = g_strndup (start, current - last_blank);
502 result = g_slist_prepend (result, new_address);
505 result = g_slist_reverse (result);
511 modest_text_utils_address_range_at_position (const gchar *recipients_list,
516 gchar *current = NULL;
517 gint range_start = 0;
520 gboolean is_quoted = FALSE;
523 for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
524 gunichar c = g_utf8_get_char (current);
526 if ((c == ',') && (!is_quoted)) {
527 if (index < position) {
528 range_start = index + 1;
532 } else if (c == '\"') {
533 is_quoted = !is_quoted;
534 } else if ((c == ' ') &&(range_start == index)) {
542 *start = range_start;
548 /* ******************************************************************* */
549 /* ************************* UTILIY FUNCTIONS ************************ */
550 /* ******************************************************************* */
553 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
559 return g_string_new("");
567 gs = g_string_new_len (i0, iter - i0);
571 get_indent_level (const char *l)
588 /* if we hit the signature marker "-- ", we return -(indent + 1). This
589 * stops reformatting.
591 if (strcmp (l, "-- ") == 0) {
599 unquote_line (GString * l)
614 g_string_erase (l, 0, p - l->str);
618 append_quoted (GString * buf, int indent, const GString * str,
623 indent = indent < 0 ? abs (indent) - 1 : indent;
624 for (i = 0; i <= indent; i++) {
625 g_string_append (buf, "> ");
628 g_string_append_len (buf, str->str, cutpoint);
630 g_string_append (buf, str->str);
632 g_string_append (buf, "\n");
636 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
639 const gchar *pos, *last;
642 indent = indent < 0 ? abs (indent) - 1 : indent;
646 uni = g_utf8_to_ucs4_fast (s, -1, NULL);
648 if ((index + 2 * indent > limit) && last) {
652 if (g_unichar_isspace (uni[index])) {
655 pos = g_utf8_next_char (pos);
663 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
668 if (last + 2 * indent < limit)
671 for (i = strlen (s); i > 0; i--) {
673 if (i + 2 * indent <= limit) {
684 get_breakpoint (const gchar * s, const gint indent, const gint limit)
687 if (g_utf8_validate (s, -1, NULL)) {
688 return get_breakpoint_utf8 (s, indent, limit);
689 } else { /* assume ASCII */
690 //g_warning("invalid UTF-8 in msg");
691 return get_breakpoint_ascii (s, indent, limit);
696 cite (const time_t sent_date, const gchar *from)
698 return g_strdup (_("mcen_ia_editor_original_message"));
702 quoted_attachments (GList *attachments)
705 GString *result = g_string_new ("");
706 for (node = attachments; node != NULL; node = g_list_next (node)) {
707 gchar *filename = (gchar *) node->data;
708 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
711 return g_string_free (result, FALSE);
716 modest_text_utils_quote_plain_text (const gchar *text,
718 const gchar *signature,
723 gint indent, breakpoint, rem_indent = 0;
724 GString *q, *l, *remaining;
726 gchar *attachments_string = NULL;
728 /* remaining will store the rest of the line if we have to break it */
729 q = g_string_new ("\n");
730 q = g_string_append (q, cite);
731 q = g_string_append_c (q, '\n');
732 remaining = g_string_new ("");
737 l = get_next_line (text, len, iter);
738 iter = iter + l->len + 1;
739 indent = get_indent_level (l->str);
742 if (remaining->len) {
743 if (l->len && indent == rem_indent) {
744 g_string_prepend (l, " ");
745 g_string_prepend (l, remaining->str);
749 get_breakpoint (remaining->str,
752 append_quoted (q, rem_indent,
753 remaining, breakpoint);
754 g_string_erase (remaining, 0,
756 if (remaining->str[0] == ' ') {
757 g_string_erase (remaining, 0,
760 } while (remaining->len);
763 g_string_free (remaining, TRUE);
764 breakpoint = get_breakpoint (l->str, indent, limit);
765 remaining = g_string_new (l->str + breakpoint);
766 if (remaining->str[0] == ' ') {
767 g_string_erase (remaining, 0, 1);
770 append_quoted (q, indent, l, breakpoint);
771 g_string_free (l, TRUE);
772 } while ((iter < text + len) || (remaining->str[0]));
774 attachments_string = quoted_attachments (attachments);
775 q = g_string_append (q, attachments_string);
776 g_free (attachments_string);
778 if (signature != NULL) {
779 q = g_string_append_c (q, '\n');
780 q = g_string_append (q, signature);
783 return g_string_free (q, FALSE);
787 modest_text_utils_quote_html (const gchar *text,
789 const gchar *signature,
793 gchar *result = NULL;
794 gchar *signature_result = NULL;
795 const gchar *format = \
796 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
800 "<pre>%s<br/>%s<br/>%s</pre>\n" \
803 gchar *attachments_string = NULL;
804 gchar *q_attachments_string = NULL;
805 gchar *q_cite = NULL;
806 gchar *html_text = NULL;
808 if (signature == NULL)
809 signature_result = g_strdup ("");
811 signature_result = modest_text_utils_convert_to_html_body (signature);
813 attachments_string = quoted_attachments (attachments);
814 q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string);
815 q_cite = modest_text_utils_convert_to_html_body (cite);
816 html_text = modest_text_utils_convert_to_html_body (text);
817 result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
820 g_free (attachments_string);
821 g_free (q_attachments_string);
822 g_free (signature_result);
827 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
829 return match2->offset - match1->offset;
834 get_url_matches (GString *txt)
837 guint rv, i, offset = 0;
838 GSList *match_list = NULL;
840 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
841 const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
843 /* initalize the regexps */
844 for (i = 0; i != pattern_num; ++i) {
845 patterns[i].preg = g_slice_new0 (regex_t);
847 /* this should not happen */
848 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
849 REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
851 /* find all the matches */
852 for (i = 0; i != pattern_num; ++i) {
856 gboolean is_submatch;
859 if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
860 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
861 break; /* try next regexp */
867 /* check old matches to see if this has already been matched */
869 while (cursor && !is_submatch) {
870 const url_match_t *old_match =
871 (const url_match_t *) cursor->data;
872 guint new_offset = offset + rm.rm_so;
873 is_submatch = (new_offset > old_match->offset &&
874 new_offset < old_match->offset + old_match->len);
875 cursor = g_slist_next (cursor);
879 /* make a list of our matches (<offset, len, prefix> tupels)*/
880 match = g_slice_new (url_match_t);
881 match->offset = offset + rm.rm_so;
882 match->len = rm.rm_eo - rm.rm_so;
883 match->prefix = patterns[i].prefix;
884 g_warning ("<%d, %d, %s>", match->offset, match->len, match->prefix);
885 match_list = g_slist_prepend (match_list, match);
892 for (i = 0; i != pattern_num; ++i) {
893 regfree (patterns[i].preg);
894 g_slice_free (regex_t, patterns[i].preg);
895 } /* don't free patterns itself -- it's static */
897 /* now sort the list, so the matches are in reverse order of occurence.
898 * that way, we can do the replacements starting from the end, so we don't need
899 * to recalculate the offsets
901 match_list = g_slist_sort (match_list,
902 (GCompareFunc)cmp_offsets_reverse);
909 hyperlinkify_plain_text (GString *txt)
912 GSList *match_list = get_url_matches (txt);
914 /* we will work backwards, so the offsets stay valid */
915 for (cursor = match_list; cursor; cursor = cursor->next) {
917 url_match_t *match = (url_match_t*) cursor->data;
918 gchar *url = g_strndup (txt->str + match->offset, match->len);
919 gchar *repl = NULL; /* replacement */
921 /* the prefix is NULL: use the one that is already there */
922 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
923 match->prefix ? match->prefix : EMPTY_STRING,
926 /* replace the old thing with our hyperlink
927 * replacement thing */
928 g_string_erase (txt, match->offset, match->len);
929 g_string_insert (txt, match->offset, repl);
934 g_slice_free (url_match_t, match);
937 g_slist_free (match_list);
943 modest_text_utils_get_display_address (gchar *address)
950 g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
952 g_strchug (address); /* remove leading whitespace */
954 /* <email@address> from display name */
955 cursor = g_strstr_len (address, strlen(address), "<");
956 if (cursor == address) /* there's nothing else? leave it */
961 /* remove (bla bla) from display name */
962 cursor = g_strstr_len (address, strlen(address), "(");
963 if (cursor == address) /* there's nothing else? leave it */
968 g_strchomp (address); /* remove trailing whitespace */
974 modest_text_utils_get_email_address (const gchar *full_address)
976 const gchar *left, *right;
981 g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
983 left = g_strrstr_len (full_address, strlen(full_address), "<");
985 return g_strdup (full_address);
987 right = g_strstr_len (left, strlen(left), ">");
989 return g_strdup (full_address);
991 return g_strndup (left + 1, right - left - 1);
995 modest_text_utils_get_subject_prefix_len (const gchar *sub)
998 static const gchar* prefix[] = {
999 "Re:", "RE:", "RV:", "re:"
1000 "Fwd:", "FWD:", "FW:", "fwd:", "Fw:", "fw:", NULL
1003 if (!sub || (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')) /* optimization */
1009 if (g_str_has_prefix(sub, prefix[i])) {
1010 int prefix_len = strlen(prefix[i]);
1011 if (sub[prefix_len] == ' ')
1012 ++prefix_len; /* ignore space after prefix as well */
1022 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1027 /* work even when s1 and/or s2 == NULL */
1028 if (G_UNLIKELY(s1 == s2))
1031 /* if it's not case sensitive */
1033 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
1035 n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
1036 n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
1038 result = strcmp (n1, n2);
1048 modest_text_utils_get_display_date (time_t date)
1051 static const guint BUF_SIZE = 64;
1052 static const guint ONE_DAY = 24 * 60 * 60; /* seconds in one day */
1053 gchar date_buf[BUF_SIZE];
1054 gchar today_buf [BUF_SIZE];
1056 modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
1060 /* we check if the date is within the last 24h, if not, we don't
1061 * have to do the extra, expensive strftime, which was very visible
1064 if (abs(now - date) < ONE_DAY) {
1066 /* it's within the last 24 hours, but double check */
1067 /* use the localized dates */
1068 modest_text_utils_strftime (today_buf, BUF_SIZE, "%x", now);
1070 /* if it's today, use the time instead */
1071 if (strcmp (date_buf, today_buf) == 0)
1072 modest_text_utils_strftime (date_buf, BUF_SIZE, "%X", date);
1075 return g_strdup(date_buf);
1080 modest_text_utils_validate_folder_name (const gchar *folder_name)
1082 /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1083 * with some extras */
1086 const gchar **cursor;
1087 const gchar *forbidden_chars[] = {
1088 "<", ">", ":", "\"", "/", "\\", "|", "?", "*", "^", "%", "$", NULL
1090 const gchar *forbidden_names[] = { /* windows does not like these */
1091 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
1092 "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1096 /* cannot be NULL */
1100 /* cannot be empty */
1101 len = strlen(folder_name);
1105 /* cannot start or end with a space */
1106 if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1109 /* cannot contain a forbidden char */
1110 for (cursor = forbidden_chars; cursor && *cursor; ++cursor)
1111 if (strstr(folder_name, *cursor) != NULL)
1114 /* cannot contain a forbidden word */
1116 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1117 if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1121 return TRUE; /* it's valid! */
1127 modest_text_utils_validate_domain_name (const gchar *domain)
1129 gboolean valid = FALSE;
1131 const gchar* domain_regex = "^[a-z0-9]([.]?[a-z0-9-])*[a-z0-9]$";
1136 /* domain name: all alphanum or '-' or '.',
1137 * but beginning/ending in alphanum */
1138 if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1139 g_warning ("BUG: error in regexp");
1143 valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1152 modest_text_utils_validate_email_address (const gchar *email_address, const gchar **invalid_char_position)
1155 const gchar *c = NULL, *domain = NULL;
1156 static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1158 if (invalid_char_position != NULL)
1159 *invalid_char_position = NULL;
1161 /* check that the email adress contains exactly one @ */
1162 if (!strstr(email_address, "@") ||
1163 (strstr(email_address, "@") != g_strrstr(email_address, "@")))
1168 /* first we validate the name portion (name@domain) */
1169 for (c = email_address; *c; c++) {
1171 (c == email_address ||
1173 *(c - 1) == '\"')) {
1177 if (*c == '\\' && (*++c == ' '))
1179 if (*c <= ' ' || *c >= 127)
1192 if (*c <= ' ' || *c >= 127)
1194 if (strchr(rfc822_specials, *c)) {
1195 if (invalid_char_position)
1196 *invalid_char_position = c;
1200 if (c == email_address || *(c - 1) == '.')
1203 /* next we validate the domain portion (name@domain) */
1204 if (!*(domain = ++c))
1208 if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0')
1212 if (*c <= ' ' || *c >= 127)
1214 if (strchr(rfc822_specials, *c)) {
1215 if (invalid_char_position)
1216 *invalid_char_position = c;
1221 return (count >= 1) ? TRUE : FALSE;
1225 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1227 gchar *stripped, *current;
1229 gboolean has_error = FALSE;
1231 if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1233 stripped = g_strdup (recipient);
1234 stripped = g_strstrip (stripped);
1237 if (*current == '\0') {
1243 if (*current == '\"') {
1244 current = g_utf8_next_char (current);
1246 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1247 if (*current == '\\') {
1248 /* TODO: This causes a warning, which breaks the build,
1249 * because a gchar cannot be < 0.
1251 if (current[1] <0) {
1256 } else if (*current == '\"') {
1258 current = g_utf8_next_char (current);
1264 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1265 if (*current == '<') {
1277 right_part = g_strdup (current);
1279 right_part = g_strstrip (right_part);
1281 if (g_str_has_prefix (right_part, "<") &&
1282 g_str_has_suffix (right_part, ">")) {
1286 address = g_strndup (right_part+1, strlen (right_part) - 2);
1287 g_free (right_part);
1288 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1292 g_free (right_part);
1299 modest_text_utils_get_display_size (guint64 size)
1301 const guint KB=1024;
1302 const guint MB=1024 * KB;
1303 const guint GB=1024 * MB;
1306 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1307 if (0 < size && size < KB)
1308 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1309 else if (KB <= size && size < 100 * KB)
1310 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1311 else if (100*KB <= size && size < MB)
1312 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1313 else if (MB <= size && size < 10*MB)
1314 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1315 else if (10*MB <= size && size < GB)
1316 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1318 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB);
1322 get_email_from_address (const gchar * address)
1324 gchar *left_limit, *right_limit;
1326 left_limit = strstr (address, "<");
1327 right_limit = g_strrstr (address, ">");
1329 if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1330 return g_strdup (address);
1332 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1336 modest_text_utils_get_color_string (GdkColor *color)
1339 return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1340 (color->red >> 12) & 0xf, (color->red >> 8) & 0xf,
1341 (color->red >> 4) & 0xf, (color->red) & 0xf,
1342 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1343 (color->green >> 4) & 0xf, (color->green) & 0xf,
1344 (color->blue >> 12) & 0xf, (color->blue >> 8) & 0xf,
1345 (color->blue >> 4) & 0xf, (color->blue) & 0xf);
1349 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1351 GtkTextIter start, end;
1352 gchar *slice, *current;
1353 GString *result = g_string_new ("");
1355 g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1357 gtk_text_buffer_get_start_iter (buffer, &start);
1358 gtk_text_buffer_get_end_iter (buffer, &end);
1360 slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1363 while (current && current != '\0') {
1364 if (g_utf8_get_char (current) == 0xFFFC) {
1365 result = g_string_append_c (result, ' ');
1366 current = g_utf8_next_char (current);
1368 gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1370 result = g_string_append (result, current);
1372 result = g_string_append_len (result, current, next - current);
1379 return g_string_free (result, FALSE);