* let the dbus-invoked msgs use the same uids as other messages,
[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         guint           break_dist = 0; /* distance since last break point */
304
305         len = strlen (data);
306
307         /* replace with special html chars where needed*/
308         for (i = 0; i != len; ++i)  {
309                 char kar = data[i];
310                 
311                 if (space_seen && kar != ' ') {
312                         g_string_append_c (html, ' ');
313                         space_seen = FALSE;
314                 }
315                 
316                 /* we artificially insert a breakpoint (newline)
317                  * after 256, to make sure our lines are not so long
318                  * they will DOS the regexping later
319                  */
320                 if (++break_dist == 256) {
321                         g_string_append_c (html, '\n');
322                         break_dist = 0;
323                 }
324                 
325                 switch (kar) {
326                 case 0:  break; /* ignore embedded \0s */       
327                 case '<'  : g_string_append (html, "&lt;");   break;
328                 case '>'  : g_string_append (html, "&gt;");   break;
329                 case '&'  : g_string_append (html, "&amp;");  break;
330                 case '"'  : g_string_append (html, "&quot;");  break;
331                 case '\'' : g_string_append (html, "&apos;"); break;
332                 case '\n' : g_string_append (html, "<br>\n");              break_dist= 0; break;
333                 case '\t' : g_string_append (html, "&nbsp;&nbsp;&nbsp; "); break_dist=0; break; /* note the space at the end*/
334                 case ' ':
335                         break_dist = 0;
336                         if (space_seen) { /* second space in a row */
337                                 g_string_append (html, "&nbsp; ");
338                                 space_seen = FALSE;
339                         } else
340                                 space_seen = TRUE;
341                         break;
342                 default:
343                         g_string_append_c (html, kar);
344                 }
345         }
346 }
347
348 gchar*
349 modest_text_utils_convert_to_html (const gchar *data)
350 {
351         GString         *html;      
352         gsize           len;
353         
354         if (!data)
355                 return NULL;
356
357         len = strlen (data);
358         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
359
360         g_string_append_printf (html,
361                                 "<html><head>"
362                                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf8\">"
363                                 "</head>"
364                                 "<body>");
365
366         modest_text_utils_convert_buffer_to_html (html, data);
367         
368         g_string_append (html, "</body></html>");
369         hyperlinkify_plain_text (html);
370
371         return g_string_free (html, FALSE);
372 }
373
374 gchar *
375 modest_text_utils_convert_to_html_body (const gchar *data)
376 {
377         GString         *html;      
378         gsize           len;
379         
380         if (!data)
381                 return NULL;
382
383         len = strlen (data);
384         html = g_string_sized_new (1.5 * len);  /* just a  guess... */
385
386         modest_text_utils_convert_buffer_to_html (html, data);
387
388         hyperlinkify_plain_text (html);
389
390         return g_string_free (html, FALSE);
391 }
392
393 void
394 modest_text_utils_get_addresses_indexes (const gchar *addresses, GSList **start_indexes, GSList **end_indexes)
395 {
396         gchar *current, *start, *last_blank;
397         gint start_offset = 0, current_offset = 0;
398
399         g_return_if_fail (start_indexes != NULL);
400         g_return_if_fail (end_indexes != NULL);
401
402         start = (gchar *) addresses;
403         current = start;
404         last_blank = start;
405
406         while (*current != '\0') {
407                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
408                         start = g_utf8_next_char (start);
409                         start_offset++;
410                         last_blank = current;
411                 } else if ((*current == ',')||(*current == ';')) {
412                         gint *start_index, *end_index;
413                         start_index = g_new0(gint, 1);
414                         end_index = g_new0(gint, 1);
415                         *start_index = start_offset;
416                         *end_index = current_offset;
417                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
418                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
419                         start = g_utf8_next_char (current);
420                         start_offset = current_offset + 1;
421                         last_blank = start;
422                 } else if (*current == '"') {
423                         current = g_utf8_next_char (current);
424                         current_offset ++;
425                         while ((*current != '"')&&(*current != '\0')) {
426                                 current = g_utf8_next_char (current);
427                                 current_offset ++;
428                         }
429                 }
430                                 
431                 current = g_utf8_next_char (current);
432                 current_offset ++;
433         }
434
435         if (start != current) {
436                         gint *start_index, *end_index;
437                         start_index = g_new0(gint, 1);
438                         end_index = g_new0(gint, 1);
439                         *start_index = start_offset;
440                         *end_index = current_offset;
441                         *start_indexes = g_slist_prepend (*start_indexes, start_index);
442                         *end_indexes = g_slist_prepend (*end_indexes, end_index);
443         }
444         
445         *start_indexes = g_slist_reverse (*start_indexes);
446         *end_indexes = g_slist_reverse (*end_indexes);
447
448         return;
449 }
450
451 GSList *
452 modest_text_utils_split_addresses_list (const gchar *addresses)
453 {
454         gchar *current, *start, *last_blank;
455         GSList *result = NULL;
456
457         start = (gchar *) addresses;
458         current = start;
459         last_blank = start;
460
461         while (*current != '\0') {
462                 if ((start == current)&&((*current == ' ')||(*current == ',')||(*current == ';'))) {
463                         start = g_utf8_next_char (start);
464                         last_blank = current;
465                 } else if ((*current == ',')||(*current == ';')) {
466                         gchar *new_address = NULL;
467                         new_address = g_strndup (start, current - last_blank);
468                         result = g_slist_prepend (result, new_address);
469                         start = g_utf8_next_char (current);
470                         last_blank = start;
471                 } else if (*current == '\"') {
472                         if (current == start) {
473                                 current = g_utf8_next_char (current);
474                                 start = g_utf8_next_char (start);
475                         }
476                         while ((*current != '\"')&&(*current != '\0'))
477                                 current = g_utf8_next_char (current);
478                 }
479                                 
480                 current = g_utf8_next_char (current);
481         }
482
483         if (start != current) {
484                 gchar *new_address = NULL;
485                 new_address = g_strndup (start, current - last_blank);
486                 result = g_slist_prepend (result, new_address);
487         }
488
489         result = g_slist_reverse (result);
490         return result;
491
492 }
493
494 void
495 modest_text_utils_address_range_at_position (const gchar *recipients_list,
496                                              gint position,
497                                              gint *start,
498                                              gint *end)
499 {
500         gchar *current = NULL;
501         gint range_start = 0;
502         gint range_end = 0;
503         gint index;
504         gboolean is_quoted = FALSE;
505
506         index = 0;
507         for (current = (gchar *) recipients_list; *current != '\0'; current = g_utf8_find_next_char (current, NULL)) {
508                 gunichar c = g_utf8_get_char (current);
509
510                 if ((c == ',') && (!is_quoted)) {
511                         if (index < position) {
512                                 range_start = index + 1;
513                         } else {
514                                 break;
515                         }
516                 } else if (c == '\"') {
517                         is_quoted = !is_quoted;
518                 } else if ((c == ' ') &&(range_start == index)) {
519                         range_start ++;
520                 }
521                 index ++;
522                 range_end = index;
523         }
524
525         if (start)
526                 *start = range_start;
527         if (end)
528                 *end = range_end;
529 }
530
531
532 /* ******************************************************************* */
533 /* ************************* UTILIY FUNCTIONS ************************ */
534 /* ******************************************************************* */
535
536 static GString *
537 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
538 {
539         GString *gs;
540         const gchar *i0;
541         
542         if (iter > b + blen)
543                 return g_string_new("");
544         
545         i0 = iter;
546         while (iter[0]) {
547                 if (iter[0] == '\n')
548                         break;
549                 iter++;
550         }
551         gs = g_string_new_len (i0, iter - i0);
552         return gs;
553 }
554 static int
555 get_indent_level (const char *l)
556 {
557         int indent = 0;
558
559         while (l[0]) {
560                 if (l[0] == '>') {
561                         indent++;
562                         if (l[1] == ' ') {
563                                 l++;
564                         }
565                 } else {
566                         break;
567                 }
568                 l++;
569
570         }
571
572         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
573          *      stops reformatting.
574          */
575         if (strcmp (l, "-- ") == 0) {
576                 return -1 - indent;
577         } else {
578                 return indent;
579         }
580 }
581
582 static void
583 unquote_line (GString * l)
584 {
585         gchar *p;
586
587         p = l->str;
588         while (p[0]) {
589                 if (p[0] == '>') {
590                         if (p[1] == ' ') {
591                                 p++;
592                         }
593                 } else {
594                         break;
595                 }
596                 p++;
597         }
598         g_string_erase (l, 0, p - l->str);
599 }
600
601 static void
602 append_quoted (GString * buf, int indent, const GString * str,
603                const int cutpoint)
604 {
605         int i;
606
607         indent = indent < 0 ? abs (indent) - 1 : indent;
608         for (i = 0; i <= indent; i++) {
609                 g_string_append (buf, "> ");
610         }
611         if (cutpoint > 0) {
612                 g_string_append_len (buf, str->str, cutpoint);
613         } else {
614                 g_string_append (buf, str->str);
615         }
616         g_string_append (buf, "\n");
617 }
618
619 static int
620 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
621 {
622         gint index = 0;
623         const gchar *pos, *last;
624         gunichar *uni;
625
626         indent = indent < 0 ? abs (indent) - 1 : indent;
627
628         last = NULL;
629         pos = s;
630         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
631         while (pos[0]) {
632                 if ((index + 2 * indent > limit) && last) {
633                         g_free (uni);
634                         return last - s;
635                 }
636                 if (g_unichar_isspace (uni[index])) {
637                         last = pos;
638                 }
639                 pos = g_utf8_next_char (pos);
640                 index++;
641         }
642         g_free (uni);
643         return strlen (s);
644 }
645
646 static int
647 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
648 {
649         gint i, last;
650
651         last = strlen (s);
652         if (last + 2 * indent < limit)
653                 return last;
654
655         for (i = strlen (s); i > 0; i--) {
656                 if (s[i] == ' ') {
657                         if (i + 2 * indent <= limit) {
658                                 return i;
659                         } else {
660                                 last = i;
661                         }
662                 }
663         }
664         return last;
665 }
666
667 static int
668 get_breakpoint (const gchar * s, const gint indent, const gint limit)
669 {
670
671         if (g_utf8_validate (s, -1, NULL)) {
672                 return get_breakpoint_utf8 (s, indent, limit);
673         } else {                /* assume ASCII */
674                 //g_warning("invalid UTF-8 in msg");
675                 return get_breakpoint_ascii (s, indent, limit);
676         }
677 }
678
679 static gchar *
680 cite (const time_t sent_date, const gchar *from)
681 {
682         return g_strdup (_("mcen_ia_editor_original_message"));
683 }
684
685 static gchar *
686 quoted_attachments (GList *attachments)
687 {
688         GList *node = NULL;
689         GString *result = g_string_new ("");
690         for (node = attachments; node != NULL; node = g_list_next (node)) {
691                 gchar *filename = (gchar *) node->data;
692                 g_string_append_printf ( result, "%s %s\n", _("mcen_ia_editor_attach_filename"), filename);
693         }
694
695         return g_string_free (result, FALSE);
696
697 }
698
699 static gchar *
700 modest_text_utils_quote_plain_text (const gchar *text, 
701                                     const gchar *cite, 
702                                     const gchar *signature,
703                                     GList *attachments,
704                                     int limit)
705 {
706         const gchar *iter;
707         gint indent, breakpoint, rem_indent = 0;
708         GString *q, *l, *remaining;
709         gsize len;
710         gchar *attachments_string = NULL;
711
712         /* remaining will store the rest of the line if we have to break it */
713         q = g_string_new ("\n");
714         q = g_string_append (q, cite);
715         q = g_string_append_c (q, '\n');
716         remaining = g_string_new ("");
717
718         iter = text;
719         len = strlen(text);
720         do {
721                 l = get_next_line (text, len, iter);
722                 iter = iter + l->len + 1;
723                 indent = get_indent_level (l->str);
724                 unquote_line (l);
725
726                 if (remaining->len) {
727                         if (l->len && indent == rem_indent) {
728                                 g_string_prepend (l, " ");
729                                 g_string_prepend (l, remaining->str);
730                         } else {
731                                 do {
732                                         breakpoint =
733                                                 get_breakpoint (remaining->str,
734                                                                 rem_indent,
735                                                                 limit);
736                                         append_quoted (q, rem_indent,
737                                                        remaining, breakpoint);
738                                         g_string_erase (remaining, 0,
739                                                         breakpoint);
740                                         if (remaining->str[0] == ' ') {
741                                                 g_string_erase (remaining, 0,
742                                                                 1);
743                                         }
744                                 } while (remaining->len);
745                         }
746                 }
747                 g_string_free (remaining, TRUE);
748                 breakpoint = get_breakpoint (l->str, indent, limit);
749                 remaining = g_string_new (l->str + breakpoint);
750                 if (remaining->str[0] == ' ') {
751                         g_string_erase (remaining, 0, 1);
752                 }
753                 rem_indent = indent;
754                 append_quoted (q, indent, l, breakpoint);
755                 g_string_free (l, TRUE);
756         } while ((iter < text + len) || (remaining->str[0]));
757
758         attachments_string = quoted_attachments (attachments);
759         q = g_string_append (q, attachments_string);
760         g_free (attachments_string);
761
762         if (signature != NULL) {
763                 q = g_string_append_c (q, '\n');
764                 q = g_string_append (q, signature);
765         }
766
767         return g_string_free (q, FALSE);
768 }
769
770 static gchar*
771 modest_text_utils_quote_html (const gchar *text, 
772                               const gchar *cite, 
773                               const gchar *signature,
774                               GList *attachments,
775                               int limit)
776 {
777         gchar *result = NULL;
778         gchar *signature_result = NULL;
779         const gchar *format = \
780                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
781                 "<html>\n" \
782                 "<body>\n" \
783                 "<br/>%s<br/>" \
784                 "<pre>%s<br/>%s<br/>%s</pre>\n" \
785                 "</body>\n" \
786                 "</html>\n";
787         gchar *attachments_string = NULL;
788         gchar *q_attachments_string = NULL;
789         gchar *q_cite = NULL;
790         gchar *html_text = NULL;
791
792         if (signature == NULL)
793                 signature_result = g_strdup ("");
794         else
795                 signature_result = modest_text_utils_convert_to_html_body (signature);
796
797         attachments_string = quoted_attachments (attachments);
798         q_attachments_string = modest_text_utils_convert_to_html_body (attachments_string);
799         q_cite = modest_text_utils_convert_to_html_body (cite);
800         html_text = modest_text_utils_convert_to_html_body (text);
801         result = g_strdup_printf (format, signature_result, q_cite, html_text, q_attachments_string);
802         g_free (q_cite);
803         g_free (html_text);
804         g_free (attachments_string);
805         g_free (q_attachments_string);
806         g_free (signature_result);
807         return result;
808 }
809
810 static gint 
811 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
812 {
813         return match2->offset - match1->offset;
814 }
815
816
817
818 /*
819  * check if the match is inside an existing match... */
820 static void
821 chk_partial_match (const url_match_t *match, guint* offset)
822 {
823         if (*offset >= match->offset && *offset < match->offset + match->len)
824                 *offset = -1;
825 }
826
827 static GSList*
828 get_url_matches (GString *txt)
829 {
830         regmatch_t rm;
831         guint rv, i, offset = 0;
832         GSList *match_list = NULL;
833
834         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
835         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
836
837         /* initalize the regexps */
838         for (i = 0; i != pattern_num; ++i) {
839                 patterns[i].preg = g_slice_new0 (regex_t);
840
841                 /* this should not happen */
842                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
843                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
844         }
845         /* find all the matches */
846         for (i = 0; i != pattern_num; ++i) {
847                 offset     = 0; 
848                 while (1) {
849                         int test_offset;
850                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
851                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
852                                 break; /* try next regexp */ 
853                         }
854                         if (rm.rm_so == -1)
855                                 break;
856
857                         /* FIXME: optimize this */
858                         /* to avoid partial matches on something that was already found... */
859                         /* check_partial_match will put -1 in the data ptr if that is the case */
860                         test_offset = offset + rm.rm_so;
861                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
862                         
863                         /* make a list of our matches (<offset, len, prefix> tupels)*/
864                         if (test_offset != -1) {
865                                 url_match_t *match = g_slice_new (url_match_t);
866                                 match->offset = offset + rm.rm_so;
867                                 match->len    = rm.rm_eo - rm.rm_so;
868                                 match->prefix = patterns[i].prefix;
869                                 match_list = g_slist_prepend (match_list, match);
870                         }
871                         offset += rm.rm_eo;
872                 }
873         }
874
875         for (i = 0; i != pattern_num; ++i) {
876                 regfree (patterns[i].preg);
877                 g_slice_free  (regex_t, patterns[i].preg);
878         } /* don't free patterns itself -- it's static */
879         
880         /* now sort the list, so the matches are in reverse order of occurence.
881          * that way, we can do the replacements starting from the end, so we don't need
882          * to recalculate the offsets
883          */
884         match_list = g_slist_sort (match_list,
885                                    (GCompareFunc)cmp_offsets_reverse); 
886         return match_list;      
887 }
888
889
890
891 static void
892 hyperlinkify_plain_text (GString *txt)
893 {
894         GSList *cursor;
895         GSList *match_list = get_url_matches (txt);
896
897         /* we will work backwards, so the offsets stay valid */
898         for (cursor = match_list; cursor; cursor = cursor->next) {
899
900                 url_match_t *match = (url_match_t*) cursor->data;
901                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
902                 gchar *repl = NULL; /* replacement  */
903
904                 /* the prefix is NULL: use the one that is already there */
905                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
906                                         match->prefix ? match->prefix : EMPTY_STRING, 
907                                         url, url);
908
909                 /* replace the old thing with our hyperlink
910                  * replacement thing */
911                 g_string_erase  (txt, match->offset, match->len);
912                 g_string_insert (txt, match->offset, repl);
913                 
914                 g_free (url);
915                 g_free (repl);
916
917                 g_slice_free (url_match_t, match);      
918         }
919         
920         g_slist_free (match_list);
921 }
922
923
924
925 gchar*
926 modest_text_utils_get_display_address (gchar *address)
927 {
928         gchar *cursor;
929         
930         if (!address)
931                 return NULL;
932         
933         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
934         
935         g_strchug (address); /* remove leading whitespace */
936
937         /*  <email@address> from display name */
938         cursor = g_strstr_len (address, strlen(address), "<");
939         if (cursor == address) /* there's nothing else? leave it */
940                 return address;
941         if (cursor) 
942                 cursor[0]='\0';
943
944         /* remove (bla bla) from display name */
945         cursor = g_strstr_len (address, strlen(address), "(");
946         if (cursor == address) /* there's nothing else? leave it */
947                 return address;
948         if (cursor) 
949                 cursor[0]='\0';
950
951         g_strchomp (address); /* remove trailing whitespace */
952
953         return address;
954 }
955
956
957
958 gint 
959 modest_text_utils_get_subject_prefix_len (const gchar *sub)
960 {
961         gint i;
962         static const gchar* prefix[] = {
963                 "Re:", "RE:", "RV:", "re:"
964                 "Fwd:", "FWD:", "FW:", "fwd:", "Fw:", "fw:", NULL
965         };
966                 
967         if (!sub || (sub[0] != 'R' && sub[0] != 'F' && sub[0] != 'r' && sub[0] != 'f')) /* optimization */
968                 return 0;
969
970         i = 0;
971         
972         while (prefix[i]) {
973                 if (g_str_has_prefix(sub, prefix[i])) {
974                         int prefix_len = strlen(prefix[i]); 
975                         if (sub[prefix_len] == ' ')
976                                 ++prefix_len; /* ignore space after prefix as well */
977                         return prefix_len; 
978                 }
979                 ++i;
980         }
981         return 0;
982 }
983
984
985 gint
986 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
987 {
988         gint result = 0;
989         gchar *n1, *n2;
990
991         /* work even when s1 and/or s2 == NULL */
992         if (G_UNLIKELY(s1 == s2))
993                 return 0;
994
995         /* if it's not case sensitive */
996         if (!insensitive)
997                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
998         
999         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
1000         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
1001         
1002         result = strcmp (n1, n2);
1003
1004         g_free (n1);
1005         g_free (n2);
1006         
1007         return result;
1008 }
1009
1010
1011 gchar*
1012 modest_text_utils_get_display_date (time_t date)
1013 {
1014         time_t now;
1015         const guint BUF_SIZE = 64; 
1016         gchar date_buf[BUF_SIZE];  
1017         gchar now_buf [BUF_SIZE];  
1018         
1019         now = time (NULL);
1020
1021         /* use the localized dates */
1022         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date); 
1023         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x", now); 
1024         
1025         /* if this is today, get the time instead of the date */
1026         if (strcmp (date_buf, now_buf) == 0)
1027                 modest_text_utils_strftime (date_buf, BUF_SIZE, "%X", date);
1028         
1029         return g_strdup(date_buf);
1030 }
1031
1032 gboolean
1033 modest_text_utils_validate_email_address (const gchar *email_address, const gchar **invalid_char_position)
1034 {
1035         int count = 0;
1036         const gchar *c = NULL, *domain = NULL;
1037         static gchar *rfc822_specials = "()<>@,;:\\\"[]&";
1038
1039         if (invalid_char_position != NULL)
1040                 *invalid_char_position = NULL;
1041
1042         /* first we validate the name portion (name@domain) */
1043         for (c = email_address;  *c;  c++) {
1044                 if (*c == '\"' && 
1045                     (c == email_address || 
1046                      *(c - 1) == '.' || 
1047                      *(c - 1) == '\"')) {
1048                         while (*++c) {
1049                                 if (*c == '\"') 
1050                                         break;
1051                                 if (*c == '\\' && (*++c == ' ')) 
1052                                         continue;
1053                                 if (*c <= ' ' || *c >= 127) 
1054                                         return FALSE;
1055                         }
1056                         if (!*c++) 
1057                                 return FALSE;
1058                         if (*c == '@') 
1059                                 break;
1060                         if (*c != '.') 
1061                                 return FALSE;
1062                         continue;
1063                 }
1064                 if (*c == '@') 
1065                         break;
1066                 if (*c <= ' ' || *c >= 127) 
1067                         return FALSE;
1068                 if (strchr(rfc822_specials, *c)) {
1069                         if (invalid_char_position)
1070                                 *invalid_char_position = c;
1071                         return FALSE;
1072                 }
1073         }
1074         if (c == email_address || *(c - 1) == '.') 
1075                 return FALSE;
1076
1077         /* next we validate the domain portion (name@domain) */
1078         if (!*(domain = ++c)) 
1079                 return FALSE;
1080         do {
1081                 if (*c == '.') {
1082                         if (c == domain || *(c - 1) == '.') 
1083                                 return FALSE;
1084                         count++;
1085                 }
1086                 if (*c <= ' ' || *c >= 127) 
1087                         return FALSE;
1088                 if (strchr(rfc822_specials, *c)) {
1089                         if (invalid_char_position)
1090                                 *invalid_char_position = c;
1091                         return FALSE;
1092                 }
1093         } while (*++c);
1094
1095         return (count >= 1) ? TRUE : FALSE;
1096 }
1097
1098 gboolean 
1099 modest_text_utils_validate_recipient (const gchar *recipient, const gchar **invalid_char_position)
1100 {
1101         gchar *stripped, *current;
1102         gchar *right_part;
1103         gboolean has_error = FALSE;
1104
1105         if (modest_text_utils_validate_email_address (recipient, invalid_char_position))
1106                 return TRUE;
1107         stripped = g_strdup (recipient);
1108         stripped = g_strstrip (stripped);
1109         current = stripped;
1110
1111         if (*current == '\0') {
1112                 g_free (stripped);
1113                 return FALSE;
1114         }
1115
1116         /* quoted string */
1117         if (*current == '\"') {
1118                 current = g_utf8_next_char (current);
1119                 has_error = TRUE;
1120                 for (; *current != '\0'; current = g_utf8_next_char (current)) {
1121                         if (*current == '\\') {
1122                                 /* TODO: This causes a warning, which breaks the build, 
1123                                  * because a gchar cannot be < 0.
1124                                  * murrayc. 
1125                                 if (current[1] <0) {
1126                                         has_error = TRUE;
1127                                         break;
1128                                 }
1129                                 */
1130                         } else if (*current == '\"') {
1131                                 has_error = FALSE;
1132                                 current = g_utf8_next_char (current);
1133                                 break;
1134                         }
1135                 }
1136         } else {
1137                 has_error = TRUE;
1138                 for (current = stripped ; *current != '\0'; current = g_utf8_next_char (current)) {
1139                         if (*current == '<') {
1140                                 has_error = FALSE;
1141                                 break;
1142                         }
1143                 }
1144         }
1145                 
1146         if (has_error) {
1147                 g_free (stripped);
1148                 return FALSE;
1149         }
1150
1151         right_part = g_strdup (current);
1152         g_free (stripped);
1153         right_part = g_strstrip (right_part);
1154
1155         if (g_str_has_prefix (right_part, "<") &&
1156             g_str_has_suffix (right_part, ">")) {
1157                 gchar *address;
1158                 gboolean valid;
1159
1160                 address = g_strndup (right_part+1, strlen (right_part) - 2);
1161                 g_free (right_part);
1162                 valid = modest_text_utils_validate_email_address (address, invalid_char_position);
1163                 g_free (address);
1164                 return valid;
1165         } else {
1166                 g_free (right_part);
1167                 return FALSE;
1168         }
1169 }
1170
1171
1172 gchar *
1173 modest_text_utils_get_display_size (guint64 size)
1174 {
1175         const guint KB=1024;
1176         const guint MB=1024 * KB;
1177         const guint GB=1024 * MB;
1178
1179         if (size == 0)
1180                 return g_strdup_printf(_FM("sfil_li_size_kb"), 0);
1181         if (0 < size && size < KB)
1182                 return g_strdup_printf (_FM("sfil_li_size_kb"), 1);
1183         else if (KB <= size && size < 100 * KB)
1184                 return g_strdup_printf (_FM("sfil_li_size_1kb_99kb"), size / KB);
1185         else if (100*KB <= size && size < MB)
1186                 return g_strdup_printf (_FM("sfil_li_size_100kb_1mb"), (float) size / MB);
1187         else if (MB <= size && size < 10*MB)
1188                 return g_strdup_printf (_FM("sfil_li_size_1mb_10mb"), (float) size / MB);
1189         else if (10*MB <= size && size < GB)
1190                 return g_strdup_printf (_FM("sfil_li_size_10mb_1gb"), size / MB);
1191         else
1192                 return g_strdup_printf (_FM("sfil_li_size_1gb_or_greater"), (float) size / GB); 
1193 }
1194
1195 static gchar *
1196 get_email_from_address (const gchar * address)
1197 {
1198         gchar *left_limit, *right_limit;
1199
1200         left_limit = strstr (address, "<");
1201         right_limit = g_strrstr (address, ">");
1202
1203         if ((left_limit == NULL)||(right_limit == NULL)|| (left_limit > right_limit))
1204                 return g_strdup (address);
1205         else
1206                 return g_strndup (left_limit + 1, (right_limit - left_limit) - 1);
1207 }
1208
1209 gchar *      
1210 modest_text_utils_get_color_string (GdkColor *color)
1211 {
1212
1213         return g_strdup_printf ("#%x%x%x%x%x%x%x%x%x%x%x%x",
1214                                 (color->red >> 12)   & 0xf, (color->red >> 8)   & 0xf,
1215                                 (color->red >>  4)   & 0xf, (color->red)        & 0xf,
1216                                 (color->green >> 12) & 0xf, (color->green >> 8) & 0xf,
1217                                 (color->green >>  4) & 0xf, (color->green)      & 0xf,
1218                                 (color->blue >> 12)  & 0xf, (color->blue >> 8)  & 0xf,
1219                                 (color->blue >>  4)  & 0xf, (color->blue)       & 0xf);
1220 }