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