* Fixes NB#89889, if the size is < 1Kb then show it as 1Kb
[modest] / src / modest-text-utils.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
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.
16  *
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.
28  */
29
30
31
32 #ifndef _GNU_SOURCE
33 #define _GNU_SOURCE
34 #endif /*_GNU_SOURCE*/
35 #include <string.h> /* for strcasestr */
36
37
38 #include <glib.h>
39 #include <stdlib.h>
40 #include <glib/gi18n.h>
41 #include <regex.h>
42 #include <modest-tny-platform-factory.h>
43 #include <modest-text-utils.h>
44 #include <modest-runtime.h>
45 #include <ctype.h>
46
47 #ifdef HAVE_CONFIG_H
48 #include <config.h>
49 #endif /*HAVE_CONFIG_H */
50
51 /* defines */
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 ""
58
59 /*
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,
63  * will hang modest
64  */
65 #define HYPERLINKIFY_MAX_LENGTH (1024*50)
66 #define SIGNATURE_MARKER "--"
67
68
69 /*
70  * we need these regexps to find URLs in plain text e-mails
71  */
72 typedef struct _url_match_pattern_t url_match_pattern_t;
73 struct _url_match_pattern_t {
74         gchar   *regex;
75         regex_t *preg;
76         gchar   *prefix;
77 };
78
79 typedef struct _url_match_t url_match_t;
80 struct _url_match_t {
81         guint offset;
82         guint len;
83         const gchar* prefix;
84 };
85
86
87 /*
88  * we mark the ampersand with \007 when converting text->html
89  * because after text->html we do hyperlink detecting, which
90  * could be screwed up by the ampersand.
91  * ie. 1<3 ==> 1\007lt;3
92  */
93 #define MARK_AMP '\007'
94 #define MARK_AMP_STR "\007"
95
96 /* mark &amp; separately, because they are parts of urls.
97  * ie. a&b => a\006amp;b, but a>b => a\007gt;b
98  *
99  * we need to handle '&' separately, because it can be part of URIs
100  * (as in href="http://foo.bar?a=1&b=1"), so inside those URIs
101  * we need to re-replace \006amp; with '&' again, while outside uri's
102  * it will be '&amp;'
103  * 
104  * yes, it's messy, but a consequence of doing text->html first, then hyperlinkify
105  */
106 #define MARK_AMP_URI '\006'
107 #define MARK_AMP_URI_STR "\006"
108
109
110 /* note: match MARK_AMP_URI_STR as well, because after txt->html, a '&' will look like $(MARK_AMP_URI_STR)"amp;" */
111 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
112         { "(file|rtsp|http|ftp|https|mms|mmsh|rtsp|rdp|lastfm)://[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR \
113                         "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",      \
114           NULL, NULL },\
115         { "www\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
116                         NULL, "http://" },                              \
117         { "ftp\\.[-a-z0-9_$.+!*(),;:@%=?/~#" MARK_AMP_URI_STR "]+[-a-z0-9_$%" MARK_AMP_URI_STR "=?/~#]",\
118           NULL, "ftp://" },\
119         { "(jabberto|voipto|sipto|sip|chatto|xmpp):[-_a-z@0-9.+]+", \
120            NULL, NULL},                                             \
121         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
122           NULL, NULL},\
123         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
124           NULL, "mailto:"}\
125         }
126
127 const gchar account_title_forbidden_chars[] = {
128         '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
129 };
130 const gchar folder_name_forbidden_chars[] = {
131         '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$', '#', '&'
132 };
133 const gchar user_name_forbidden_chars[] = {
134         '<', '>'
135 };
136 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
137 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
138 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
139
140 /* private */
141 static gchar*   cite                    (const time_t sent_date, const gchar *from);
142 static void     hyperlinkify_plain_text (GString *txt, gint offset);
143 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
144 static GSList*  get_url_matches         (GString *txt, gint offset);
145
146 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
147 static int      get_indent_level        (const char *l);
148 static void     unquote_line            (GString * l, const gchar *quote_symbol);
149 static void     append_quoted           (GString * buf, const gchar *quote_symbol,
150                                          const int indent, const GString * str, 
151                                          const int cutpoint);
152 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
153 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
154 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
155
156 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
157                                                     const gchar *cite, 
158                                                     const gchar *signature,
159                                                     GList *attachments, 
160                                                     int limit);
161
162 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
163                                                     const gchar *cite,
164                                                     const gchar *signature,
165                                                     GList *attachments,
166                                                     int limit);
167 static gchar*   get_email_from_address (const gchar *address);
168
169
170 /* ******************************************************************* */
171 /* ************************* PUBLIC FUNCTIONS ************************ */
172 /* ******************************************************************* */
173
174 gchar *
175 modest_text_utils_quote (const gchar *text, 
176                          const gchar *content_type,
177                          const gchar *signature,
178                          const gchar *from,
179                          const time_t sent_date, 
180                          GList *attachments,
181                          int limit)
182 {
183         gchar *retval, *cited;
184
185         g_return_val_if_fail (text, NULL);
186         g_return_val_if_fail (content_type, NULL);
187
188         cited = cite (sent_date, from);
189         
190         if (content_type && strcmp (content_type, "text/html") == 0)
191                 /* TODO: extract the <body> of the HTML and pass it to
192                    the function */
193                 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
194         else
195                 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
196         
197         g_free (cited);
198         
199         return retval;
200 }
201
202
203 gchar *
204 modest_text_utils_cite (const gchar *text,
205                         const gchar *content_type,
206                         const gchar *signature,
207                         const gchar *from,
208                         time_t sent_date)
209 {
210         gchar *retval;
211         gchar *tmp_sig;
212         
213         g_return_val_if_fail (text, NULL);
214         g_return_val_if_fail (content_type, NULL);
215         
216         if (!signature)
217                 retval = g_strdup ("");
218         else if (strcmp(content_type, "text/html") == 0) {
219                 tmp_sig = g_strconcat ("\n", SIGNATURE_MARKER,"\n", signature, NULL);
220                 retval = modest_text_utils_convert_to_html_body(tmp_sig, -1, TRUE);
221                 g_free (tmp_sig);
222         } else {
223                 retval = g_strconcat (text, "\n", SIGNATURE_MARKER, "\n", signature, NULL);
224         }
225
226         return retval;
227 }
228
229 static gchar *
230 forward_cite (const gchar *from,
231               const gchar *sent,
232               const gchar *to,
233               const gchar *subject)
234 {
235         g_return_val_if_fail (sent, NULL);
236         
237         return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n", 
238                                 FORWARD_STRING, 
239                                 FROM_STRING, (from)?from:"",
240                                 SENT_STRING, sent,
241                                 TO_STRING, (to)?to:"",
242                                 SUBJECT_STRING, (subject)?subject:"");
243 }
244
245 gchar * 
246 modest_text_utils_inline (const gchar *text,
247                           const gchar *content_type,
248                           const gchar *signature,
249                           const gchar *from,
250                           time_t sent_date,
251                           const gchar *to,
252                           const gchar *subject)
253 {
254         gchar sent_str[101];
255         gchar *cited;
256         gchar *retval;
257         
258         g_return_val_if_fail (text, NULL);
259         g_return_val_if_fail (content_type, NULL);
260         
261         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
262
263         cited = forward_cite (from, sent_str, to, subject);
264         
265         if (content_type && strcmp (content_type, "text/html") == 0)
266                 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
267         else
268                 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
269         
270         g_free (cited);
271         return retval;
272 }
273
274 /* just to prevent warnings:
275  * warning: `%x' yields only last 2 digits of year in some locales
276  */
277 gsize
278 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
279 {
280         struct tm tm;
281
282         /* To prevent possible problems in strftime that could leave
283            garbage in the s variable */
284         if (s)
285                 s[0] = '\0';
286
287         /* does not work on old maemo glib: 
288          *   g_date_set_time_t (&date, timet);
289          */
290         localtime_r (&timet, &tm);
291         return strftime(s, max, fmt, &tm);
292 }
293
294 gchar *
295 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
296 {
297         gchar *tmp, *subject_dup, *retval;
298         gint prefix_len;
299
300         g_return_val_if_fail (prefix, NULL);
301
302         if (!subject || subject[0] == '\0')
303                 subject = _("mail_va_no_subject");
304
305         subject_dup = g_strdup (subject);
306         tmp = g_strchug (subject_dup);
307
308         /* We do not want things like "Re: Re: Re:" or "Fw: Fw:" so
309            delete the previous ones */
310         prefix_len = strlen (prefix);
311         do {
312                 if (g_str_has_prefix (tmp, prefix)) {
313                         tmp += prefix_len;
314                         tmp = g_strchug (tmp);
315                 } else {
316                         break;
317                 }
318         } while (tmp);
319
320         retval = g_strdup_printf ("%s %s", prefix, tmp);
321         g_free (subject_dup);
322
323         return retval;
324 }
325
326 gchar*
327 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
328 {
329         gchar *dup, *token, *ptr = NULL, *result;
330         GString *filtered_emails;
331         gchar *email_address;
332
333         g_return_val_if_fail (address_list, NULL);
334         
335         if (!address)
336                 return g_strdup (address_list);
337
338         email_address = get_email_from_address (address);
339         
340         /* search for substring */
341         if (!strstr ((const char *) address_list, (const char *) email_address)) {
342                 g_free (email_address);
343                 return g_strdup (address_list);
344         }
345
346         dup = g_strdup (address_list);
347         filtered_emails = g_string_new (NULL);
348         
349         token = strtok_r (dup, ",", &ptr);
350
351         while (token != NULL) {
352                 /* Add to list if not found */
353                 if (!strstr ((const char *) token, (const char *) email_address)) {
354                         if (filtered_emails->len == 0)
355                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
356                         else
357                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
358                 }
359                 token = strtok_r (NULL, ",", &ptr);
360         }
361         result = filtered_emails->str;
362
363         /* Clean */
364         g_free (email_address);
365         g_free (dup);
366         g_string_free (filtered_emails, FALSE);
367
368         return result;
369 }
370
371
372 gchar*
373 modest_text_utils_remove_duplicate_addresses (const gchar *address_list)
374 {
375         GSList *addresses, *cursor;
376         GHashTable *table;
377         gchar *new_list = NULL;
378         
379         g_return_val_if_fail (address_list, NULL);
380
381         table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
382         addresses = modest_text_utils_split_addresses_list (address_list);
383
384         cursor = addresses;
385         while (cursor) {
386                 const gchar* address = (const gchar*)cursor->data;
387
388                 /* We need only the email to just compare it and not
389                    the full address which would make "a <a@a.com>"
390                    different from "a@a.com" */
391                 const gchar *email = get_email_from_address (address);
392
393                 /* ignore the address if already seen */
394                 if (g_hash_table_lookup (table, email) == 0) {
395                         gchar *tmp;
396
397                         /* Include the full address and not only the
398                            email in the returned list */
399                         if (!new_list) {
400                                 tmp = g_strdup (address);
401                         } else {
402                                 tmp = g_strjoin (",", new_list, address, NULL);
403                                 g_free (new_list);
404                         }
405                         new_list = tmp;
406                         
407                         g_hash_table_insert (table, (gchar*)email, GINT_TO_POINTER(1));
408                 }
409                 cursor = g_slist_next (cursor);
410         }
411
412         g_hash_table_unref (table);
413         g_slist_foreach (addresses, (GFunc)g_free, NULL);
414         g_slist_free (addresses);
415
416         return new_list;
417 }
418
419
420 static void
421 modest_text_utils_convert_buffer_to_html_start (GString *html, const gchar *data, gssize n)
422 {
423         guint           i;
424         gboolean        space_seen = FALSE;
425         guint           break_dist = 0; /* distance since last break point */
426
427         if (n == -1)
428                 n = strlen (data);
429
430         /* replace with special html chars where needed*/
431         for (i = 0; i != n; ++i)  {
432                 guchar kar = data[i];
433                 
434                 if (space_seen && kar != ' ') {
435                         g_string_append_c (html, ' ');
436                         space_seen = FALSE;
437                 }
438                 
439                 /* we artificially insert a breakpoint (newline)
440                  * after 256, to make sure our lines are not so long
441                  * they will DOS the regexping later
442                  * Also, check that kar is ASCII to make sure that we
443                  * don't break a UTF8 char in two
444                  */
445                 if (++break_dist >= 256 && kar < 127) {
446                         g_string_append_c (html, '\n');
447                         break_dist = 0;
448                 }
449                 
450                 switch (kar) {
451                 case 0:
452                 case MARK_AMP:
453                 case MARK_AMP_URI:      
454                         /* this is a temp place holder for '&'; we can only
455                                 * set the real '&' after hyperlink translation, otherwise
456                                 * we might screw that up */
457                         break; /* ignore embedded \0s and MARK_AMP */   
458                 case '<'  : g_string_append (html, MARK_AMP_STR "lt;");   break;
459                 case '>'  : g_string_append (html, MARK_AMP_STR "gt;");   break;
460                 case '&'  : g_string_append (html, MARK_AMP_URI_STR "amp;");  break; /* special case */
461                 case '"'  : g_string_append (html, MARK_AMP_STR "quot;");  break;
462
463                 /* don't convert &apos; --> wpeditor will try to re-convert it... */    
464                 //case '\'' : g_string_append (html, "&apos;"); break;
465                 case '\n' : g_string_append (html, "<br>\n");break_dist= 0; break;
466                 case '\t' : g_string_append (html, MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp;" MARK_AMP_STR "nbsp; ");
467                         break_dist=0; break; /* note the space at the end*/
468                 case ' ':
469                         break_dist = 0;
470                         if (space_seen) { /* second space in a row */
471                                 g_string_append (html, "&nbsp; ");
472                                 space_seen = FALSE;
473                         } else
474                                 space_seen = TRUE;
475                         break;
476                 default:
477                         g_string_append_c (html, kar);
478                 }
479         }
480 }
481
482
483 static void
484 modest_text_utils_convert_buffer_to_html_finish (GString *html)
485 {
486         int i;
487         /* replace all our MARK_AMPs with real ones */
488         for (i = 0; i != html->len; ++i)
489                 if ((html->str)[i] == MARK_AMP || (html->str)[i] == MARK_AMP_URI)
490                         (html->str)[i] = '&';
491 }
492
493
494 gchar*
495 modest_text_utils_convert_to_html (const gchar *data)
496 {
497         GString         *html;      
498         gsize           len;
499
500         g_return_val_if_fail (data, NULL);
501         
502         if (!data)
503                 return NULL;
504
505         len = strlen (data);
506         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
507
508         g_string_append_printf (html,
509                                 "<html><head>"
510                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
511                                 "</head>"
512                                 "<body>");
513
514         modest_text_utils_convert_buffer_to_html_start (html, data, -1);
515         
516         g_string_append (html, "</body></html>");
517
518         if (len <= HYPERLINKIFY_MAX_LENGTH)
519                 hyperlinkify_plain_text (html, 0);
520
521         modest_text_utils_convert_buffer_to_html_finish (html);
522         
523         return g_string_free (html, FALSE);
524 }
525
526 gchar *
527 modest_text_utils_convert_to_html_body (const gchar *data, gssize n, gboolean hyperlinkify)
528 {
529         GString         *html;      
530
531         g_return_val_if_fail (data, NULL);
532
533         if (!data)
534                 return NULL;
535
536         if (n == -1) 
537                 n = strlen (data);
538         html = g_string_sized_new (1.5 * n);    /* just a  guess... */
539
540         modest_text_utils_convert_buffer_to_html_start (html, data, n);
541
542         if (hyperlinkify && (n < HYPERLINKIFY_MAX_LENGTH))
543                 hyperlinkify_plain_text (html, 0);
544
545         modest_text_utils_convert_buffer_to_html_finish (html);
546         
547         return g_string_free (html, FALSE);
548 }
549
550 void
551 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
552 {
553         gchar *current, *start, *last_blank;
554         gint start_offset = 0, current_offset = 0;
555
556         g_return_if_fail (start_indexes != NULL);
557         g_return_if_fail (end_indexes != NULL);
558
559         start = (gchar *) addresses;
560         current = start;
561         last_blank = start;
562
563         while (*current != '\0') {
564                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
565                         start = g_utf8_next_char (start);
566                         start_offset++;
567                         last_blank = current;
568                 } else if ((*current == ',')||(*current == ';')) {
569                         gint *start_index, *end_index;
570                         start_index = g_new0(gint, 1);
571                         end_index = g_new0(gint, 1);
572                         *start_index = start_offset;
573                         *end_index = current_offset;
574                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
575                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
576                         start = g_utf8_next_char (current);
577                         start_offset = current_offset + 1;
578                         last_blank = start;
579                 } else if (*current == '"') {
580                         current = g_utf8_next_char (current);
581                         current_offset ++;
582                         while ((*current != '"')&&(*current != '\0')) {
583                                 current = g_utf8_next_char (current);
584                                 current_offset ++;
585                         }
586                 }
587                                 
588                 current = g_utf8_next_char (current);
589                 current_offset ++;
590         }
591
592         if (start != current) {
593                         gint *start_index, *end_index;
594                         start_index = g_new0(gint, 1);
595                         end_index = g_new0(gint, 1);
596                         *start_index = start_offset;
597                         *end_index = current_offset;
598                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
599                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
600         }
601         
602         *start_indexes = g_slist_reverse (*start_indexes);
603         *end_indexes = g_slist_reverse (*end_indexes);
604
605         return;
606 }
607
608
609 GSList *
610 modest_text_utils_split_addresses_list (const gchar *addresses)
611 {
612         GSList *head;
613         const gchar *my_addrs = addresses;
614         const gchar *end;
615         gchar *addr;
616         gboolean after_at = FALSE;
617
618         g_return_val_if_fail (addresses, NULL);
619         
620         /* skip any space, ',', ';' at the start */
621         while (my_addrs && (my_addrs[0] == ' ' || my_addrs[0] == ',' || my_addrs[0] == ';'))
622                ++my_addrs;
623
624         /* are we at the end of addresses list? */
625         if (!my_addrs[0])
626                 return NULL;
627         
628         /* nope, we are at the start of some address
629          * now, let's find the end of the address */
630         end = my_addrs + 1;
631         while (end[0] && end[0] != ';' && !(after_at && end[0] == ',')) {
632                 if (end[0] == '\"') {
633                         while (end[0] && end[0] != '\"')
634                                 ++end;
635                 }
636                 if (end[0] == '@') {
637                         after_at = TRUE;
638                 }
639                 if ((end[0] && end[0] == '>')&&(end[1] && end[1] == ',')) {
640                         ++end;
641                         break;
642                 }
643                 ++end;
644         }
645
646         /* we got the address; copy it and remove trailing whitespace */
647         addr = g_strndup (my_addrs, end - my_addrs);
648         g_strchomp (addr);
649
650         head = g_slist_append (NULL, addr);
651         head->next = modest_text_utils_split_addresses_list (end); /* recurse */
652
653         return head;
654 }
655
656
657 void
658 modest_text_utils_address_range_at_position (const gchar *recipients_list,
659                                              guint position,
660                                              guint *start,
661                                              guint *end)
662 {
663         gchar *current = NULL;
664         gint range_start = 0;
665         gint range_end = 0;
666         gint index;
667         gboolean is_quoted = FALSE;
668
669         g_return_if_fail (recipients_list);
670         g_return_if_fail (position < g_utf8_strlen(recipients_list, -1));
671                 
672         index = 0;
673         for (current = (gchar *) recipients_list; *current != '\0';
674              current = g_utf8_find_next_char (current, NULL)) {
675                 gunichar c = g_utf8_get_char (current);
676
677                 if ((c == ',') && (!is_quoted)) {
678                         if (index < position) {
679                                 range_start = index + 1;
680                         } else {
681                                 break;
682                         }
683                 } else if (c == '\"') {
684                         is_quoted = !is_quoted;
685                 } else if ((c == ' ') &&(range_start == index)) {
686                         range_start ++;
687                 }
688                 index ++;
689                 range_end = index;
690         }
691
692         if (start)
693                 *start = range_start;
694         if (end)
695                 *end = range_end;
696 }
697
698 gchar *
699 modest_text_utils_address_with_standard_length (const gchar *recipients_list)
700 {
701         gchar ** splitted;
702         gchar ** current;
703         GString *buffer = g_string_new ("");
704
705         splitted = g_strsplit (recipients_list, "\n", 0);
706         current = splitted;
707         while (*current) {
708                 gchar *line;
709                 if (current != splitted)
710                         buffer = g_string_append_c (buffer, '\n');
711                 line = g_strndup (*splitted, 1000);
712                 buffer = g_string_append (buffer, line);
713                 g_free (line);
714                 current++;
715         }
716
717         g_strfreev (splitted);
718
719         return g_string_free (buffer, FALSE);
720 }
721
722
723 /* ******************************************************************* */
724 /* ************************* UTILIY FUNCTIONS ************************ */
725 /* ******************************************************************* */
726
727 static GString *
728 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
729 {
730         GString *gs;
731         const gchar *i0;
732         
733         if (iter > b + blen)
734                 return g_string_new("");
735         
736         i0 = iter;
737         while (iter[0]) {
738                 if (iter[0] == '\n')
739                         break;
740                 iter++;
741         }
742         gs = g_string_new_len (i0, iter - i0);
743         return gs;
744 }
745 static int
746 get_indent_level (const char *l)
747 {
748         int indent = 0;
749
750         while (l[0]) {
751                 if (l[0] == '>') {
752                         indent++;
753                         if (l[1] == ' ') {
754                                 l++;
755                         }
756                 } else {
757                         break;
758                 }
759                 l++;
760
761         }
762
763         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
764          *      stops reformatting.
765          */
766         if (strcmp (l, "-- ") == 0) {
767                 return -1 - indent;
768         } else {
769                 return indent;
770         }
771 }
772
773 static void
774 unquote_line (GString * l, const gchar *quote_symbol)
775 {
776         gchar *p;
777         gint quote_len;
778
779         p = l->str;
780         quote_len = strlen (quote_symbol);
781         while (p[0]) {
782                 if (g_str_has_prefix (p, quote_symbol)) {
783                         if (p[quote_len] == ' ') {
784                                 p += quote_len;
785                         }
786                 } else {
787                         break;
788                 }
789                 p++;
790         }
791         g_string_erase (l, 0, p - l->str);
792 }
793
794 static void
795 append_quoted (GString * buf, const gchar *quote_symbol,
796                int indent, const GString * str,
797                const int cutpoint)
798 {
799         int i;
800         gchar *quote_concat;
801
802         indent = indent < 0 ? abs (indent) - 1 : indent;
803         quote_concat = g_strconcat (quote_symbol, " ", NULL);
804         for (i = 0; i <= indent; i++) {
805                 g_string_append (buf, quote_concat);
806         }
807         g_free (quote_concat);
808         if (cutpoint > 0) {
809                 g_string_append_len (buf, str->str, cutpoint);
810         } else {
811                 g_string_append (buf, str->str);
812         }
813         g_string_append (buf, "\n");
814 }
815
816 static int
817 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
818 {
819         gint index = 0;
820         const gchar *pos, *last;
821         gunichar *uni;
822
823         indent = indent < 0 ? abs (indent) - 1 : indent;
824
825         last = NULL;
826         pos = s;
827         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
828         while (pos[0]) {
829                 if ((index + 2 * indent > limit) && last) {
830                         g_free (uni);
831                         return last - s;
832                 }
833                 if (g_unichar_isspace (uni[index])) {
834                         last = pos;
835                 }
836                 pos = g_utf8_next_char (pos);
837                 index++;
838         }
839         g_free (uni);
840         return strlen (s);
841 }
842
843 static int
844 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
845 {
846         gint i, last;
847
848         last = strlen (s);
849         if (last + 2 * indent < limit)
850                 return last;
851
852         for (i = strlen (s); i > 0; i--) {
853                 if (s[i] == ' ') {
854                         if (i + 2 * indent <= limit) {
855                                 return i;
856                         } else {
857                                 last = i;
858                         }
859                 }
860         }
861         return last;
862 }
863
864 static int
865 get_breakpoint (const gchar * s, const gint indent, const gint limit)
866 {
867
868         if (g_utf8_validate (s, -1, NULL)) {
869                 return get_breakpoint_utf8 (s, indent, limit);
870         } else {                /* assume ASCII */
871                 //g_warning("invalid UTF-8 in msg");
872                 return get_breakpoint_ascii (s, indent, limit);
873         }
874 }
875
876 static gchar *
877 cite (const time_t sent_date, const gchar *from)
878 {
879         return g_strdup (_("mcen_ia_editor_original_message"));
880 }
881
882 static gchar *
883 quoted_attachments (GList *attachments)
884 {
885         GList *node = NULL;
886         GString *result = g_string_new ("");
887         for (node = attachments; node != NULL; node = g_list_next (node)) {
888                 gchar *filename = (gchar *) node->data;
889                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
890         }
891
892         return g_string_free (result, FALSE);
893
894 }
895
896 static GString *
897 modest_text_utils_quote_body (GString *output, const gchar *text,
898                               const gchar *quote_symbol,
899                               int limit)
900 {
901
902         const gchar *iter;
903         gsize len;
904         gint indent, breakpoint, rem_indent = 0;
905         GString *l, *remaining;
906
907         iter = text;
908         len = strlen(text);
909         remaining = g_string_new ("");
910         do {
911                 l = get_next_line (text, len, iter);
912                 iter = iter + l->len + 1;
913                 indent = get_indent_level (l->str);
914                 unquote_line (l, quote_symbol);
915
916                 if (remaining->len) {
917                         if (l->len && indent == rem_indent) {
918                                 g_string_prepend (l, " ");
919                                 g_string_prepend (l, remaining->str);
920                         } else {
921                                 do {
922                                         breakpoint =
923                                                 get_breakpoint (remaining->str,
924                                                                 rem_indent,
925                                                                 limit);
926                                         append_quoted (output, quote_symbol, rem_indent,
927                                                        remaining, breakpoint);
928                                         g_string_erase (remaining, 0,
929                                                         breakpoint);
930                                         if (remaining->str[0] == ' ') {
931                                                 g_string_erase (remaining, 0,
932                                                                 1);
933                                         }
934                                 } while (remaining->len);
935                         }
936                 }
937                 g_string_free (remaining, TRUE);
938                 breakpoint = get_breakpoint (l->str, indent, limit);
939                 remaining = g_string_new (l->str + breakpoint);
940                 if (remaining->str[0] == ' ') {
941                         g_string_erase (remaining, 0, 1);
942                 }
943                 rem_indent = indent;
944                 append_quoted (output, quote_symbol, indent, l, breakpoint);
945                 g_string_free (l, TRUE);
946         } while ((iter < text + len) || (remaining->str[0]));
947
948         return output;
949 }
950
951 static gchar *
952 modest_text_utils_quote_plain_text (const gchar *text, 
953                                     const gchar *cite, 
954                                     const gchar *signature,
955                                     GList *attachments,
956                                     int limit)
957 {
958         GString *q;
959         gchar *attachments_string = NULL;
960
961         q = g_string_new ("");
962
963         if (signature != NULL) {
964                 q = g_string_append (q, "\n--\n");
965                 q = g_string_append (q, signature);
966         }
967
968         q = g_string_append (q, "\n");
969         q = g_string_append (q, cite);
970         q = g_string_append_c (q, '\n');
971
972         q = modest_text_utils_quote_body (q, text, ">", limit);
973
974         attachments_string = quoted_attachments (attachments);
975         q = g_string_append (q, attachments_string);
976         g_free (attachments_string);
977
978         return g_string_free (q, FALSE);
979 }
980
981 static void
982 quote_html_add_to_gstring (GString *string,
983                            const gchar *text)
984 {
985         if (text && strcmp (text, "")) {
986                 gchar *html_text = modest_text_utils_convert_to_html_body (text, -1, TRUE);
987                 g_string_append_printf (string, "%s<br/>", html_text);
988                 g_free (html_text);
989         }
990 }
991
992 static gchar*
993 modest_text_utils_quote_html (const gchar *text, 
994                               const gchar *cite, 
995                               const gchar *signature,
996                               GList *attachments,
997                               int limit)
998 {
999         GString *result_string;
1000
1001         result_string = 
1002                 g_string_new ( \
1003                               "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
1004                               "<html>\n"                                \
1005                               "<body>\n<br/>\n");
1006
1007         if (text || cite || signature) {
1008                 GString *quoted_text;
1009                 g_string_append (result_string, "<pre>\n");
1010                 if (signature) {
1011                         quote_html_add_to_gstring (result_string, SIGNATURE_MARKER);
1012                         quote_html_add_to_gstring (result_string, signature);
1013                 }
1014                 quote_html_add_to_gstring (result_string, cite);
1015                 quoted_text = g_string_new ("");
1016                 quoted_text = modest_text_utils_quote_body (quoted_text, text, ">", limit);
1017                 quote_html_add_to_gstring (result_string, quoted_text->str);
1018                 g_string_free (quoted_text, TRUE);
1019                 if (attachments) {
1020                         gchar *attachments_string = quoted_attachments (attachments);
1021                         quote_html_add_to_gstring (result_string, attachments_string);
1022                         g_free (attachments_string);
1023                 }
1024                 g_string_append (result_string, "</pre>");
1025         }
1026         g_string_append (result_string, "</body>");
1027         g_string_append (result_string, "</html>");
1028
1029         return g_string_free (result_string, FALSE);
1030 }
1031
1032 static gint 
1033 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
1034 {
1035         return match2->offset - match1->offset;
1036 }
1037
1038 static gint url_matches_block = 0;
1039 static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
1040
1041
1042 static gboolean
1043 compile_patterns ()
1044 {
1045         guint i;
1046         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1047         for (i = 0; i != pattern_num; ++i) {
1048                 patterns[i].preg = g_slice_new0 (regex_t);
1049                 
1050                 /* this should not happen */
1051                 if (regcomp (patterns[i].preg, patterns[i].regex,
1052                              REG_ICASE|REG_EXTENDED|REG_NEWLINE) != 0) {
1053                         g_warning ("%s: error in regexp:\n%s\n", __FUNCTION__, patterns[i].regex);
1054                         return FALSE;
1055                 }
1056         }
1057         return TRUE;
1058 }
1059
1060 static void 
1061 free_patterns ()
1062 {
1063         guint i;
1064         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1065         for (i = 0; i != pattern_num; ++i) {
1066                 regfree (patterns[i].preg);
1067                 g_slice_free  (regex_t, patterns[i].preg);
1068         } /* don't free patterns itself -- it's static */
1069 }
1070
1071 void
1072 modest_text_utils_hyperlinkify_begin (void)
1073 {
1074         if (url_matches_block == 0)
1075                 compile_patterns ();
1076         url_matches_block ++;
1077 }
1078
1079 void
1080 modest_text_utils_hyperlinkify_end (void)
1081 {
1082         url_matches_block--;
1083         if (url_matches_block <= 0)
1084                 free_patterns ();
1085 }
1086
1087
1088 static GSList*
1089 get_url_matches (GString *txt, gint offset)
1090 {
1091         regmatch_t rm;
1092         guint rv, i, tmp_offset = 0;
1093         GSList *match_list = NULL;
1094
1095         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
1096
1097         /* initalize the regexps */
1098         modest_text_utils_hyperlinkify_begin ();
1099
1100         /* find all the matches */
1101         for (i = 0; i != pattern_num; ++i) {
1102                 tmp_offset     = offset;        
1103                 while (1) {
1104                         url_match_t *match;
1105                         gboolean is_submatch;
1106                         GSList *cursor;
1107                         
1108                         if ((rv = regexec (patterns[i].preg, txt->str + tmp_offset, 1, &rm, 0)) != 0) {
1109                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
1110                                 break; /* try next regexp */ 
1111                         }
1112                         if (rm.rm_so == -1)
1113                                 break;
1114                         
1115                         is_submatch = FALSE;
1116                         /* check  old matches to see if this has already been matched */
1117                         cursor = match_list;
1118                         while (cursor && !is_submatch) {
1119                                 const url_match_t *old_match =
1120                                         (const url_match_t *) cursor->data;
1121                                 guint new_offset = tmp_offset + rm.rm_so;
1122                                 is_submatch = (new_offset >  old_match->offset &&
1123                                                new_offset <  old_match->offset + old_match->len);
1124                                 cursor = g_slist_next (cursor);
1125                         }
1126
1127                         if (!is_submatch) {
1128                                 /* make a list of our matches (<offset, len, prefix> tupels)*/
1129                                 match = g_slice_new (url_match_t);
1130                                 match->offset = tmp_offset + rm.rm_so;
1131                                 match->len    = rm.rm_eo - rm.rm_so;
1132                                 match->prefix = patterns[i].prefix;
1133                                 match_list = g_slist_prepend (match_list, match);
1134                         }               
1135                         tmp_offset += rm.rm_eo;
1136                 }
1137         }
1138
1139         modest_text_utils_hyperlinkify_end ();
1140         
1141         /* now sort the list, so the matches are in reverse order of occurence.
1142          * that way, we can do the replacements starting from the end, so we don't need
1143          * to recalculate the offsets
1144          */
1145         match_list = g_slist_sort (match_list,
1146                                    (GCompareFunc)cmp_offsets_reverse); 
1147         return match_list;      
1148 }
1149
1150
1151
1152 /* replace all occurences of needle in haystack with repl*/
1153 static gchar*
1154 replace_string (const gchar *haystack, const gchar *needle, gchar repl)
1155 {
1156         gchar *str, *cursor;
1157
1158         if (!haystack || !needle || strlen(needle) == 0)
1159                 return haystack ? g_strdup(haystack) : NULL;
1160         
1161         str = g_strdup (haystack);
1162
1163         for (cursor = str; cursor && *cursor; ++cursor) {
1164                 if (g_str_has_prefix (cursor, needle)) {
1165                         cursor[0] = repl;
1166                         memmove (cursor + 1,
1167                                  cursor + strlen (needle),
1168                                  strlen (cursor + strlen (needle)) + 1);
1169                 }
1170         }
1171         
1172         return str;
1173 }
1174
1175 static void
1176 hyperlinkify_plain_text (GString *txt, gint offset)
1177 {
1178         GSList *cursor;
1179         GSList *match_list = get_url_matches (txt, offset);
1180
1181         /* we will work backwards, so the offsets stay valid */
1182         for (cursor = match_list; cursor; cursor = cursor->next) {
1183
1184                 url_match_t *match = (url_match_t*) cursor->data;
1185                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
1186                 gchar *repl = NULL; /* replacement  */
1187
1188                 /* the string still contains $(MARK_AMP_URI_STR)"amp;" for each
1189                  * '&' in the original, because of the text->html conversion.
1190                  * in the href-URL (and only there), we must convert that back to
1191                  * '&'
1192                  */
1193                 gchar *href_url = replace_string (url, MARK_AMP_URI_STR "amp;", '&');
1194                 
1195                 /* the prefix is NULL: use the one that is already there */
1196                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
1197                                         match->prefix ? match->prefix : EMPTY_STRING, 
1198                                         href_url, url);
1199
1200                 /* replace the old thing with our hyperlink
1201                  * replacement thing */
1202                 g_string_erase  (txt, match->offset, match->len);
1203                 g_string_insert (txt, match->offset, repl);
1204                 
1205                 g_free (url);
1206                 g_free (repl);
1207                 g_free (href_url);
1208
1209                 g_slice_free (url_match_t, match);      
1210         }
1211         
1212         g_slist_free (match_list);
1213 }
1214
1215 void
1216 modest_text_utils_hyperlinkify (GString *string_buffer)
1217 {
1218         gchar *after_body;
1219         gint offset = 0;
1220
1221         after_body = strstr (string_buffer->str, "<body>");
1222         if (after_body != NULL)
1223                 offset = after_body - string_buffer->str;
1224         hyperlinkify_plain_text (string_buffer, offset);
1225 }
1226
1227
1228 /* for optimization reasons, we change the string in-place */
1229 void
1230 modest_text_utils_get_display_address (gchar *address)
1231 {
1232         int i;
1233
1234         g_return_if_fail (address);
1235         
1236         if (!address)
1237                 return;
1238         
1239         /* should not be needed, and otherwise, we probably won't screw up the address
1240          * more than it already is :) 
1241          * g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
1242          * */
1243         
1244         /* remove leading whitespace */
1245         if (address[0] == ' ')
1246                 g_strchug (address);
1247                 
1248         for (i = 0; address[i]; ++i) {
1249                 if (address[i] == '<') {
1250                         if (G_UNLIKELY(i == 0))
1251                                 return; /* there's nothing else, leave it */
1252                         else {
1253                                 address[i] = '\0'; /* terminate the string here */
1254                                 return;
1255                         }
1256                 }
1257         }
1258 }
1259
1260
1261
1262
1263
1264 gchar *
1265 modest_text_utils_get_email_address (const gchar *full_address)
1266 {
1267         const gchar *left, *right;
1268
1269         g_return_val_if_fail (full_address, NULL);
1270         
1271         if (!full_address)
1272                 return NULL;
1273         
1274         g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
1275         
1276         left = g_strrstr_len (full_address, strlen(full_address), "<");
1277         if (left == NULL)
1278                 return g_strdup (full_address);
1279
1280         right = g_strstr_len (left, strlen(left), ">");
1281         if (right == NULL)
1282                 return g_strdup (full_address);
1283
1284         return g_strndup (left + 1, right - left - 1);
1285 }
1286
1287 gint 
1288 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1289 {
1290         gint prefix_len = 0;    
1291
1292         g_return_val_if_fail (sub, 0);
1293
1294         if (!sub)
1295                 return 0;
1296         
1297         /* optimization: "Re", "RE", "re","Fwd", "FWD", "fwd","FW","Fw", "fw" */
1298         if (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')
1299                 return 0;
1300         else if (sub[0] && sub[1] != 'e' && sub[1] != 'E' && sub[1] != 'w' && sub[1] != 'W')
1301                 return 0;
1302
1303         prefix_len = 2;
1304         if (sub[2] == 'd')
1305                 ++prefix_len;
1306
1307         /* skip over a [...] block */
1308         if (sub[prefix_len] == '[') {
1309                 int c = prefix_len + 1;
1310                 while (sub[c] && sub[c] != ']')
1311                         ++c;
1312                 if (!sub[c])
1313                         return 0; /* no end to the ']' found */
1314                 else
1315                         prefix_len = c + 1;
1316         }
1317
1318         /* did we find the ':' ? */
1319         if (sub[prefix_len] == ':') {
1320                 ++prefix_len;
1321                 if (sub[prefix_len] == ' ')
1322                         ++prefix_len;
1323                 prefix_len += modest_text_utils_get_subject_prefix_len (sub + prefix_len);
1324 /*              g_warning ("['%s','%s']", sub, (char*) sub + prefix_len); */
1325                 return prefix_len;
1326         } else
1327                 return 0;
1328 }
1329
1330
1331 gint
1332 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1333 {
1334
1335 /* work even when s1 and/or s2 == NULL */
1336         if (G_UNLIKELY(s1 == s2))
1337                 return 0;
1338         if (G_UNLIKELY(!s1))
1339                 return -1;
1340         if (G_UNLIKELY(!s2))
1341                 return 1;
1342         
1343         /* if it's not case sensitive */
1344         if (!insensitive) {
1345
1346                 /* optimization: shortcut if first char is ascii */ 
1347                 if (((s1[0] & 0x80)== 0) && ((s2[0] & 0x80) == 0) &&
1348                     (s1[0] != s2[0])) 
1349                         return s1[0] - s2[0];
1350                 
1351                 return g_utf8_collate (s1, s2);
1352
1353         } else {
1354                 gint result;
1355                 gchar *n1, *n2;
1356
1357                 /* optimization: shortcut if first char is ascii */ 
1358                 if (((s1[0] & 0x80) == 0) && ((s2[0] & 0x80) == 0) &&
1359                     (tolower(s1[0]) != tolower (s2[0]))) 
1360                         return tolower(s1[0]) - tolower(s2[0]);
1361                 
1362                 n1 = g_utf8_strdown (s1, -1);
1363                 n2 = g_utf8_strdown (s2, -1);
1364                 
1365                 result = g_utf8_collate (n1, n2);
1366                 
1367                 g_free (n1);
1368                 g_free (n2);
1369         
1370                 return result;
1371         }
1372 }
1373
1374
1375 const gchar*
1376 modest_text_utils_get_display_date (time_t date)
1377 {
1378 #define DATE_BUF_SIZE 64 
1379         static gchar date_buf[DATE_BUF_SIZE];
1380         
1381         /* calculate the # of days since epoch for 
1382          * for today and for the date provided 
1383          * based on idea from pvanhoof */
1384         int day      = time(NULL) / (24 * 60 * 60);
1385         int date_day = date       / (24 * 60 * 60);
1386
1387         /* if it's today, show the time, if it's not today, show the date instead */
1388
1389         /* TODO: take into account the system config for 24/12h */
1390         if (day == date_day) /* is the date today? */
1391                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_24h_time"), date);
1392         else 
1393                 modest_text_utils_strftime (date_buf, DATE_BUF_SIZE, _HL("wdgt_va_date"), date); 
1394
1395         return date_buf; /* this is a static buffer, don't free! */
1396 }
1397
1398
1399
1400 gboolean
1401 modest_text_utils_validate_folder_name (const gchar *folder_name)
1402 {
1403         /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1404          * with some extras */
1405         
1406         guint len;
1407         gint i;
1408         const gchar **cursor = NULL;
1409         const gchar *forbidden_names[] = { /* windows does not like these */
1410                 "CON", "PRN", "AUX", "NUL", ".", "..", "cur", "tmp", "new", 
1411                 NULL /* cur, tmp, new are reserved for Maildir */
1412         };
1413         
1414         /* cannot be NULL */
1415         if (!folder_name) 
1416                 return FALSE;
1417
1418         /* cannot be empty */
1419         len = strlen(folder_name);
1420         if (len == 0)
1421                 return FALSE;
1422         
1423         /* cannot start with a dot, vfat does not seem to like that */
1424         if (folder_name[0] == '.')
1425                 return FALSE;
1426
1427         /* cannot start or end with a space */
1428         if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1429                 return FALSE; 
1430
1431         /* cannot contain a forbidden char */   
1432         for (i = 0; i < len; i++)
1433                 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1434                         return FALSE;
1435
1436         /* Cannot contain Windows port numbers. I'd like to use GRegex
1437            but it's still not available in Maemo. sergio */
1438         if (!g_ascii_strncasecmp (folder_name, "LPT", 3) ||
1439             !g_ascii_strncasecmp (folder_name, "COM", 3)) {
1440                 glong val;
1441                 gchar *endptr;
1442
1443                 /* We skip the first 3 characters for the
1444                    comparison */
1445                 val = strtol(folder_name+3, &endptr, 10);
1446
1447                 /* If the conversion to long succeeded then the string
1448                    is not valid for us */
1449                 if (*endptr == '\0')
1450                         return FALSE;
1451                 else
1452                         return TRUE;
1453         }
1454         
1455         /* cannot contain a forbidden word */
1456         if (len <= 4) {
1457                 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1458                         if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1459                                 return FALSE;
1460                 }
1461         }
1462
1463         return TRUE; /* it's valid! */
1464 }
1465
1466
1467
1468 gboolean
1469 modest_text_utils_validate_domain_name (const gchar *domain)
1470 {
1471         gboolean valid = FALSE;
1472         regex_t rx;
1473         const gchar* domain_regex = "^([a-z0-9-]*[a-z0-9]\\.)+[a-z0-9-]*[a-z0-9]$";
1474
1475         g_return_val_if_fail (domain, FALSE);
1476         
1477         if (!domain)
1478                 return FALSE;
1479         
1480         memset (&rx, 0, sizeof(regex_t)); /* coverity wants this... */
1481                 
1482         /* domain name: all alphanum or '-' or '.',
1483          * but beginning/ending in alphanum */  
1484         if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1485                 g_warning ("BUG: error in regexp");
1486                 return FALSE;
1487         }
1488         
1489         valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1490         regfree (&rx);
1491                 
1492         return valid;
1493 }
1494
1495
1496
1497 gboolean
1498 modest_text_utils_validate_email_address (const gchar *email_address,
1499                                           const gchar **invalid_char_position)
1500 {
1501         int count = 0;
1502         const gchar *c = NULL, *domain = NULL;
1503         static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1504         
1505         if (invalid_char_position)
1506                 *invalid_char_position = NULL;
1507         
1508         g_return_val_if_fail (email_address, FALSE);
1509         
1510         /* check that the email adress contains exactly one @ */
1511         if (!strstr(email_address, "@") || 
1512                         (strstr(email_address, "@") != g_strrstr(email_address, "@"))) 
1513                 return FALSE;
1514         
1515         /* first we validate the name portion (name@domain) */
1516         for (c = email_address;  *c;  c++) {
1517                 if (*c == '\"' && 
1518                     (c == email_address || 
1519                      *(c - 1) == '.' || 
1520                      *(c - 1) == '\"')) {
1521                         while (*++c) {
1522                                 if (*c == '\"') 
1523                                         break;
1524                                 if (*c == '\\' && (*++c == ' ')) 
1525                                         continue;
1526                                 if (*c <= ' ' || *c >= 127) 
1527                                         return FALSE;
1528                         }
1529                         if (!*c++) 
1530                                 return FALSE;
1531                         if (*c == '@') 
1532                                 break;
1533                         if (*c != '.') 
1534                                 return FALSE;
1535                         continue;
1536                 }
1537                 if (*c == '@') 
1538                         break;
1539                 if (*c <= ' ' || *c >= 127) 
1540                         return FALSE;
1541                 if (strchr(rfc822_specials, *c)) {
1542                         if (invalid_char_position)
1543                                 *invalid_char_position = c;
1544                         return FALSE;
1545                 }
1546         }
1547         if (c == email_address || *(c - 1) == '.') 
1548                 return FALSE;
1549
1550         /* next we validate the domain portion (name@domain) */
1551         if (!*(domain = ++c)) 
1552                 return FALSE;
1553         do {
1554                 if (*c == '.') {
1555                         if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0') 
1556                                 return FALSE;
1557                         count++;
1558                 }
1559                 if (*c <= ' ' || *c >= 127) 
1560                         return FALSE;
1561                 if (strchr(rfc822_specials, *c)) {
1562                         if (invalid_char_position)
1563                                 *invalid_char_position = c;
1564                         return FALSE;
1565                 }
1566         } while (*++c);
1567
1568         return (count >= 1) ? TRUE : FALSE;
1569 }
1570
1571 gboolean 
1572 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1573 {
1574         gchar *stripped, *current;
1575         gchar *right_part;
1576         gboolean has_error = FALSE;
1577
1578         if (invalid_char_position)
1579                 *invalid_char_position = NULL;
1580         
1581         g_return_val_if_fail (recipient, FALSE);
1582         
1583         if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1584                 return TRUE;
1585
1586         stripped = g_strdup (recipient);
1587         stripped = g_strstrip (stripped);
1588         current = stripped;
1589
1590         if (*current == '\0') {
1591                 g_free (stripped);
1592                 return FALSE;
1593         }
1594
1595         /* quoted string */
1596         if (*current == '\"') {
1597                 current = g_utf8_next_char (current);
1598                 has_error = TRUE;
1599                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1600                         if (*current == '\\') {
1601                                 /* TODO: This causes a warning, which breaks the build, 
1602                                  * because a gchar cannot be < 0.
1603                                  * murrayc. 
1604                                 if (current[1] <0) {
1605                                         has_error = TRUE;
1606                                         break;
1607                                 }
1608                                 */
1609                         } else if (*current == '\"') {
1610                                 has_error = FALSE;
1611                                 current = g_utf8_next_char (current);
1612                                 break;
1613                         }
1614                 }
1615         } else {
1616                 has_error = TRUE;
1617                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1618                         if (*current == '<') {
1619                                 has_error = FALSE;
1620                                 break;
1621                         }
1622                 }
1623         }
1624                 
1625         if (has_error) {
1626                 g_free (stripped);
1627                 return FALSE;
1628         }
1629
1630         right_part = g_strdup (current);
1631         g_free (stripped);
1632         right_part = g_strstrip (right_part);
1633
1634         if (g_str_has_prefix (right_part, "<") &&
1635             g_str_has_suffix (right_part, ">")) {
1636                 gchar *address;
1637                 gboolean valid;
1638
1639                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1640                 g_free (right_part);
1641                 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1642                 g_free (address);
1643                 return valid;
1644         } else {
1645                 g_free (right_part);
1646                 return FALSE;
1647         }
1648 }
1649
1650
1651 gchar *
1652 modest_text_utils_get_display_size (guint64 size)
1653 {
1654         const guint KB=1024;
1655         const guint MB=1024 * KB;
1656         const guint GB=1024 * MB;
1657
1658         if (size == 0)
1659                 return g_strdup_printf (_FM("sfil_li_size_kb"));
1660         if (0 <= size && size < KB)
1661                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), 1);
1662         else if (KB <= size && size < 100 * KB)
1663                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1664         else if (100*KB <= size && size < MB)
1665                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1666         else if (MB <= size && size < 10*MB)
1667                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1668         else if (10*MB <= size && size < GB)
1669                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1670         else
1671                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1672 }
1673
1674 static gchar *
1675 get_email_from_address (const gchar * address)
1676 {
1677         gchar *left_limit, *right_limit;
1678
1679         left_limit = strstr (address, "<");
1680         right_limit = g_strrstr (address, ">");
1681
1682         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1683                 return g_strdup (address);
1684         else
1685                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1686 }
1687
1688 gchar *      
1689 modest_text_utils_get_color_string (GdkColor *color)
1690 {
1691         g_return_val_if_fail (color, NULL);
1692         
1693         return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1694                                 (color->red >> 12)   & 0xf, (color->red >> 8)   & 0xf,
1695                                 (color->red >>  4)   & 0xf, (color->red)        & 0xf,
1696                                 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1697                                 (color->green >>  4) & 0xf, (color->green)      & 0xf,
1698                                 (color->blue >> 12)  & 0xf, (color->blue >> 8)  & 0xf,
1699                                 (color->blue >>  4)  & 0xf, (color->blue)       & 0xf);
1700 }
1701
1702 gchar *
1703 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1704 {
1705         GtkTextIter start, end;
1706         gchar *slice, *current;
1707         GString *result = g_string_new ("");
1708
1709         g_return_val_if_fail (buffer && GTK_IS_TEXT_BUFFER (buffer), NULL);
1710         
1711         gtk_text_buffer_get_start_iter (buffer, &start);
1712         gtk_text_buffer_get_end_iter (buffer, &end);
1713
1714         slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1715         current = slice;
1716
1717         while (current && current != '\0') {
1718                 if (g_utf8_get_char (current) == 0xFFFC) {
1719                         result = g_string_append_c (result, ' ');
1720                         current = g_utf8_next_char (current);
1721                 } else {
1722                         gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1723                         if (next == NULL) {
1724                                 result = g_string_append (result, current);
1725                         } else {
1726                                 result = g_string_append_len (result, current, next - current);
1727                         }
1728                         current = next;
1729                 }
1730         }
1731         g_free (slice);
1732
1733         return g_string_free (result, FALSE);
1734         
1735 }
1736
1737 gboolean
1738 modest_text_utils_is_forbidden_char (const gchar character,
1739                                      ModestTextUtilsForbiddenCharType type)
1740 {
1741         gint i, len;
1742         const gchar *forbidden_chars = NULL;
1743         
1744         /* We need to get the length in the switch because the
1745            compiler needs to know the size at compile time */
1746         switch (type) {
1747         case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1748                 forbidden_chars = account_title_forbidden_chars;
1749                 len = G_N_ELEMENTS (account_title_forbidden_chars);
1750                 break;
1751         case FOLDER_NAME_FORBIDDEN_CHARS:
1752                 forbidden_chars = folder_name_forbidden_chars;
1753                 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1754                 break;
1755         case USER_NAME_FORBIDDEN_NAMES:
1756                 forbidden_chars = user_name_forbidden_chars;
1757                 len = G_N_ELEMENTS (user_name_forbidden_chars);
1758                 break;
1759         default:
1760                 g_return_val_if_reached (TRUE);
1761         }
1762
1763         for (i = 0; i < len ; i++)
1764                 if (forbidden_chars[i] == character)
1765                         return TRUE;
1766
1767         return FALSE; /* it's valid! */
1768 }
1769
1770 gchar *      
1771 modest_text_utils_label_get_selection (GtkLabel *label)
1772 {
1773         gint start, end;
1774         gchar *selection;
1775
1776         if (gtk_label_get_selection_bounds (GTK_LABEL (label), &start, &end)) {
1777                 const gchar *start_offset;
1778                 const gchar *end_offset;
1779                 start_offset = gtk_label_get_text (GTK_LABEL (label));
1780                 start_offset = g_utf8_offset_to_pointer (start_offset, start);
1781                 end_offset = gtk_label_get_text (GTK_LABEL (label));
1782                 end_offset = g_utf8_offset_to_pointer (end_offset, end);
1783                 selection = g_strndup (start_offset, end_offset - start_offset);
1784                 return selection;
1785         } else {
1786                 return g_strdup ("");
1787         }
1788 }
1789
1790 static gboolean
1791 _forward_search_image_char (gunichar ch,
1792                             gpointer userdata)
1793 {
1794         return (ch == 0xFFFC);
1795 }
1796
1797 gboolean
1798 modest_text_utils_buffer_selection_is_valid (GtkTextBuffer *buffer)
1799 {
1800         gboolean result;
1801         GtkTextIter start, end;
1802
1803         g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
1804
1805         result = gtk_text_buffer_get_has_selection (GTK_TEXT_BUFFER (buffer));
1806
1807         /* check there are no images in selection */
1808         if (result) {
1809                 gtk_text_buffer_get_selection_bounds (buffer, &start, &end);
1810                 if (gtk_text_iter_get_char (&start)== 0xFFFC)
1811                         result = FALSE;
1812                 else {
1813                         gtk_text_iter_backward_char (&end);
1814                         if (gtk_text_iter_forward_find_char (&start, _forward_search_image_char,
1815                                                              NULL, &end))
1816                                 result = FALSE;
1817                 }
1818                                     
1819         }
1820
1821         return result;
1822 }
1823
1824 gchar *
1825 modest_text_utils_escape_mnemonics (const gchar *text)
1826 {
1827         const gchar *p;
1828         GString *result = NULL;
1829
1830         if (text == NULL)
1831                 return NULL;
1832
1833         result = g_string_new ("");
1834         for (p = text; *p != '\0'; p++) {
1835                 if (*p == '_')
1836                         result = g_string_append (result, "__");
1837                 else
1838                         result = g_string_append_c (result, *p);
1839         }
1840         
1841         return g_string_free (result, FALSE);
1842 }