* src/modest-text-utils.c:
[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 #include <glib.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <glib/gi18n.h>
35 #include <regex.h>
36 #include <modest-tny-platform-factory.h>
37 #include <modest-text-utils.h>
38 #include <modest-runtime.h>
39
40
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif /*HAVE_CONFIG_H */
44
45 /* defines */
46 #define FORWARD_STRING _("-----Forwarded Message-----")
47 #define FROM_STRING _("From:")
48 #define SENT_STRING _("Sent:")
49 #define TO_STRING _("To:")
50 #define SUBJECT_STRING _("Subject:")
51 #define EMPTY_STRING ""
52
53 /*
54  * we need these regexps to find URLs in plain text e-mails
55  */
56 typedef struct _url_match_pattern_t url_match_pattern_t;
57 struct _url_match_pattern_t {
58         gchar   *regex;
59         regex_t *preg;
60         gchar   *prefix;
61 };
62
63 typedef struct _url_match_t url_match_t;
64 struct _url_match_t {
65         guint offset;
66         guint len;
67         const gchar* prefix;
68 };
69
70 #define MAIL_VIEWER_URL_MATCH_PATTERNS  {                               \
71         { "(file|rtsp|http|ftp|https)://[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]+[-A-Za-z0-9_$%&=?/~#]",\
72           NULL, NULL },\
73         { "www\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
74           NULL, "http://" },\
75         { "ftp\\.[-a-z0-9.]+[-a-z0-9](:[0-9]*)?(/[-A-Za-z0-9_$.+!*(),;:@%&=?/~#]*[^]}\\),?!;:\"]?)?",\
76           NULL, "ftp://" },\
77         { "(voipto|callto|chatto|jabberto|xmpp):[-_a-z@0-9.\\+]+", \
78            NULL, NULL},                                             \
79         { "mailto:[-_a-z0-9.\\+]+@[-_a-z0-9.]+",                    \
80           NULL, NULL},\
81         { "[-_a-z0-9.\\+]+@[-_a-z0-9.]+",\
82           NULL, "mailto:"}\
83         }
84
85 /* private */
86 static gchar*   cite                    (const time_t sent_date, const gchar *from);
87 static void     hyperlinkify_plain_text (GString *txt);
88 static gint     cmp_offsets_reverse     (const url_match_t *match1, const url_match_t *match2);
89 static void     chk_partial_match       (const url_match_t *match, guint* offset);
90 static GSList*  get_url_matches         (GString *txt);
91
92 static GString* get_next_line           (const char *b, const gsize blen, const gchar * iter);
93 static int      get_indent_level        (const char *l);
94 static void     unquote_line            (GString * l);
95 static void     append_quoted           (GString * buf, const int indent, const GString * str, 
96                                          const int cutpoint);
97 static int      get_breakpoint_utf8     (const gchar * s, const gint indent, const gint limit);
98 static int      get_breakpoint_ascii    (const gchar * s, const gint indent, const gint limit);
99 static int      get_breakpoint          (const gchar * s, const gint indent, const gint limit);
100
101 static gchar*   modest_text_utils_quote_plain_text (const gchar *text, 
102                                                     const gchar *cite, 
103                                                     const gchar *signature,
104                                                     GList *attachments, 
105                                                     int limit);
106
107 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
108                                                     const gchar *cite,
109                                                     const gchar *signature,
110                                                     GList *attachments,
111                                                     int limit);
112 static gchar*   get_email_from_address (const gchar *address);
113
114
115 /* ******************************************************************* */
116 /* ************************* PUBLIC FUNCTIONS ************************ */
117 /* ******************************************************************* */
118
119 gchar *
120 modest_text_utils_quote (const gchar *text, 
121                          const gchar *content_type,
122                          const gchar *signature,
123                          const gchar *from,
124                          const time_t sent_date, 
125                          GList *attachments,
126                          int limit)
127 {
128         gchar *retval, *cited;
129
130         g_return_val_if_fail (text, NULL);
131         g_return_val_if_fail (content_type, NULL);
132
133         cited = cite (sent_date, from);
134         
135         if (content_type && strcmp (content_type, "text/html") == 0)
136                 /* TODO: extract the <body> of the HTML and pass it to
137                    the function */
138                 retval = modest_text_utils_quote_html (text, cited, signature, attachments, limit);
139         else
140                 retval = modest_text_utils_quote_plain_text (text, cited, signature, attachments, limit);
141         
142         g_free (cited);
143         
144         return retval;
145 }
146
147
148 gchar *
149 modest_text_utils_cite (const gchar *text,
150                         const gchar *content_type,
151                         const gchar *signature,
152                         const gchar *from,
153                         time_t sent_date)
154 {
155         gchar *retval;
156         gchar *tmp_sig;
157
158         g_return_val_if_fail (text, NULL);
159         g_return_val_if_fail (content_type, NULL);
160
161         if (!signature)
162                 retval = g_strdup ("");
163         else if (!strcmp(content_type, "text/html")) {
164                 tmp_sig = g_strconcat ("\n", signature, NULL);
165                 retval = modest_text_utils_convert_to_html_body(tmp_sig);
166                 g_free (tmp_sig);
167         } else {
168                 retval = g_strconcat ("\n", signature, NULL);
169         }
170
171         return retval;
172 }
173
174 static gchar *
175 forward_cite (const gchar *from,
176                     const gchar *sent,
177                     const gchar *to,
178                     const gchar *subject)
179 {
180         return g_strdup_printf ("%s\n%s %s\n%s %s\n%s %s\n%s %s\n", 
181                                 FORWARD_STRING, 
182                                 FROM_STRING, (from)?from:"",
183                                 SENT_STRING, sent,
184                                 TO_STRING, (to)?to:"",
185                                 SUBJECT_STRING, (subject)?subject:"");
186 }
187
188 gchar * 
189 modest_text_utils_inline (const gchar *text,
190                           const gchar *content_type,
191                           const gchar *signature,
192                           const gchar *from,
193                           time_t sent_date,
194                           const gchar *to,
195                           const gchar *subject)
196 {
197         gchar sent_str[101];
198         gchar *cited;
199         gchar *retval;
200         
201         g_return_val_if_fail (text, NULL);
202         g_return_val_if_fail (content_type, NULL);
203         
204         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
205
206         cited = forward_cite (from, sent_str, to, subject);
207         
208         if (content_type && strcmp (content_type, "text/html") == 0)
209                 retval = modest_text_utils_quote_html (text, cited, signature, NULL, 80);
210         else
211                 retval = modest_text_utils_quote_plain_text (text, cited, signature, NULL, 80);
212         
213         g_free (cited);
214         return retval;
215 }
216
217 /* just to prevent warnings:
218  * warning: `%x' yields only last 2 digits of year in some locales
219  */
220 gsize
221 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
222 {
223         struct tm tm;
224
225         /* does not work on old maemo glib: 
226          *   g_date_set_time_t (&date, timet);
227          */
228         localtime_r (&timet, &tm);
229         return strftime(s, max, fmt, &tm);
230 }
231
232 gchar *
233 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
234 {
235         gchar *tmp;
236
237         g_return_val_if_fail (prefix, NULL);
238         
239         if (!subject)
240                 return g_strdup (prefix);
241
242         tmp = g_strchug (g_strdup (subject));
243
244         if (!strncmp (tmp, prefix, strlen (prefix))) {
245                 return tmp;
246         } else {
247                 g_free (tmp);
248                 return g_strdup_printf ("%s %s", prefix, subject);
249         }
250 }
251
252 gchar*
253 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
254 {
255         gchar *dup, *token, *ptr, *result;
256         GString *filtered_emails;
257         gchar *email_address;
258
259         g_return_val_if_fail (address_list, NULL);
260
261         if (!address)
262                 return g_strdup (address_list);
263
264         email_address = get_email_from_address (address);
265         
266         /* search for substring */
267         if (!strstr ((const char *) address_list, (const char *) email_address)) {
268                 g_free (email_address);
269                 return g_strdup (address_list);
270         }
271
272         dup = g_strdup (address_list);
273         filtered_emails = g_string_new (NULL);
274         
275         token = strtok_r (dup, ",", &ptr);
276
277         while (token != NULL) {
278                 /* Add to list if not found */
279                 if (!strstr ((const char *) token, (const char *) email_address)) {
280                         if (filtered_emails->len == 0)
281                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
282                         else
283                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
284                 }
285                 token = strtok_r (NULL, ",", &ptr);
286         }
287         result = filtered_emails->str;
288
289         /* Clean */
290         g_free (email_address);
291         g_free (dup);
292         g_string_free (filtered_emails, FALSE);
293
294         return result;
295 }
296
297 static void
298 modest_text_utils_convert_buffer_to_html (GString *html, const gchar *data)
299 {
300         guint            i;
301         gboolean        space_seen = FALSE;
302         gsize           len;
303
304         len = strlen (data);
305
306         /* replace with special html chars where needed*/
307         for (i = 0; i != len; ++i)  {
308                 char kar = data[i];
309                 
310                 if (space_seen && kar != ' ') {
311                         g_string_append_c (html, ' ');
312                         space_seen = FALSE;
313                 }
314                 
315                 switch (kar) {
316                 case 0:  break; /* ignore embedded \0s */       
317                 case '<'  : g_string_append (html, "&lt;");   break;
318                 case '>'  : g_string_append (html, "&gt;");   break;
319                 case '&'  : g_string_append (html, "&amp;");  break;
320                 case '"'  : g_string_append (html, "&quot;");  break;
321                 case '\'' : g_string_append (html, "&apos;"); break;
322                 case '\n' : g_string_append (html, "<br>\n");  break;
323                 case '\t' : g_string_append (html, "&nbsp;&nbsp;&nbsp; "); break; /* note the space at the end*/
324                 case ' ':
325                         if (space_seen) { /* second space in a row */
326                                 g_string_append (html, "&nbsp; ");
327                                 space_seen = FALSE;
328                         } else
329                                 space_seen = TRUE;
330                         break;
331                 default:
332                         g_string_append_c (html, kar);
333                 }
334         }
335 }
336
337 gchar*
338 modest_text_utils_convert_to_html (const gchar *data)
339 {
340         GString         *html;      
341         gsize           len;
342         
343         if (!data)
344                 return NULL;
345
346         len = strlen (data);
347         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
348
349         g_string_append_printf (html,
350                                 "<html><head>"
351                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
352                                 "</head>"
353                                 "<body>");
354
355         modest_text_utils_convert_buffer_to_html (html, data);
356         
357         g_string_append (html, "</body></html>");
358         hyperlinkify_plain_text (html);
359
360         return g_string_free (html, FALSE);
361 }
362
363 gchar *
364 modest_text_utils_convert_to_html_body (const gchar *data)
365 {
366         GString         *html;      
367         gsize           len;
368         
369         if (!data)
370                 return NULL;
371
372         len = strlen (data);
373         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
374
375         modest_text_utils_convert_buffer_to_html (html, data);
376
377         hyperlinkify_plain_text (html);
378
379         return g_string_free (html, FALSE);
380 }
381
382 void
383 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
384 {
385         gchar *current, *start, *last_blank;
386         gint start_offset = 0, current_offset = 0;
387
388         g_return_if_fail (start_indexes != NULL);
389         g_return_if_fail (end_indexes != NULL);
390
391         start = (gchar *) addresses;
392         current = start;
393         last_blank = start;
394
395         while (*current != '\0') {
396                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
397                         start = g_utf8_next_char (start);
398                         start_offset++;
399                         last_blank = current;
400                 } else if ((*current == ',')||(*current == ';')) {
401                         gint *start_index, *end_index;
402                         start_index = g_new0(gint, 1);
403                         end_index = g_new0(gint, 1);
404                         *start_index = start_offset;
405                         *end_index = current_offset;
406                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
407                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
408                         start = g_utf8_next_char (current);
409                         start_offset = current_offset + 1;
410                         last_blank = start;
411                 } else if (*current == '"') {
412                         current = g_utf8_next_char (current);
413                         current_offset ++;
414                         while ((*current != '"')&&(*current != '\0')) {
415                                 current = g_utf8_next_char (current);
416                                 current_offset ++;
417                         }
418                 }
419                                 
420                 current = g_utf8_next_char (current);
421                 current_offset ++;
422         }
423
424         if (start != current) {
425                         gint *start_index, *end_index;
426                         start_index = g_new0(gint, 1);
427                         end_index = g_new0(gint, 1);
428                         *start_index = start_offset;
429                         *end_index = current_offset;
430                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
431                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
432         }
433         
434         *start_indexes = g_slist_reverse (*start_indexes);
435         *end_indexes = g_slist_reverse (*end_indexes);
436
437         return;
438 }
439
440 GSList *
441 modest_text_utils_split_addresses_list (const gchar *addresses)
442 {
443         gchar *current, *start, *last_blank;
444         GSList *result = NULL;
445
446         start = (gchar *) addresses;
447         current = start;
448         last_blank = start;
449
450         while (*current != '\0') {
451                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
452                         start = g_utf8_next_char (start);
453                         last_blank = current;
454                 } else if ((*current == ',')||(*current == ';')) {
455                         gchar *new_address = NULL;
456                         new_address = g_strndup (start, current - last_blank);
457                         result = g_slist_prepend (result, new_address);
458                         start = g_utf8_next_char (current);
459                         last_blank = start;
460                 } else if (*current == '\"') {
461                         if (current == start) {
462                                 current = g_utf8_next_char (current);
463                                 start = g_utf8_next_char (start);
464                         }
465                         while ((*current != '\"')&&(*current != '\0'))
466                                 current = g_utf8_next_char (current);
467                 }
468                                 
469                 current = g_utf8_next_char (current);
470         }
471
472         if (start != current) {
473                 gchar *new_address = NULL;
474                 new_address = g_strndup (start, current - last_blank);
475                 result = g_slist_prepend (result, new_address);
476         }
477
478         result = g_slist_reverse (result);
479         return result;
480
481 }
482
483 void
484 modest_text_utils_address_range_at_position (const gchar *recipients_list,
485                                              gint position,
486                                              gint *start,
487                                              gint *end)
488 {
489         gchar *current = NULL;
490         gint range_start = 0;
491         gint range_end = 0;
492         gint index;
493         gboolean is_quoted = FALSE;
494
495         index = 0;
496         for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
497                 gunichar c = g_utf8_get_char (current);
498
499                 if ((c == ',') && (!is_quoted)) {
500                         if (index < position) {
501                                 range_start = index + 1;
502                         } else {
503                                 break;
504                         }
505                 } else if (c == '\"') {
506                         is_quoted = !is_quoted;
507                 } else if ((c == ' ') &&(range_start == index)) {
508                         range_start ++;
509                 }
510                 index ++;
511                 range_end = index;
512         }
513
514         if (start)
515                 *start = range_start;
516         if (end)
517                 *end = range_end;
518 }
519
520
521 /* ******************************************************************* */
522 /* ************************* UTILIY FUNCTIONS ************************ */
523 /* ******************************************************************* */
524
525 static GString *
526 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
527 {
528         GString *gs;
529         const gchar *i0;
530         
531         if (iter > b + blen)
532                 return g_string_new("");
533         
534         i0 = iter;
535         while (iter[0]) {
536                 if (iter[0] == '\n')
537                         break;
538                 iter++;
539         }
540         gs = g_string_new_len (i0, iter - i0);
541         return gs;
542 }
543 static int
544 get_indent_level (const char *l)
545 {
546         int indent = 0;
547
548         while (l[0]) {
549                 if (l[0] == '>') {
550                         indent++;
551                         if (l[1] == ' ') {
552                                 l++;
553                         }
554                 } else {
555                         break;
556                 }
557                 l++;
558
559         }
560
561         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
562          *      stops reformatting.
563          */
564         if (strcmp (l, "-- ") == 0) {
565                 return -1 - indent;
566         } else {
567                 return indent;
568         }
569 }
570
571 static void
572 unquote_line (GString * l)
573 {
574         gchar *p;
575
576         p = l->str;
577         while (p[0]) {
578                 if (p[0] == '>') {
579                         if (p[1] == ' ') {
580                                 p++;
581                         }
582                 } else {
583                         break;
584                 }
585                 p++;
586         }
587         g_string_erase (l, 0, p - l->str);
588 }
589
590 static void
591 append_quoted (GString * buf, int indent, const GString * str,
592                const int cutpoint)
593 {
594         int i;
595
596         indent = indent < 0 ? abs (indent) - 1 : indent;
597         for (i = 0; i <= indent; i++) {
598                 g_string_append (buf, "> ");
599         }
600         if (cutpoint > 0) {
601                 g_string_append_len (buf, str->str, cutpoint);
602         } else {
603                 g_string_append (buf, str->str);
604         }
605         g_string_append (buf, "\n");
606 }
607
608 static int
609 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
610 {
611         gint index = 0;
612         const gchar *pos, *last;
613         gunichar *uni;
614
615         indent = indent < 0 ? abs (indent) - 1 : indent;
616
617         last = NULL;
618         pos = s;
619         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
620         while (pos[0]) {
621                 if ((index + 2 * indent > limit) && last) {
622                         g_free (uni);
623                         return last - s;
624                 }
625                 if (g_unichar_isspace (uni[index])) {
626                         last = pos;
627                 }
628                 pos = g_utf8_next_char (pos);
629                 index++;
630         }
631         g_free (uni);
632         return strlen (s);
633 }
634
635 static int
636 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
637 {
638         gint i, last;
639
640         last = strlen (s);
641         if (last + 2 * indent < limit)
642                 return last;
643
644         for (i = strlen (s); i > 0; i--) {
645                 if (s[i] == ' ') {
646                         if (i + 2 * indent <= limit) {
647                                 return i;
648                         } else {
649                                 last = i;
650                         }
651                 }
652         }
653         return last;
654 }
655
656 static int
657 get_breakpoint (const gchar * s, const gint indent, const gint limit)
658 {
659
660         if (g_utf8_validate (s, -1, NULL)) {
661                 return get_breakpoint_utf8 (s, indent, limit);
662         } else {                /* assume ASCII */
663                 //g_warning("invalid UTF-8 in msg");
664                 return get_breakpoint_ascii (s, indent, limit);
665         }
666 }
667
668 static gchar *
669 cite (const time_t sent_date, const gchar *from)
670 {
671         return g_strdup (_("mcen_ia_editor_original_message"));
672 }
673
674 static gchar *
675 quoted_attachments (GList *attachments)
676 {
677         GList *node = NULL;
678         GString *result = g_string_new ("");
679         for (node = attachments; node != NULL; node = g_list_next (node)) {
680                 gchar *filename = (gchar *) node->data;
681                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
682         }
683
684         return g_string_free (result, FALSE);
685
686 }
687
688 static gchar *
689 modest_text_utils_quote_plain_text (const gchar *text, 
690                                     const gchar *cite, 
691                                     const gchar *signature,
692                                     GList *attachments,
693                                     int limit)
694 {
695         const gchar *iter;
696         gint indent, breakpoint, rem_indent = 0;
697         GString *q, *l, *remaining;
698         gsize len;
699         gchar *attachments_string = NULL;
700
701         /* remaining will store the rest of the line if we have to break it */
702         q = g_string_new ("\n");
703         q = g_string_append (q, cite);
704         q = g_string_append_c (q, '\n');
705         remaining = g_string_new ("");
706
707         iter = text;
708         len = strlen(text);
709         do {
710                 l = get_next_line (text, len, iter);
711                 iter = iter + l->len + 1;
712                 indent = get_indent_level (l->str);
713                 unquote_line (l);
714
715                 if (remaining->len) {
716                         if (l->len && indent == rem_indent) {
717                                 g_string_prepend (l, " ");
718                                 g_string_prepend (l, remaining->str);
719                         } else {
720                                 do {
721                                         breakpoint =
722                                                 get_breakpoint (remaining->str,
723                                                                 rem_indent,
724                                                                 limit);
725                                         append_quoted (q, rem_indent,
726                                                        remaining, breakpoint);
727                                         g_string_erase (remaining, 0,
728                                                         breakpoint);
729                                         if (remaining->str[0] == ' ') {
730                                                 g_string_erase (remaining, 0,
731                                                                 1);
732                                         }
733                                 } while (remaining->len);
734                         }
735                 }
736                 g_string_free (remaining, TRUE);
737                 breakpoint = get_breakpoint (l->str, indent, limit);
738                 remaining = g_string_new (l->str + breakpoint);
739                 if (remaining->str[0] == ' ') {
740                         g_string_erase (remaining, 0, 1);
741                 }
742                 rem_indent = indent;
743                 append_quoted (q, indent, l, breakpoint);
744                 g_string_free (l, TRUE);
745         } while ((iter < text + len) || (remaining->str[0]));
746
747         attachments_string = quoted_attachments (attachments);
748         q = g_string_append (q, attachments_string);
749         g_free (attachments_string);
750
751         if (signature != NULL) {
752                 q = g_string_append_c (q, '\n');
753                 q = g_string_append (q, signature);
754         }
755
756         return g_string_free (q, FALSE);
757 }
758
759 static gchar*
760 modest_text_utils_quote_html (const gchar *text, 
761                               const gchar *cite, 
762                               const gchar *signature,
763                               GList *attachments,
764                               int limit)
765 {
766         gchar *result = NULL;
767         gchar *signature_result = NULL;
768         const gchar *format = \
769                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
770                 "<html>\n" \
771                 "<body>\n" \
772                 "<br/>%s<br/>" \
773                 "<pre>%s<br/>%s<br/>%s</pre>\n" \
774                 "</body>\n" \
775                 "</html>\n";
776         gchar *attachments_string = NULL;
777         gchar *q_attachments_string = NULL;
778         gchar *q_cite = NULL;
779         gchar *html_text = NULL;
780
781         if (signature == NULL)
782                 signature_result = g_strdup ("");
783         else
784                 signature_result = modest_text_utils_convert_to_html_body (signature);
785
786         attachments_string = quoted_attachments (attachments);
787         q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string);
788         q_cite = modest_text_utils_convert_to_html_body (cite);
789         html_text = modest_text_utils_convert_to_html_body (text);
790         result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
791         g_free (q_cite);
792         g_free (html_text);
793         g_free (attachments_string);
794         g_free (q_attachments_string);
795         g_free (signature_result);
796         return result;
797 }
798
799 static gint 
800 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
801 {
802         return match2->offset - match1->offset;
803 }
804
805
806
807 /*
808  * check if the match is inside an existing match... */
809 static void
810 chk_partial_match (const url_match_t *match, guint* offset)
811 {
812         if (*offset >= match->offset && *offset < match->offset + match->len)
813                 *offset = -1;
814 }
815
816 static GSList*
817 get_url_matches (GString *txt)
818 {
819         regmatch_t rm;
820         guint rv, i, offset = 0;
821         GSList *match_list = NULL;
822
823         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
824         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
825
826         /* initalize the regexps */
827         for (i = 0; i != pattern_num; ++i) {
828                 patterns[i].preg = g_slice_new0 (regex_t);
829
830                 /* this should not happen */
831                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
832                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
833         }
834         /* find all the matches */
835         for (i = 0; i != pattern_num; ++i) {
836                 offset     = 0; 
837                 while (1) {
838                         int test_offset;
839                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
840                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
841                                 break; /* try next regexp */ 
842                         }
843                         if (rm.rm_so == -1)
844                                 break;
845
846                         /* FIXME: optimize this */
847                         /* to avoid partial matches on something that was already found... */
848                         /* check_partial_match will put -1 in the data ptr if that is the case */
849                         test_offset = offset + rm.rm_so;
850                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
851                         
852                         /* make a list of our matches (<offset, len, prefix> tupels)*/
853                         if (test_offset != -1) {
854                                 url_match_t *match = g_slice_new (url_match_t);
855                                 match->offset = offset + rm.rm_so;
856                                 match->len    = rm.rm_eo - rm.rm_so;
857                                 match->prefix = patterns[i].prefix;
858                                 match_list = g_slist_prepend (match_list, match);
859                         }
860                         offset += rm.rm_eo;
861                 }
862         }
863
864         for (i = 0; i != pattern_num; ++i) {
865                 regfree (patterns[i].preg);
866                 g_slice_free  (regex_t, patterns[i].preg);
867         } /* don't free patterns itself -- it's static */
868         
869         /* now sort the list, so the matches are in reverse order of occurence.
870          * that way, we can do the replacements starting from the end, so we don't need
871          * to recalculate the offsets
872          */
873         match_list = g_slist_sort (match_list,
874                                    (GCompareFunc)cmp_offsets_reverse); 
875         return match_list;      
876 }
877
878
879
880 static void
881 hyperlinkify_plain_text (GString *txt)
882 {
883         GSList *cursor;
884         GSList *match_list = get_url_matches (txt);
885
886         /* we will work backwards, so the offsets stay valid */
887         for (cursor = match_list; cursor; cursor = cursor->next) {
888
889                 url_match_t *match = (url_match_t*) cursor->data;
890                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
891                 gchar *repl = NULL; /* replacement  */
892
893                 /* the prefix is NULL: use the one that is already there */
894                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
895                                         match->prefix ? match->prefix : EMPTY_STRING, 
896                                         url, url);
897
898                 /* replace the old thing with our hyperlink
899                  * replacement thing */
900                 g_string_erase  (txt, match->offset, match->len);
901                 g_string_insert (txt, match->offset, repl);
902                 
903                 g_free (url);
904                 g_free (repl);
905
906                 g_slice_free (url_match_t, match);      
907         }
908         
909         g_slist_free (match_list);
910 }
911
912
913
914 gchar*
915 modest_text_utils_get_display_address (gchar *address)
916 {
917         gchar *cursor;
918         
919         if (!address)
920                 return NULL;
921         
922         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
923         
924         g_strchug (address); /* remove leading whitespace */
925
926         /*  <email@address> from display name */
927         cursor = g_strstr_len (address, strlen(address), "<");
928         if (cursor == address) /* there's nothing else? leave it */
929                 return address;
930         if (cursor) 
931                 cursor[0]='\0';
932
933         /* remove (bla bla) from display name */
934         cursor = g_strstr_len (address, strlen(address), "(");
935         if (cursor == address) /* there's nothing else? leave it */
936                 return address;
937         if (cursor) 
938                 cursor[0]='\0';
939
940         g_strchomp (address); /* remove trailing whitespace */
941
942         return address;
943 }
944
945
946
947 gint 
948 modest_text_utils_get_subject_prefix_len (const gchar *sub)
949 {
950         gint i;
951         static const gchar* prefix[] = {
952                 "Re:", "RE:", "RV:", "re:"
953                 "Fwd:", "FWD:", "FW:", "fwd:", "Fw:", "fw:", NULL
954         };
955                 
956         if (!sub || (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')) /* optimization */
957                 return 0;
958
959         i = 0;
960         
961         while (prefix[i]) {
962                 if (g_str_has_prefix(sub, prefix[i])) {
963                         int prefix_len = strlen(prefix[i]); 
964                         if (sub[prefix_len] == ' ')
965                                 ++prefix_len; /* ignore space after prefix as well */
966                         return prefix_len; 
967                 }
968                 ++i;
969         }
970         return 0;
971 }
972
973
974 gint
975 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
976 {
977         gint result = 0;
978         gchar *n1, *n2;
979
980         /* work even when s1 and/or s2 == NULL */
981         if (G_UNLIKELY(s1 == s2))
982                 return 0;
983
984         /* if it's not case sensitive */
985         if (!insensitive)
986                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
987         
988         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
989         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
990         
991         result = strcmp (n1, n2);
992
993         g_free (n1);
994         g_free (n2);
995         
996         return result;
997 }
998
999
1000 gchar*
1001 modest_text_utils_get_display_date (time_t date)
1002 {
1003         time_t now;
1004         const guint BUF_SIZE = 64; 
1005         gchar date_buf[BUF_SIZE];  
1006         gchar now_buf [BUF_SIZE];  
1007         
1008         now = time (NULL);
1009
1010         /* use the localized dates */
1011         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date); 
1012         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x", now); 
1013         
1014         /* if this is today, get the time instead of the date */
1015         if (strcmp (date_buf, now_buf) == 0)
1016                 modest_text_utils_strftime (date_buf, BUF_SIZE, "%X", date);
1017         
1018         return g_strdup(date_buf);
1019 }
1020
1021 gboolean 
1022 modest_text_utils_validate_email_address (const gchar *email_address)
1023 {
1024         int count = 0;
1025         const gchar *c = NULL, *domain = NULL;
1026         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
1027
1028         /* first we validate the name portion (name@domain) */
1029         for (c = email_address;  *c;  c++) {
1030                 if (*c == '\"' && 
1031                     (c == email_address || 
1032                      *(c - 1) == '.' || 
1033                      *(c - 1) == '\"')) {
1034                         while (*++c) {
1035                                 if (*c == '\"') 
1036                                         break;
1037                                 if (*c == '\\' && (*++c == ' ')) 
1038                                         continue;
1039                                 if (*c <= ' ' || *c >= 127) 
1040                                         return FALSE;
1041                         }
1042                         if (!*c++) 
1043                                 return FALSE;
1044                         if (*c == '@') 
1045                                 break;
1046                         if (*c != '.') 
1047                                 return FALSE;
1048                         continue;
1049                 }
1050                 if (*c == '@') 
1051                         break;
1052                 if (*c <= ' ' || *c >= 127) 
1053                         return FALSE;
1054                 if (strchr(rfc822_specials, *c)) 
1055                         return FALSE;
1056         }
1057         if (c == email_address || *(c - 1) == '.') 
1058                 return FALSE;
1059
1060         /* next we validate the domain portion (name@domain) */
1061         if (!*(domain = ++c)) 
1062                 return FALSE;
1063         do {
1064                 if (*c == '.') {
1065                         if (c == domain || *(c - 1) == '.') 
1066                                 return FALSE;
1067                         count++;
1068                 }
1069                 if (*c <= ' ' || *c >= 127) 
1070                         return FALSE;
1071                 if (strchr(rfc822_specials, *c)) 
1072                         return FALSE;
1073         } while (*++c);
1074
1075         return (count >= 1) ? TRUE : FALSE;
1076 }
1077
1078 gboolean 
1079 modest_text_utils_validate_recipient (const gchar *recipient)
1080 {
1081         gchar *stripped, *current;
1082         gchar *right_part;
1083         gboolean has_error = FALSE;
1084
1085         if (modest_text_utils_validate_email_address (recipient))
1086                 return TRUE;
1087         stripped = g_strdup (recipient);
1088         stripped = g_strstrip (stripped);
1089         current = stripped;
1090
1091         if (*current == '\0') {
1092                 g_free (stripped);
1093                 return FALSE;
1094         }
1095
1096         /* quoted string */
1097         if (*current == '\"') {
1098                 current = g_utf8_next_char (current);
1099                 has_error = TRUE;
1100                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1101                         if (*current == '\\') {
1102                                 /* TODO: This causes a warning, which breaks the build, 
1103                                  * because a gchar cannot be < 0.
1104                                  * murrayc. 
1105                                 if (current[1] <0) {
1106                                         has_error = TRUE;
1107                                         break;
1108                                 }
1109                                 */
1110                         } else if (*current == '\"') {
1111                                 has_error = FALSE;
1112                                 current = g_utf8_next_char (current);
1113                                 break;
1114                         }
1115                 }
1116         } else {
1117                 has_error = TRUE;
1118                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1119                         if (*current == '<') {
1120                                 has_error = FALSE;
1121                                 break;
1122                         }
1123                 }
1124         }
1125                 
1126         if (has_error) {
1127                 g_free (stripped);
1128                 return FALSE;
1129         }
1130
1131         right_part = g_strdup (current);
1132         g_free (stripped);
1133         right_part = g_strstrip (right_part);
1134
1135         if (g_str_has_prefix (right_part, "<") &&
1136             g_str_has_suffix (right_part, ">")) {
1137                 gchar *address;
1138                 gboolean valid;
1139
1140                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1141                 g_free (right_part);
1142                 valid = modest_text_utils_validate_email_address (address);
1143                 g_free (address);
1144                 return valid;
1145         } else {
1146                 g_free (right_part);
1147                 return FALSE;
1148         }
1149 }
1150
1151
1152 gchar *
1153 modest_text_utils_get_display_size (guint64 size)
1154 {
1155         const guint KB=1024;
1156         const guint MB=1024 * KB;
1157         const guint GB=1024 * MB;
1158
1159         if (size == 0)
1160                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1161         if (0 < size && size < KB)
1162                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1163         else if (KB <= size && size < 100 * KB)
1164                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1165         else if (100*KB <= size && size < MB)
1166                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1167         else if (MB <= size && size < 10*MB)
1168                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1169         else if (10*MB <= size && size < GB)
1170                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1171         else
1172                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1173 }
1174
1175 static gchar *
1176 get_email_from_address (const gchar * address)
1177 {
1178         gchar *left_limit, *right_limit;
1179
1180         left_limit = strstr (address, "<");
1181         right_limit = g_strrstr (address, ">");
1182
1183         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1184                 return g_strdup (address);
1185         else
1186                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1187 }