6e22878eacdfd15d075894989f626c4eab95e0f6
[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                                                     int limit);
104
105 static gchar*   modest_text_utils_quote_html       (const gchar *text, 
106                                                     const gchar *cite, 
107                                                     int limit);
108
109
110 /* ******************************************************************* */
111 /* ************************* PUBLIC FUNCTIONS ************************ */
112 /* ******************************************************************* */
113
114 gchar *
115 modest_text_utils_quote (const gchar *text, 
116                          const gchar *content_type,
117                          const gchar *from,
118                          const time_t sent_date, 
119                          int limit)
120 {
121         gchar *retval, *cited;
122
123         g_return_val_if_fail (text, NULL);
124         g_return_val_if_fail (content_type, NULL);
125
126         cited = cite (sent_date, from);
127         
128         if (content_type && strcmp (content_type, "text/html") == 0)
129                 /* TODO: extract the <body> of the HTML and pass it to
130                    the function */
131                 retval = modest_text_utils_quote_html (text, cited, limit);
132         else
133                 retval = modest_text_utils_quote_plain_text (text, cited, limit);
134         
135         g_free (cited);
136
137         return retval;
138 }
139
140
141 gchar *
142 modest_text_utils_cite (const gchar *text,
143                         const gchar *content_type,
144                         const gchar *from,
145                         time_t sent_date)
146 {
147         gchar *tmp, *retval;
148
149         g_return_val_if_fail (text, NULL);
150         g_return_val_if_fail (content_type, NULL);
151
152         tmp = cite (sent_date, from);
153         retval = g_strdup_printf ("%s%s\n", tmp, text);
154         g_free (tmp);
155
156         return retval;
157 }
158
159 gchar * 
160 modest_text_utils_inline (const gchar *text,
161                           const gchar *content_type,
162                           const gchar *from,
163                           time_t sent_date,
164                           const gchar *to,
165                           const gchar *subject)
166 {
167         gchar sent_str[101];
168         const gchar *plain_format = "%s\n%s %s\n%s %s\n%s %s\n%s %s\n\n%s";
169         const gchar *html_format = \
170                 "%s<br>\n<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n" \
171                 "<tr><td>%s</td><td>%s</td></tr>\n" \
172                 "<tr><td>%s</td><td>%s</td></tr>\n" \
173                 "<tr><td>%s</td><td>%s</td></tr>\n" \
174                 "<tr><td>%s</td><td>%s</td></tr>\n" \
175                 "<br><br>%s";
176         const gchar *format;
177
178         g_return_val_if_fail (text, NULL);
179         g_return_val_if_fail (content_type, NULL);
180         g_return_val_if_fail (text, NULL);
181         
182         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
183
184         if (!strcmp (content_type, "text/html"))
185                 /* TODO: extract the <body> of the HTML and pass it to
186                    the function */
187                 format = html_format;
188         else
189                 format = plain_format;
190
191         return g_strdup_printf (format, 
192                                 FORWARD_STRING,
193                                 FROM_STRING, (from) ? from : EMPTY_STRING,
194                                 SENT_STRING, sent_str,
195                                 TO_STRING, (to) ? to : EMPTY_STRING,
196                                 SUBJECT_STRING, (subject) ? subject : EMPTY_STRING,
197                                 text);
198 }
199
200 /* just to prevent warnings:
201  * warning: `%x' yields only last 2 digits of year in some locales
202  */
203 gsize
204 modest_text_utils_strftime(char *s, gsize max, const char *fmt, time_t timet)
205 {
206         static GDate date;
207
208         g_date_set_time_t (&date, timet);
209         return g_date_strftime (s, max, fmt, (const GDate*) &date);
210 }
211
212 gchar *
213 modest_text_utils_derived_subject (const gchar *subject, const gchar *prefix)
214 {
215         gchar *tmp;
216
217         g_return_val_if_fail (prefix, NULL);
218         
219         if (!subject)
220                 return g_strdup (prefix);
221
222         tmp = g_strchug (g_strdup (subject));
223
224         if (!strncmp (tmp, prefix, strlen (prefix))) {
225                 return tmp;
226         } else {
227                 g_free (tmp);
228                 return g_strdup_printf ("%s %s", prefix, subject);
229         }
230 }
231
232 gchar*
233 modest_text_utils_remove_address (const gchar *address_list, const gchar *address)
234 {
235         gchar *dup, *token, *ptr, *result;
236         GString *filtered_emails;
237
238         g_return_val_if_fail (address_list, NULL);
239
240         if (!address)
241                 return g_strdup (address_list);
242         
243         /* search for substring */
244         if (!strstr ((const char *) address_list, (const char *) address))
245                 return g_strdup (address_list);
246
247         dup = g_strdup (address_list);
248         filtered_emails = g_string_new (NULL);
249         
250         token = strtok_r (dup, ",", &ptr);
251
252         while (token != NULL) {
253                 /* Add to list if not found */
254                 if (!strstr ((const char *) token, (const char *) address)) {
255                         if (filtered_emails->len == 0)
256                                 g_string_append_printf (filtered_emails, "%s", g_strstrip (token));
257                         else
258                                 g_string_append_printf (filtered_emails, ",%s", g_strstrip (token));
259                 }
260                 token = strtok_r (NULL, ",", &ptr);
261         }
262         result = filtered_emails->str;
263
264         /* Clean */
265         g_free (dup);
266         g_string_free (filtered_emails, FALSE);
267
268         return result;
269 }
270
271 gchar*
272 modest_text_utils_convert_to_html (const gchar *data)
273 {
274         guint            i;
275         gboolean         first_space = TRUE;
276         GString         *html;      
277         gsize           len;
278
279         if (!data)
280                 return NULL;
281
282         len = strlen (data);
283         html = g_string_sized_new (len + 100);  /* just a  guess... */
284         
285         g_string_append_printf (html,
286                                 "<html>"
287                                 "<head>"
288                                 "<meta http-equiv=\"content-type\""
289                                 " content=\"text/html; charset=utf8\">"
290                                 "</head>"
291                                 "<body><tt>");
292         
293         /* replace with special html chars where needed*/
294         for (i = 0; i != len; ++i)  {
295                 char    kar = data[i]; 
296                 switch (kar) {
297                         
298                 case 0:  break; /* ignore embedded \0s */       
299                 case '<' : g_string_append   (html, "&lt;"); break;
300                 case '>' : g_string_append   (html, "&gt;"); break;
301                 case '&' : g_string_append   (html, "&quot;"); break;
302                 case '\n': g_string_append   (html, "<br>\n"); break;
303                 default:
304                         if (kar == ' ') {
305                                 g_string_append (html, first_space ? " " : "&nbsp;");
306                                 first_space = FALSE;
307                         } else  if (kar == '\t')
308                                 g_string_append (html, "&nbsp; &nbsp;&nbsp;");
309                         else {
310                                 int charnum = 0;
311                                 first_space = TRUE;
312                                 /* optimization trick: accumulate 'normal' chars, then copy */
313                                 do {
314                                         kar = data [++charnum + i];
315                                         
316                                 } while ((i + charnum < len) &&
317                                          (kar > '>' || (kar != '<' && kar != '>'
318                                                         && kar != '&' && kar !=  ' '
319                                                         && kar != '\n' && kar != '\t')));
320                                 g_string_append_len (html, &data[i], charnum);
321                                 i += (charnum  - 1);
322                         }
323                 }
324         }
325         
326         g_string_append (html, "</tt></body></html>");
327         hyperlinkify_plain_text (html);
328
329         return g_string_free (html, FALSE);
330 }
331
332 /* ******************************************************************* */
333 /* ************************* UTILIY FUNCTIONS ************************ */
334 /* ******************************************************************* */
335
336 static GString *
337 get_next_line (const gchar * b, const gsize blen, const gchar * iter)
338 {
339         GString *gs;
340         const gchar *i0;
341         
342         if (iter > b + blen)
343                 return g_string_new("");
344         
345         i0 = iter;
346         while (iter[0]) {
347                 if (iter[0] == '\n')
348                         break;
349                 iter++;
350         }
351         gs = g_string_new_len (i0, iter - i0);
352         return gs;
353 }
354 static int
355 get_indent_level (const char *l)
356 {
357         int indent = 0;
358
359         while (l[0]) {
360                 if (l[0] == '>') {
361                         indent++;
362                         if (l[1] == ' ') {
363                                 l++;
364                         }
365                 } else {
366                         break;
367                 }
368                 l++;
369
370         }
371
372         /*      if we hit the signature marker "-- ", we return -(indent + 1). This
373          *      stops reformatting.
374          */
375         if (strcmp (l, "-- ") == 0) {
376                 return -1 - indent;
377         } else {
378                 return indent;
379         }
380 }
381
382 static void
383 unquote_line (GString * l)
384 {
385         gchar *p;
386
387         p = l->str;
388         while (p[0]) {
389                 if (p[0] == '>') {
390                         if (p[1] == ' ') {
391                                 p++;
392                         }
393                 } else {
394                         break;
395                 }
396                 p++;
397         }
398         g_string_erase (l, 0, p - l->str);
399 }
400
401 static void
402 append_quoted (GString * buf, int indent, const GString * str,
403                const int cutpoint)
404 {
405         int i;
406
407         indent = indent < 0 ? abs (indent) - 1 : indent;
408         for (i = 0; i <= indent; i++) {
409                 g_string_append (buf, "> ");
410         }
411         if (cutpoint > 0) {
412                 g_string_append_len (buf, str->str, cutpoint);
413         } else {
414                 g_string_append (buf, str->str);
415         }
416         g_string_append (buf, "\n");
417 }
418
419 static int
420 get_breakpoint_utf8 (const gchar * s, gint indent, const gint limit)
421 {
422         gint index = 0;
423         const gchar *pos, *last;
424         gunichar *uni;
425
426         indent = indent < 0 ? abs (indent) - 1 : indent;
427
428         last = NULL;
429         pos = s;
430         uni = g_utf8_to_ucs4_fast (s, -1, NULL);
431         while (pos[0]) {
432                 if ((index + 2 * indent > limit) && last) {
433                         g_free (uni);
434                         return last - s;
435                 }
436                 if (g_unichar_isspace (uni[index])) {
437                         last = pos;
438                 }
439                 pos = g_utf8_next_char (pos);
440                 index++;
441         }
442         g_free (uni);
443         return strlen (s);
444 }
445
446 static int
447 get_breakpoint_ascii (const gchar * s, const gint indent, const gint limit)
448 {
449         gint i, last;
450
451         last = strlen (s);
452         if (last + 2 * indent < limit)
453                 return last;
454
455         for (i = strlen (s); i > 0; i--) {
456                 if (s[i] == ' ') {
457                         if (i + 2 * indent <= limit) {
458                                 return i;
459                         } else {
460                                 last = i;
461                         }
462                 }
463         }
464         return last;
465 }
466
467 static int
468 get_breakpoint (const gchar * s, const gint indent, const gint limit)
469 {
470
471         if (g_utf8_validate (s, -1, NULL)) {
472                 return get_breakpoint_utf8 (s, indent, limit);
473         } else {                /* assume ASCII */
474                 //g_warning("invalid UTF-8 in msg");
475                 return get_breakpoint_ascii (s, indent, limit);
476         }
477 }
478
479 static gchar *
480 cite (const time_t sent_date, const gchar *from)
481 {
482         gchar sent_str[101];
483
484         /* format sent_date */
485         modest_text_utils_strftime (sent_str, 100, "%c", sent_date);
486         return g_strdup_printf (N_("On %s, %s wrote:\n"), 
487                                 sent_str, 
488                                 (from) ? from : EMPTY_STRING);
489 }
490
491
492 static gchar *
493 modest_text_utils_quote_plain_text (const gchar *text, 
494                                     const gchar *cite, 
495                                     int limit)
496 {
497         const gchar *iter;
498         gint indent, breakpoint, rem_indent = 0;
499         GString *q, *l, *remaining;
500         gsize len;
501
502         /* remaining will store the rest of the line if we have to break it */
503         q = g_string_new (cite);
504         remaining = g_string_new ("");
505
506         iter = text;
507         len = strlen(text);
508         do {
509                 l = get_next_line (text, len, iter);
510                 iter = iter + l->len + 1;
511                 indent = get_indent_level (l->str);
512                 unquote_line (l);
513
514                 if (remaining->len) {
515                         if (l->len && indent == rem_indent) {
516                                 g_string_prepend (l, " ");
517                                 g_string_prepend (l, remaining->str);
518                         } else {
519                                 do {
520                                         breakpoint =
521                                                 get_breakpoint (remaining->str,
522                                                                 rem_indent,
523                                                                 limit);
524                                         append_quoted (q, rem_indent,
525                                                        remaining, breakpoint);
526                                         g_string_erase (remaining, 0,
527                                                         breakpoint);
528                                         if (remaining->str[0] == ' ') {
529                                                 g_string_erase (remaining, 0,
530                                                                 1);
531                                         }
532                                 } while (remaining->len);
533                         }
534                 }
535                 g_string_free (remaining, TRUE);
536                 breakpoint = get_breakpoint (l->str, indent, limit);
537                 remaining = g_string_new (l->str + breakpoint);
538                 if (remaining->str[0] == ' ') {
539                         g_string_erase (remaining, 0, 1);
540                 }
541                 rem_indent = indent;
542                 append_quoted (q, indent, l, breakpoint);
543                 g_string_free (l, TRUE);
544         } while ((iter < text + len) || (remaining->str[0]));
545
546         return g_string_free (q, FALSE);
547 }
548
549 static gchar*
550 modest_text_utils_quote_html (const gchar *text, 
551                               const gchar *cite, 
552                               int limit)
553 {
554         const gchar *format = \
555                 "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" \
556                 "<html>\n" \
557                 "<body>\n" \
558                 "%s" \
559                 "<blockquote type=\"cite\">\n%s\n</blockquote>\n" \
560                 "</body>\n" \
561                 "</html>\n";
562
563         return g_strdup_printf (format, cite, text);
564 }
565
566 static gint 
567 cmp_offsets_reverse (const url_match_t *match1, const url_match_t *match2)
568 {
569         return match2->offset - match1->offset;
570 }
571
572
573
574 /*
575  * check if the match is inside an existing match... */
576 static void
577 chk_partial_match (const url_match_t *match, guint* offset)
578 {
579         if (*offset >= match->offset && *offset < match->offset + match->len)
580                 *offset = -1;
581 }
582
583 static GSList*
584 get_url_matches (GString *txt)
585 {
586         regmatch_t rm;
587         guint rv, i, offset = 0;
588         GSList *match_list = NULL;
589
590         static url_match_pattern_t patterns[] = MAIL_VIEWER_URL_MATCH_PATTERNS;
591         const size_t pattern_num = sizeof(patterns)/sizeof(url_match_pattern_t);
592
593         /* initalize the regexps */
594         for (i = 0; i != pattern_num; ++i) {
595                 patterns[i].preg = g_slice_new0 (regex_t);
596
597                 /* this should not happen */
598                 g_return_val_if_fail (regcomp (patterns[i].preg, patterns[i].regex,
599                                                REG_ICASE|REG_EXTENDED|REG_NEWLINE) == 0, NULL);
600         }
601         /* find all the matches */
602         for (i = 0; i != pattern_num; ++i) {
603                 offset     = 0; 
604                 while (1) {
605                         int test_offset;
606                         if ((rv = regexec (patterns[i].preg, txt->str + offset, 1, &rm, 0)) != 0) {
607                                 g_return_val_if_fail (rv == REG_NOMATCH, NULL); /* this should not happen */
608                                 break; /* try next regexp */ 
609                         }
610                         if (rm.rm_so == -1)
611                                 break;
612
613                         /* FIXME: optimize this */
614                         /* to avoid partial matches on something that was already found... */
615                         /* check_partial_match will put -1 in the data ptr if that is the case */
616                         test_offset = offset + rm.rm_so;
617                         g_slist_foreach (match_list, (GFunc)chk_partial_match, &test_offset);
618                         
619                         /* make a list of our matches (<offset, len, prefix> tupels)*/
620                         if (test_offset != -1) {
621                                 url_match_t *match = g_slice_new (url_match_t);
622                                 match->offset = offset + rm.rm_so;
623                                 match->len    = rm.rm_eo - rm.rm_so;
624                                 match->prefix = patterns[i].prefix;
625                                 match_list = g_slist_prepend (match_list, match);
626                         }
627                         offset += rm.rm_eo;
628                 }
629         }
630
631         for (i = 0; i != pattern_num; ++i) {
632                 regfree (patterns[i].preg);
633                 g_slice_free  (regex_t, patterns[i].preg);
634         } /* don't free patterns itself -- it's static */
635         
636         /* now sort the list, so the matches are in reverse order of occurence.
637          * that way, we can do the replacements starting from the end, so we don't need
638          * to recalculate the offsets
639          */
640         match_list = g_slist_sort (match_list,
641                                    (GCompareFunc)cmp_offsets_reverse); 
642         return match_list;      
643 }
644
645
646
647 static void
648 hyperlinkify_plain_text (GString *txt)
649 {
650         GSList *cursor;
651         GSList *match_list = get_url_matches (txt);
652
653         /* we will work backwards, so the offsets stay valid */
654         for (cursor = match_list; cursor; cursor = cursor->next) {
655
656                 url_match_t *match = (url_match_t*) cursor->data;
657                 gchar *url  = g_strndup (txt->str + match->offset, match->len);
658                 gchar *repl = NULL; /* replacement  */
659
660                 /* the prefix is NULL: use the one that is already there */
661                 repl = g_strdup_printf ("<a href=\"%s%s\">%s</a>",
662                                         match->prefix ? match->prefix : EMPTY_STRING, 
663                                         url, url);
664
665                 /* replace the old thing with our hyperlink
666                  * replacement thing */
667                 g_string_erase  (txt, match->offset, match->len);
668                 g_string_insert (txt, match->offset, repl);
669                 
670                 g_free (url);
671                 g_free (repl);
672
673                 g_slice_free (url_match_t, match);      
674         }
675         
676         g_slist_free (match_list);
677 }
678
679
680
681 gchar*
682 modest_text_utils_get_display_address (gchar *address)
683 {
684         gchar *cursor;
685         
686         if (!address)
687                 return NULL;
688
689         g_return_val_if_fail (g_utf8_validate (address, -1, NULL), NULL);
690
691         g_strchug (address); /* remove leading whitespace */
692
693         /*  <email@address> from display name */
694         cursor = g_strstr_len (address, strlen(address), "<");
695         if (cursor == address) /* there's nothing else? leave it */
696                 return address;
697         if (cursor) 
698                 cursor[0]='\0';
699
700         /* remove (bla bla) from display name */
701         cursor = g_strstr_len (address, strlen(address), "(");
702         if (cursor == address) /* there's nothing else? leave it */
703                 return address;
704         if (cursor) 
705                 cursor[0]='\0';
706
707         g_strchomp (address); /* remove trailing whitespace */
708
709         return address;
710 }
711
712
713
714 gint 
715 modest_text_utils_get_subject_prefix_len (const gchar *sub)
716 {
717         gint i;
718         static const gchar* prefix[] = {
719                 "Re:", "RE:", "Fwd:", "FWD:", "FW:", NULL
720         };
721                 
722         if (!sub || (sub[0] != 'R' && sub[0] != 'F')) /* optimization */
723                 return 0;
724
725         i = 0;
726         
727         while (prefix[i]) {
728                 if (g_str_has_prefix(sub, prefix[i])) {
729                         int prefix_len = strlen(prefix[i]); 
730                         if (sub[prefix_len] == ' ')
731                                 ++prefix_len; /* ignore space after prefix as well */
732                         return prefix_len; 
733                 }
734                 ++i;
735         }
736         return 0;
737 }
738
739
740 gint
741 modest_text_utils_utf8_strcmp (const gchar* s1, const gchar *s2, gboolean insensitive)
742 {
743         gint result = 0;
744         gchar *n1, *n2;
745
746         /* work even when s1 and/or s2 == NULL */
747         if (G_UNLIKELY(s1 == s2))
748                 return 0;
749
750         /* if it's not case sensitive */
751         if (!insensitive)
752                 return strcmp (s1 ? s1 : "", s2 ? s2 : "");
753         
754         n1 = g_utf8_collate_key (s1 ? s1 : "", -1);
755         n2 = g_utf8_collate_key (s2 ? s2 : "", -1);
756         
757         result = strcmp (n1, n2);
758
759         g_free (n1);
760         g_free (n2);
761         
762         return result;
763 }
764
765
766 gchar*
767 modest_text_utils_get_display_date (time_t date)
768 {
769         time_t now;
770         const guint BUF_SIZE = 64; 
771         gchar date_buf[BUF_SIZE];  
772         gchar now_buf [BUF_SIZE];  
773         
774         now = time (NULL);
775
776         modest_text_utils_strftime (date_buf, BUF_SIZE, "%x", date);
777         modest_text_utils_strftime (now_buf,  BUF_SIZE, "%x",  now); /* today */
778         
779         /* if this is today, get the time instead of the date */
780         if (strcmp (date_buf, now_buf) == 0)
781                 modest_text_utils_strftime (date_buf, BUF_SIZE, _("%X"), date);
782         
783         return g_strdup(date_buf);
784 }
785
786 gboolean 
787 modest_text_utils_validate_email_address (const gchar *email_address)
788 {
789         int count = 0;
790         const gchar *c, *domain;
791         static gchar *rfc822_specials = "()<>@,;:\\\"[]";
792
793         /* first we validate the name portion (name@domain) */
794         for (c = email_address;  *c;  c++) {
795                 if (*c == '\"' && 
796                     (c == email_address || 
797                      *(c - 1) == '.' || 
798                      *(c - 1) == '\"')) {
799                         while (*++c) {
800                                 if (*c == '\"') 
801                                         break;
802                                 if (*c == '\\' && (*++c == ' ')) 
803                                         continue;
804                                 if (*c <= ' ' || *c >= 127) 
805                                         return FALSE;
806                         }
807                         if (!*c++) 
808                                 return FALSE;
809                         if (*c == '@') 
810                                 break;
811                         if (*c != '.') 
812                                 return FALSE;
813                         continue;
814                 }
815                 if (*c == '@') 
816                         break;
817                 if (*c <= ' ' || *c >= 127) 
818                         return FALSE;
819                 if (strchr(rfc822_specials, *c)) 
820                         return FALSE;
821         }
822         if (c == email_address || *(c - 1) == '.') 
823                 return FALSE;
824
825         /* next we validate the domain portion (name@domain) */
826         if (!*(domain = ++c)) 
827                 return FALSE;
828         do {
829                 if (*c == '.') {
830                         if (c == domain || *(c - 1) == '.') 
831                                 return FALSE;
832                         count++;
833                 }
834                 if (*c <= ' ' || *c >= 127) 
835                         return FALSE;
836                 if (strchr(rfc822_specials, *c)) 
837                         return FALSE;
838         } while (*++c);
839
840         return (count >= 1) ? TRUE : FALSE;
841 }
842
843
844
845
846 gchar *
847 modest_text_utils_get_display_size (guint size)
848 {
849         const guint KB=1024;
850         const guint MB=1024 * KB;
851         const guint GB=1024 * MB;
852         const guint TB=1024 * GB;
853
854         if (size < KB)
855                 return g_strdup_printf (_("%0.1f Kb"), (double)size / KB);
856         else if (size < MB)
857                 return g_strdup_printf (_("%d Kb"), size / KB);
858         else if (size < GB)
859                 return g_strdup_printf (_("%d Mb"), size / MB);
860         else if (size < TB)
861                 return g_strdup_printf (_("%d Gb"), size/ GB);
862         else
863                 return g_strdup_printf (_("Very big"));
864 }