* Fixed modest_text_utils_get_display_address, now the original string is not modifi...
[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
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
67 /*
68  * we need these regexps to find URLs in plain text e-mails
69  */
70 typedef struct _url_match_pattern_t url_match_pattern_t;
71 struct _url_match_pattern_t {
72         gchar   *regex;
73         regex_t *preg;
74         gchar   *prefix;
75 };
76
77 typedef struct _url_match_t url_match_t;
78 struct _url_match_t {
79         guint offset;
80         guint len;
81         const gchar* prefix;
82 };
83
84 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
85         { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
86           NULL, NULL },\
87         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
88                         NULL, "http://" },                              \
89         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
90           NULL, "ftp://" },\
91         { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
92            NULL, NULL},                                             \
93         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
94           NULL, NULL},\
95         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
96           NULL, "mailto:"}\
97         }
98
99 const gchar account_title_forbidden_chars[] = {
100         '\\', '/', ':', '*', '?', '\'', '<', '>', '|', '^'
101 };
102 const gchar folder_name_forbidden_chars[] = {
103         '<', '>', ':', '\'', '/', '\\', '|', '?', '*', '^', '%', '$'
104 };
105 const gchar user_name_forbidden_chars[] = {
106         '<', '>'
107 };
108 const guint ACCOUNT_TITLE_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (account_title_forbidden_chars);
109 const guint FOLDER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (folder_name_forbidden_chars);
110 const guint USER_NAME_FORBIDDEN_CHARS_LENGTH = G_N_ELEMENTS (user_name_forbidden_chars);
111
112 /* private */
113 static gchar*   cite                    (const time_t sent_date, const gchar *from);
114 static void     hyperlinkify_plain_text (GString *txt);
115 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
116 static GSList*  get_url_matches         (GString *txt);
117
118 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
119 static int      get_indent_level        (const char *l);
120 static void     unquote_line            (GString * l);
121 static void     append_quoted           (GString * buf, const int indent, const GString * str, 
122                                          const int cutpoint);
123 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
124 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
125 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
126
127 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
128                                                     const gchar *cite, 
129                                                     const gchar *signature,
130                                                     GList *attachments, 
131                                                     int limit);
132
133 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
134                                                     const gchar *cite,
135                                                     const gchar *signature,
136                                                     GList *attachments,
137                                                     int limit);
138 static gchar*   get_email_from_address (const gchar *address);
139
140
141 /* ******************************************************************* */
142 /* ************************* PUBLIC FUNCTIONS ************************ */
143 /* ******************************************************************* */
144
145 gchar *
146 modest_text_utils_quote (const gchar *text, 
147                          const gchar *content_type,
148                          const gchar *signature,
149                          const gchar *from,
150                          const time_t sent_date, 
151                          GList *attachments,
152                          int limit)
153 {
154         gchar *retval, *cited;
155
156         g_return_val_if_fail (text, NULL);
157         g_return_val_if_fail (content_type, NULL);
158
159         cited = cite (sent_date, from);
160         
161         if (content_type && strcmp (content_type, "text/html") == 0)
162                 /* TODO: extract the <body> of the HTML and pass it to
163                    the function */
164                 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
165         else
166                 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
167         
168         g_free (cited);
169         
170         return retval;
171 }
172
173
174 gchar *
175 modest_text_utils_cite (const gchar *text,
176                         const gchar *content_type,
177                         const gchar *signature,
178                         const gchar *from,
179                         time_t sent_date)
180 {
181         gchar *retval;
182         gchar *tmp_sig;
183         
184         g_return_val_if_fail (text, NULL);
185         g_return_val_if_fail (content_type, NULL);
186         
187         if (!signature)
188                 retval = g_strdup ("");
189         else if (strcmp(content_type, "text/html") == 0) {
190                 tmp_sig = g_strconcat ("\n", signature, NULL);
191                 retval = modest_text_utils_convert_to_html_body(tmp_sig);
192                 g_free (tmp_sig);
193         } else {
194                 retval = g_strconcat (text, "\n", signature, NULL);
195         }
196
197         return retval;
198 }
199
200 static gchar *
201 forward_cite (const gchar *from,
202               const gchar *sent,
203               const gchar *to,
204               const gchar *subject)
205 {
206         return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n", 
207                                 FORWARD_STRING, 
208                                 FROM_STRING, (from)?from:"",
209                                 SENT_STRING, sent,
210                                 TO_STRING, (to)?to:"",
211                                 SUBJECT_STRING, (subject)?subject:"");
212 }
213
214 gchar * 
215 modest_text_utils_inline (const gchar *text,
216                           const gchar *content_type,
217                           const gchar *signature,
218                           const gchar *from,
219                           time_t sent_date,
220                           const gchar *to,
221                           const gchar *subject)
222 {
223         gchar sent_str[101];
224         gchar *cited;
225         gchar *retval;
226         
227         g_return_val_if_fail (text, NULL);
228         g_return_val_if_fail (content_type, NULL);
229         
230         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
231
232         cited = forward_cite (from, sent_str, to, subject);
233         
234         if (content_type && strcmp (content_type, "text/html") == 0)
235                 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
236         else
237                 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
238         
239         g_free (cited);
240         return retval;
241 }
242
243 /* just to prevent warnings:
244  * warning: `%x' yields only last 2 digits of year in some locales
245  */
246 gsize
247 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
248 {
249         struct tm tm;
250
251         /* does not work on old maemo glib: 
252          *   g_date_set_time_t (&date, timet);
253          */
254         localtime_r (&timet, &tm);
255         return strftime(s, max, fmt, &tm);
256 }
257
258 gchar *
259 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
260 {
261         gchar *tmp;
262
263         g_return_val_if_fail (prefix, NULL);
264
265         if (!subject || subject[0] == '\0')
266                 subject = _("mail_va_no_subject");
267
268         tmp = g_strchug (g_strdup (subject));
269
270         if (!strncmp (tmp, prefix, strlen (prefix))) {
271                 return tmp;
272         } else {
273                 g_free (tmp);
274                 return g_strdup_printf ("%s %s", prefix, subject);
275         }
276 }
277
278 gchar*
279 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
280 {
281         gchar *dup, *token, *ptr, *result;
282         GString *filtered_emails;
283         gchar *email_address;
284
285         g_return_val_if_fail (address_list, NULL);
286
287         if (!address)
288                 return g_strdup (address_list);
289
290         email_address = get_email_from_address (address);
291         
292         /* search for substring */
293         if (!strstr ((const char *) address_list, (const char *) email_address)) {
294                 g_free (email_address);
295                 return g_strdup (address_list);
296         }
297
298         dup = g_strdup (address_list);
299         filtered_emails = g_string_new (NULL);
300         
301         token = strtok_r (dup, ",", &ptr);
302
303         while (token != NULL) {
304                 /* Add to list if not found */
305                 if (!strstr ((const char *) token, (const char *) email_address)) {
306                         if (filtered_emails->len == 0)
307                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
308                         else
309                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
310                 }
311                 token = strtok_r (NULL, ",", &ptr);
312         }
313         result = filtered_emails->str;
314
315         /* Clean */
316         g_free (email_address);
317         g_free (dup);
318         g_string_free (filtered_emails, FALSE);
319
320         return result;
321 }
322
323 static void
324 modest_text_utils_convert_buffer_to_html (GString *html, const gchar *data)
325 {
326         guint            i;
327         gboolean        space_seen = FALSE;
328         gsize           len;
329         guint           break_dist = 0; /* distance since last break point */
330
331         len = strlen (data);
332
333         /* replace with special html chars where needed*/
334         for (i = 0; i != len; ++i)  {
335                 char kar = data[i];
336                 
337                 if (space_seen && kar != ' ') {
338                         g_string_append_c (html, ' ');
339                         space_seen = FALSE;
340                 }
341                 
342                 /* we artificially insert a breakpoint (newline)
343                  * after 256, to make sure our lines are not so long
344                  * they will DOS the regexping later
345                  */
346                 if (++break_dist == 256) {
347                         g_string_append_c (html, '\n');
348                         break_dist = 0;
349                 }
350                 
351                 switch (kar) {
352                 case 0:  break; /* ignore embedded \0s */       
353                 case '<'  : g_string_append (html, "&lt;");   break;
354                 case '>'  : g_string_append (html, "&gt;");   break;
355                 case '&'  : g_string_append (html, "&amp;");  break;
356                 case '"'  : g_string_append (html, "&quot;");  break;
357
358                 /* don't convert &apos; --> wpeditor will try to re-convert it... */    
359                 //case '\'' : g_string_append (html, "&apos;"); break;
360                 case '\n' : g_string_append (html, "<br>\n");              break_dist= 0; break;
361                 case '\t' : g_string_append (html, "&nbsp;&nbsp;&nbsp; "); break_dist=0; break; /* note the space at the end*/
362                 case ' ':
363                         break_dist = 0;
364                         if (space_seen) { /* second space in a row */
365                                 g_string_append (html, "&nbsp; ");
366                                 space_seen = FALSE;
367                         } else
368                                 space_seen = TRUE;
369                         break;
370                 default:
371                         g_string_append_c (html, kar);
372                 }
373         }
374 }
375
376 gchar*
377 modest_text_utils_convert_to_html (const gchar *data)
378 {
379         GString         *html;      
380         gsize           len;
381         
382         if (!data)
383                 return NULL;
384
385         len = strlen (data);
386         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
387
388         g_string_append_printf (html,
389                                 "<html><head>"
390                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
391                                 "</head>"
392                                 "<body>");
393
394         modest_text_utils_convert_buffer_to_html (html, data);
395         
396         g_string_append (html, "</body></html>");
397
398         if (len <= HYPERLINKIFY_MAX_LENGTH)
399                 hyperlinkify_plain_text (html);
400
401         return g_string_free (html, FALSE);
402 }
403
404 gchar *
405 modest_text_utils_convert_to_html_body (const gchar *data)
406 {
407         GString         *html;      
408         gsize           len;
409         
410         if (!data)
411                 return NULL;
412
413         len = strlen (data);
414         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
415
416         modest_text_utils_convert_buffer_to_html (html, data);
417
418         if (len < HYPERLINKIFY_MAX_LENGTH)
419                 hyperlinkify_plain_text (html);
420
421         return g_string_free (html, FALSE);
422 }
423
424 void
425 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
426 {
427         gchar *current, *start, *last_blank;
428         gint start_offset = 0, current_offset = 0;
429
430         g_return_if_fail (start_indexes != NULL);
431         g_return_if_fail (end_indexes != NULL);
432
433         start = (gchar *) addresses;
434         current = start;
435         last_blank = start;
436
437         while (*current != '\0') {
438                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
439                         start = g_utf8_next_char (start);
440                         start_offset++;
441                         last_blank = current;
442                 } else if ((*current == ',')||(*current == ';')) {
443                         gint *start_index, *end_index;
444                         start_index = g_new0(gint, 1);
445                         end_index = g_new0(gint, 1);
446                         *start_index = start_offset;
447                         *end_index = current_offset;
448                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
449                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
450                         start = g_utf8_next_char (current);
451                         start_offset = current_offset + 1;
452                         last_blank = start;
453                 } else if (*current == '"') {
454                         current = g_utf8_next_char (current);
455                         current_offset ++;
456                         while ((*current != '"')&&(*current != '\0')) {
457                                 current = g_utf8_next_char (current);
458                                 current_offset ++;
459                         }
460                 }
461                                 
462                 current = g_utf8_next_char (current);
463                 current_offset ++;
464         }
465
466         if (start != current) {
467                         gint *start_index, *end_index;
468                         start_index = g_new0(gint, 1);
469                         end_index = g_new0(gint, 1);
470                         *start_index = start_offset;
471                         *end_index = current_offset;
472                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
473                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
474         }
475         
476         *start_indexes = g_slist_reverse (*start_indexes);
477         *end_indexes = g_slist_reverse (*end_indexes);
478
479         return;
480 }
481
482 GSList *
483 modest_text_utils_split_addresses_list (const gchar *addresses)
484 {
485         gchar *current, *start, *last_blank;
486         GSList *result = NULL;
487
488         start = (gchar *) addresses;
489         current = start;
490         last_blank = start;
491
492         while (*current != '\0') {
493                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
494                         start = g_utf8_next_char (start);
495                         last_blank = current;
496                 } else if ((*current == ',')||(*current == ';')) {
497                         gchar *new_address = NULL;
498                         new_address = g_strndup (start, current - last_blank);
499                         result = g_slist_prepend (result, new_address);
500                         start = g_utf8_next_char (current);
501                         last_blank = start;
502                 } else if (*current == '\"') {
503                         if (current == start) {
504                                 current = g_utf8_next_char (current);
505                                 start = g_utf8_next_char (start);
506                         }
507                         while ((*current != '\"')&&(*current != '\0'))
508                                 current = g_utf8_next_char (current);
509                 }
510                                 
511                 current = g_utf8_next_char (current);
512         }
513
514         if (start != current) {
515                 gchar *new_address = NULL;
516                 new_address = g_strndup (start, current - last_blank);
517                 result = g_slist_prepend (result, new_address);
518         }
519
520         result = g_slist_reverse (result);
521         return result;
522
523 }
524
525 void
526 modest_text_utils_address_range_at_position (const gchar *recipients_list,
527                                              gint position,
528                                              gint *start,
529                                              gint *end)
530 {
531         gchar *current = NULL;
532         gint range_start = 0;
533         gint range_end = 0;
534         gint index;
535         gboolean is_quoted = FALSE;
536
537         index = 0;
538         for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
539                 gunichar c = g_utf8_get_char (current);
540
541                 if ((c == ',') && (!is_quoted)) {
542                         if (index < position) {
543                                 range_start = index + 1;
544                         } else {
545                                 break;
546                         }
547                 } else if (c == '\"') {
548                         is_quoted = !is_quoted;
549                 } else if ((c == ' ') &&(range_start == index)) {
550                         range_start ++;
551                 }
552                 index ++;
553                 range_end = index;
554         }
555
556         if (start)
557                 *start = range_start;
558         if (end)
559                 *end = range_end;
560 }
561
562
563 /* ******************************************************************* */
564 /* ************************* UTILIY FUNCTIONS ************************ */
565 /* ******************************************************************* */
566
567 static GString *
568 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
569 {
570         GString *gs;
571         const gchar *i0;
572         
573         if (iter > b + blen)
574                 return g_string_new("");
575         
576         i0 = iter;
577         while (iter[0]) {
578                 if (iter[0] == '\n')
579                         break;
580                 iter++;
581         }
582         gs = g_string_new_len (i0, iter - i0);
583         return gs;
584 }
585 static int
586 get_indent_level (const char *l)
587 {
588         int indent = 0;
589
590         while (l[0]) {
591                 if (l[0] == '>') {
592                         indent++;
593                         if (l[1] == ' ') {
594                                 l++;
595                         }
596                 } else {
597                         break;
598                 }
599                 l++;
600
601         }
602
603         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
604          *      stops reformatting.
605          */
606         if (strcmp (l, "-- ") == 0) {
607                 return -1 - indent;
608         } else {
609                 return indent;
610         }
611 }
612
613 static void
614 unquote_line (GString * l)
615 {
616         gchar *p;
617
618         p = l->str;
619         while (p[0]) {
620                 if (p[0] == '>') {
621                         if (p[1] == ' ') {
622                                 p++;
623                         }
624                 } else {
625                         break;
626                 }
627                 p++;
628         }
629         g_string_erase (l, 0, p - l->str);
630 }
631
632 static void
633 append_quoted (GString * buf, int indent, const GString * str,
634                const int cutpoint)
635 {
636         int i;
637
638         indent = indent < 0 ? abs (indent) - 1 : indent;
639         for (i = 0; i <= indent; i++) {
640                 g_string_append (buf, "> ");
641         }
642         if (cutpoint > 0) {
643                 g_string_append_len (buf, str->str, cutpoint);
644         } else {
645                 g_string_append (buf, str->str);
646         }
647         g_string_append (buf, "\n");
648 }
649
650 static int
651 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
652 {
653         gint index = 0;
654         const gchar *pos, *last;
655         gunichar *uni;
656
657         indent = indent < 0 ? abs (indent) - 1 : indent;
658
659         last = NULL;
660         pos = s;
661         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
662         while (pos[0]) {
663                 if ((index + 2 * indent > limit) && last) {
664                         g_free (uni);
665                         return last - s;
666                 }
667                 if (g_unichar_isspace (uni[index])) {
668                         last = pos;
669                 }
670                 pos = g_utf8_next_char (pos);
671                 index++;
672         }
673         g_free (uni);
674         return strlen (s);
675 }
676
677 static int
678 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
679 {
680         gint i, last;
681
682         last = strlen (s);
683         if (last + 2 * indent < limit)
684                 return last;
685
686         for (i = strlen (s); i > 0; i--) {
687                 if (s[i] == ' ') {
688                         if (i + 2 * indent <= limit) {
689                                 return i;
690                         } else {
691                                 last = i;
692                         }
693                 }
694         }
695         return last;
696 }
697
698 static int
699 get_breakpoint (const gchar * s, const gint indent, const gint limit)
700 {
701
702         if (g_utf8_validate (s, -1, NULL)) {
703                 return get_breakpoint_utf8 (s, indent, limit);
704         } else {                /* assume ASCII */
705                 //g_warning("invalid UTF-8 in msg");
706                 return get_breakpoint_ascii (s, indent, limit);
707         }
708 }
709
710 static gchar *
711 cite (const time_t sent_date, const gchar *from)
712 {
713         return g_strdup (_("mcen_ia_editor_original_message"));
714 }
715
716 static gchar *
717 quoted_attachments (GList *attachments)
718 {
719         GList *node = NULL;
720         GString *result = g_string_new ("");
721         for (node = attachments; node != NULL; node = g_list_next (node)) {
722                 gchar *filename = (gchar *) node->data;
723                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
724         }
725
726         return g_string_free (result, FALSE);
727
728 }
729
730 static gchar *
731 modest_text_utils_quote_plain_text (const gchar *text, 
732                                     const gchar *cite, 
733                                     const gchar *signature,
734                                     GList *attachments,
735                                     int limit)
736 {
737         const gchar *iter;
738         gint indent, breakpoint, rem_indent = 0;
739         GString *q, *l, *remaining;
740         gsize len;
741         gchar *attachments_string = NULL;
742
743         /* remaining will store the rest of the line if we have to break it */
744         q = g_string_new ("\n");
745         q = g_string_append (q, cite);
746         q = g_string_append_c (q, '\n');
747         remaining = g_string_new ("");
748
749         iter = text;
750         len = strlen(text);
751         do {
752                 l = get_next_line (text, len, iter);
753                 iter = iter + l->len + 1;
754                 indent = get_indent_level (l->str);
755                 unquote_line (l);
756
757                 if (remaining->len) {
758                         if (l->len && indent == rem_indent) {
759                                 g_string_prepend (l, " ");
760                                 g_string_prepend (l, remaining->str);
761                         } else {
762                                 do {
763                                         breakpoint =
764                                                 get_breakpoint (remaining->str,
765                                                                 rem_indent,
766                                                                 limit);
767                                         append_quoted (q, rem_indent,
768                                                        remaining, breakpoint);
769                                         g_string_erase (remaining, 0,
770                                                         breakpoint);
771                                         if (remaining->str[0] == ' ') {
772                                                 g_string_erase (remaining, 0,
773                                                                 1);
774                                         }
775                                 } while (remaining->len);
776                         }
777                 }
778                 g_string_free (remaining, TRUE);
779                 breakpoint = get_breakpoint (l->str, indent, limit);
780                 remaining = g_string_new (l->str + breakpoint);
781                 if (remaining->str[0] == ' ') {
782                         g_string_erase (remaining, 0, 1);
783                 }
784                 rem_indent = indent;
785                 append_quoted (q, indent, l, breakpoint);
786                 g_string_free (l, TRUE);
787         } while ((iter < text + len) || (remaining->str[0]));
788
789         attachments_string = quoted_attachments (attachments);
790         q = g_string_append (q, attachments_string);
791         g_free (attachments_string);
792
793         if (signature != NULL) {
794                 q = g_string_append_c (q, '\n');
795                 q = g_string_append (q, signature);
796         }
797
798         return g_string_free (q, FALSE);
799 }
800
801 static gchar*
802 modest_text_utils_quote_html (const gchar *text, 
803                               const gchar *cite, 
804                               const gchar *signature,
805                               GList *attachments,
806                               int limit)
807 {
808         gchar *result = NULL;
809         gchar *signature_result = NULL;
810         const gchar *format = \
811                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
812                 "<html>\n" \
813                 "<body>\n" \
814                 "<br/>%s<br/>" \
815                 "<pre>%s<br/>%s<br/>%s</pre>\n" \
816                 "</body>\n" \
817                 "</html>\n";
818         gchar *attachments_string = NULL;
819         gchar *q_attachments_string = NULL;
820         gchar *q_cite = NULL;
821         gchar *html_text = NULL;
822
823         if (signature == NULL)
824                 signature_result = g_strdup ("");
825         else
826                 signature_result = modest_text_utils_convert_to_html_body (signature);
827
828         attachments_string = quoted_attachments (attachments);
829         q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string);
830         q_cite = modest_text_utils_convert_to_html_body (cite);
831         html_text = modest_text_utils_convert_to_html_body (text);
832         result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
833         g_free (q_cite);
834         g_free (html_text);
835         g_free (attachments_string);
836         g_free (q_attachments_string);
837         g_free (signature_result);
838         
839         return result;
840 }
841
842 static gint 
843 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
844 {
845         return match2->offset - match1->offset;
846 }
847
848
849 static GSList*
850 get_url_matches (GString *txt)
851 {
852         regmatch_t rm;
853         guint rv, i, offset = 0;
854         GSList *match_list = NULL;
855
856         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
857         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
858
859         /* initalize the regexps */
860         for (i = 0; i != pattern_num; ++i) {
861                 patterns[i].preg = g_slice_new0 (regex_t);
862
863                 /* this should not happen */
864                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
865                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
866         }
867         /* find all the matches */
868         for (i = 0; i != pattern_num; ++i) {
869                 offset     = 0; 
870                 while (1) {
871                         url_match_t *match;
872                         gboolean is_submatch;
873                         GSList *cursor;
874                         
875                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
876                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
877                                 break; /* try next regexp */ 
878                         }
879                         if (rm.rm_so == -1)
880                                 break;
881                         
882                         is_submatch = FALSE;
883                         /* check  old matches to see if this has already been matched */
884                         cursor = match_list;
885                         while (cursor && !is_submatch) {
886                                 const url_match_t *old_match =
887                                         (const url_match_t *) cursor->data;
888                                 guint new_offset = offset + rm.rm_so;
889                                 is_submatch = (new_offset >  old_match->offset &&
890                                                new_offset <  old_match->offset + old_match->len);
891                                 cursor = g_slist_next (cursor);
892                         }
893
894                         if (!is_submatch) {
895                                 /* make a list of our matches (<offset, len, prefix> tupels)*/
896                                 match = g_slice_new (url_match_t);
897                                 match->offset = offset + rm.rm_so;
898                                 match->len    = rm.rm_eo - rm.rm_so;
899                                 match->prefix = patterns[i].prefix;
900                                 match_list = g_slist_prepend (match_list, match);
901                         }
902                                 
903                         offset += rm.rm_eo;
904                 }
905         }
906
907         for (i = 0; i != pattern_num; ++i) {
908                 regfree (patterns[i].preg);
909                 g_slice_free  (regex_t, patterns[i].preg);
910         } /* don't free patterns itself -- it's static */
911         
912         /* now sort the list, so the matches are in reverse order of occurence.
913          * that way, we can do the replacements starting from the end, so we don't need
914          * to recalculate the offsets
915          */
916         match_list = g_slist_sort (match_list,
917                                    (GCompareFunc)cmp_offsets_reverse); 
918         return match_list;      
919 }
920
921
922
923 static void
924 hyperlinkify_plain_text (GString *txt)
925 {
926         GSList *cursor;
927         GSList *match_list = get_url_matches (txt);
928
929         /* we will work backwards, so the offsets stay valid */
930         for (cursor = match_list; cursor; cursor = cursor->next) {
931
932                 url_match_t *match = (url_match_t*) cursor->data;
933                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
934                 gchar *repl = NULL; /* replacement  */
935
936                 /* the prefix is NULL: use the one that is already there */
937                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
938                                         match->prefix ? match->prefix : EMPTY_STRING, 
939                                         url, url);
940
941                 /* replace the old thing with our hyperlink
942                  * replacement thing */
943                 g_string_erase  (txt, match->offset, match->len);
944                 g_string_insert (txt, match->offset, repl);
945                 
946                 g_free (url);
947                 g_free (repl);
948
949                 g_slice_free (url_match_t, match);      
950         }
951         
952         g_slist_free (match_list);
953 }
954
955
956 gchar*
957 modest_text_utils_get_display_address (const gchar *address)
958 {
959         gchar *display;
960         gchar **tokens;
961         gint i = 0;
962         
963         if (!address)
964                 return NULL;
965
966         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
967         
968         tokens = g_strsplit_set ((const gchar*) address, "<>()", 3);
969
970         /* Note that if any of the delimiters is the first character
971            then g_strsplit_set will return "" as the first string */
972         while (tokens[i] != NULL) {
973                 if (strlen ((char *) (tokens[i])) != 0)
974                         break;
975                 i++;
976         }
977
978         display = g_strdup (tokens [i]);
979         g_strchug (display);
980
981         /* Free the other tokens */
982         g_strfreev (tokens);
983
984         return display;
985 }
986
987 gchar *
988 modest_text_utils_get_email_address (const gchar *full_address)
989 {
990         const gchar *left, *right;
991         
992         if (!full_address)
993                 return NULL;
994         
995         g_return_val_if_fail (g_utf8_validate (full_address, -1, NULL), NULL);
996         
997         left = g_strrstr_len (full_address, strlen(full_address), "<");
998         if (left == NULL)
999                 return g_strdup (full_address);
1000
1001         right = g_strstr_len (left, strlen(left), ">");
1002         if (right == NULL)
1003                 return g_strdup (full_address);
1004
1005         return g_strndup (left + 1, right - left - 1);
1006 }
1007
1008 gint 
1009 modest_text_utils_get_subject_prefix_len (const gchar *sub)
1010 {
1011         gint i;
1012         static const gchar* prefix[] = {
1013                 "Re:", "RE:", "RV:", "re:"
1014                 "Fwd:", "FWD:", "FW:", "fwd:", "Fw:", "fw:", NULL
1015         };
1016                 
1017         if (!sub || (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')) /* optimization */
1018                 return 0;
1019
1020         i = 0;
1021         
1022         while (prefix[i]) {
1023                 if (g_str_has_prefix(sub, prefix[i])) {
1024                         int prefix_len = strlen(prefix[i]); 
1025                         if (sub[prefix_len] == ' ')
1026                                 ++prefix_len; /* ignore space after prefix as well */
1027                         return prefix_len; 
1028                 }
1029                 ++i;
1030         }
1031         return 0;
1032 }
1033
1034
1035 gint
1036 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
1037 {
1038         gint result = 0;
1039         gchar *n1, *n2;
1040
1041         /* work even when s1 and/or s2 == NULL */
1042         if (G_UNLIKELY(s1 == s2))
1043                 return 0;
1044
1045         /* if it's not case sensitive */
1046         if (!insensitive)
1047                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
1048         
1049         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
1050         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
1051         
1052         result = strcmp (n1, n2);
1053
1054         g_free (n1);
1055         g_free (n2);
1056         
1057         return result;
1058 }
1059
1060
1061 gchar*
1062 modest_text_utils_get_display_date (time_t date)
1063 {
1064         time_t now;
1065         static const guint BUF_SIZE = 64; 
1066         static const guint ONE_DAY = 24 * 60 * 60; /* seconds in one day */
1067         gchar date_buf[BUF_SIZE];  
1068         gchar today_buf [BUF_SIZE];  
1069
1070         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date); 
1071
1072         now = time (NULL);
1073
1074         /* we check if the date is within the last 24h, if not, we don't
1075          * have to do the extra, expensive strftime, which was very visible
1076          * in the profiles.
1077          */
1078         if (abs(now - date) < ONE_DAY) {
1079                 
1080                 /* it's within the last 24 hours, but double check */
1081                 /* use the localized dates */
1082                 modest_text_utils_strftime (today_buf,  BUF_SIZE, "%x", now); 
1083
1084                 /* if it's today, use the time instead */
1085                 if (strcmp (date_buf, today_buf) == 0)
1086                         modest_text_utils_strftime (date_buf, BUF_SIZE, "%X", date);
1087         }
1088         
1089         return g_strdup(date_buf);
1090 }
1091
1092
1093 gboolean
1094 modest_text_utils_validate_folder_name (const gchar *folder_name)
1095 {
1096         /* based on http://msdn2.microsoft.com/en-us/library/aa365247.aspx,
1097          * with some extras */
1098         
1099         guint len;
1100         gint i;
1101         const gchar **cursor = NULL;
1102         const gchar *forbidden_names[] = { /* windows does not like these */
1103                 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
1104                 "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
1105                 ".", "..", NULL
1106         };
1107         
1108         /* cannot be NULL */
1109         if (!folder_name) 
1110                 return FALSE;
1111
1112         /* cannot be empty */
1113         len = strlen(folder_name);
1114         if (len == 0)
1115                 return FALSE;
1116         
1117         /* cannot start or end with a space */
1118         if (g_ascii_isspace(folder_name[0]) || g_ascii_isspace(folder_name[len - 1]))
1119                 return FALSE; 
1120
1121         /* cannot contain a forbidden char */   
1122         for (i = 0; i < len; i++)
1123                 if (modest_text_utils_is_forbidden_char (folder_name[i], FOLDER_NAME_FORBIDDEN_CHARS))
1124                         return FALSE;
1125         
1126         /* cannot contain a forbidden word */
1127         if (len <= 4) {
1128                 for (cursor = forbidden_names; cursor && *cursor; ++cursor) {
1129                         if (g_ascii_strcasecmp (folder_name, *cursor) == 0)
1130                                 return FALSE;
1131                 }
1132         }
1133         return TRUE; /* it's valid! */
1134 }
1135
1136
1137
1138 gboolean
1139 modest_text_utils_validate_domain_name (const gchar *domain)
1140 {
1141         gboolean valid = FALSE;
1142         regex_t rx;
1143         const gchar* domain_regex = "^[a-z0-9]([.]?[a-z0-9-])*[a-z0-9]$";
1144
1145         if (!domain)
1146                 return FALSE;
1147         
1148         /* domain name: all alphanum or '-' or '.',
1149          * but beginning/ending in alphanum */  
1150         if (regcomp (&rx, domain_regex, REG_ICASE|REG_EXTENDED|REG_NOSUB)) {
1151                 g_warning ("BUG: error in regexp");
1152                 return FALSE;
1153         }
1154         
1155         valid = (regexec (&rx, domain, 1, NULL, 0) == 0);
1156         regfree (&rx);
1157                 
1158         return valid;
1159 }
1160
1161
1162
1163 gboolean
1164 modest_text_utils_validate_email_address (const gchar *email_address, const gchar **invalid_char_position)
1165 {
1166         int count = 0;
1167         const gchar *c = NULL, *domain = NULL;
1168         static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1169
1170         if (invalid_char_position != NULL)
1171                 *invalid_char_position = NULL;
1172         
1173         /* check that the email adress contains exactly one @ */
1174         if (!strstr(email_address, "@") || 
1175                         (strstr(email_address, "@") != g_strrstr(email_address, "@")))
1176         {
1177                 return FALSE;
1178         }
1179         
1180         /* first we validate the name portion (name@domain) */
1181         for (c = email_address;  *c;  c++) {
1182                 if (*c == '\"' && 
1183                     (c == email_address || 
1184                      *(c - 1) == '.' || 
1185                      *(c - 1) == '\"')) {
1186                         while (*++c) {
1187                                 if (*c == '\"') 
1188                                         break;
1189                                 if (*c == '\\' && (*++c == ' ')) 
1190                                         continue;
1191                                 if (*c <= ' ' || *c >= 127) 
1192                                         return FALSE;
1193                         }
1194                         if (!*c++) 
1195                                 return FALSE;
1196                         if (*c == '@') 
1197                                 break;
1198                         if (*c != '.') 
1199                                 return FALSE;
1200                         continue;
1201                 }
1202                 if (*c == '@') 
1203                         break;
1204                 if (*c <= ' ' || *c >= 127) 
1205                         return FALSE;
1206                 if (strchr(rfc822_specials, *c)) {
1207                         if (invalid_char_position)
1208                                 *invalid_char_position = c;
1209                         return FALSE;
1210                 }
1211         }
1212         if (c == email_address || *(c - 1) == '.') 
1213                 return FALSE;
1214
1215         /* next we validate the domain portion (name@domain) */
1216         if (!*(domain = ++c)) 
1217                 return FALSE;
1218         do {
1219                 if (*c == '.') {
1220                         if (c == domain || *(c - 1) == '.' || *(c + 1) == '\0') 
1221                                 return FALSE;
1222                         count++;
1223                 }
1224                 if (*c <= ' ' || *c >= 127) 
1225                         return FALSE;
1226                 if (strchr(rfc822_specials, *c)) {
1227                         if (invalid_char_position)
1228                                 *invalid_char_position = c;
1229                         return FALSE;
1230                 }
1231         } while (*++c);
1232
1233         return (count >= 1) ? TRUE : FALSE;
1234 }
1235
1236 gboolean 
1237 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1238 {
1239         gchar *stripped, *current;
1240         gchar *right_part;
1241         gboolean has_error = FALSE;
1242
1243         if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1244                 return TRUE;
1245         stripped = g_strdup (recipient);
1246         stripped = g_strstrip (stripped);
1247         current = stripped;
1248
1249         if (*current == '\0') {
1250                 g_free (stripped);
1251                 return FALSE;
1252         }
1253
1254         /* quoted string */
1255         if (*current == '\"') {
1256                 current = g_utf8_next_char (current);
1257                 has_error = TRUE;
1258                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1259                         if (*current == '\\') {
1260                                 /* TODO: This causes a warning, which breaks the build, 
1261                                  * because a gchar cannot be < 0.
1262                                  * murrayc. 
1263                                 if (current[1] <0) {
1264                                         has_error = TRUE;
1265                                         break;
1266                                 }
1267                                 */
1268                         } else if (*current == '\"') {
1269                                 has_error = FALSE;
1270                                 current = g_utf8_next_char (current);
1271                                 break;
1272                         }
1273                 }
1274         } else {
1275                 has_error = TRUE;
1276                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1277                         if (*current == '<') {
1278                                 has_error = FALSE;
1279                                 break;
1280                         }
1281                 }
1282         }
1283                 
1284         if (has_error) {
1285                 g_free (stripped);
1286                 return FALSE;
1287         }
1288
1289         right_part = g_strdup (current);
1290         g_free (stripped);
1291         right_part = g_strstrip (right_part);
1292
1293         if (g_str_has_prefix (right_part, "<") &&
1294             g_str_has_suffix (right_part, ">")) {
1295                 gchar *address;
1296                 gboolean valid;
1297
1298                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1299                 g_free (right_part);
1300                 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1301                 g_free (address);
1302                 return valid;
1303         } else {
1304                 g_free (right_part);
1305                 return FALSE;
1306         }
1307 }
1308
1309
1310 gchar *
1311 modest_text_utils_get_display_size (guint64 size)
1312 {
1313         const guint KB=1024;
1314         const guint MB=1024 * KB;
1315         const guint GB=1024 * MB;
1316
1317         if (size == 0)
1318                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1319         if (0 < size && size < KB)
1320                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1321         else if (KB <= size && size < 100 * KB)
1322                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1323         else if (100*KB <= size && size < MB)
1324                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1325         else if (MB <= size && size < 10*MB)
1326                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1327         else if (10*MB <= size && size < GB)
1328                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1329         else
1330                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1331 }
1332
1333 static gchar *
1334 get_email_from_address (const gchar * address)
1335 {
1336         gchar *left_limit, *right_limit;
1337
1338         left_limit = strstr (address, "<");
1339         right_limit = g_strrstr (address, ">");
1340
1341         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1342                 return g_strdup (address);
1343         else
1344                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1345 }
1346
1347 gchar *      
1348 modest_text_utils_get_color_string (GdkColor *color)
1349 {
1350
1351         return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1352                                 (color->red >> 12)   & 0xf, (color->red >> 8)   & 0xf,
1353                                 (color->red >>  4)   & 0xf, (color->red)        & 0xf,
1354                                 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1355                                 (color->green >>  4) & 0xf, (color->green)      & 0xf,
1356                                 (color->blue >> 12)  & 0xf, (color->blue >> 8)  & 0xf,
1357                                 (color->blue >>  4)  & 0xf, (color->blue)       & 0xf);
1358 }
1359
1360 gchar *
1361 modest_text_utils_text_buffer_get_text (GtkTextBuffer *buffer)
1362 {
1363         GtkTextIter start, end;
1364         gchar *slice, *current;
1365         GString *result = g_string_new ("");
1366
1367         g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1368
1369         gtk_text_buffer_get_start_iter (buffer, &start);
1370         gtk_text_buffer_get_end_iter (buffer, &end);
1371
1372         slice = gtk_text_buffer_get_slice (buffer, &start, &end, FALSE);
1373         current = slice;
1374
1375         while (current && current != '\0') {
1376                 if (g_utf8_get_char (current) == 0xFFFC) {
1377                         result = g_string_append_c (result, ' ');
1378                         current = g_utf8_next_char (current);
1379                 } else {
1380                         gchar *next = g_utf8_strchr (current, -1, 0xFFFC);
1381                         if (next == NULL) {
1382                                 result = g_string_append (result, current);
1383                         } else {
1384                                 result = g_string_append_len (result, current, next - current);
1385                         }
1386                         current = next;
1387                 }
1388         }
1389         g_free (slice);
1390
1391         return g_string_free (result, FALSE);
1392         
1393 }
1394
1395 gboolean
1396 modest_text_utils_is_forbidden_char (const gchar character,
1397                                      ModestTextUtilsForbiddenCharType type)
1398 {
1399         gint i, len;
1400         const gchar *forbidden_chars = NULL;
1401         
1402         /* We need to get the length in the switch because the
1403            compiler needs to know the size at compile time */
1404         switch (type) {
1405         case ACCOUNT_TITLE_FORBIDDEN_CHARS:
1406                 forbidden_chars = account_title_forbidden_chars;
1407                 len = G_N_ELEMENTS (account_title_forbidden_chars);
1408                 break;
1409         case FOLDER_NAME_FORBIDDEN_CHARS:
1410                 forbidden_chars = folder_name_forbidden_chars;
1411                 len = G_N_ELEMENTS (folder_name_forbidden_chars);
1412                 break;
1413         case USER_NAME_FORBIDDEN_NAMES:
1414                 forbidden_chars = user_name_forbidden_chars;
1415                 len = G_N_ELEMENTS (user_name_forbidden_chars);
1416                 break;
1417         default:
1418                 g_return_val_if_reached (TRUE);
1419         }
1420
1421         for (i = 0; i < len ; i++)
1422                 if (forbidden_chars[i] == character)
1423                         return TRUE;
1424
1425         return FALSE; /* it's valid! */
1426 }