Forgot to date rc1
[claws.git] / src / matcher.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2002-2004 by the Claws Mail Team and Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <glib.h>
25 #include <glib/gi18n.h>
26 #include <ctype.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <errno.h>
30
31 #ifdef USE_PTHREAD
32 #include <pthread.h>
33 #endif
34
35 #include "defs.h"
36 #include "utils.h"
37 #include "procheader.h"
38 #include "matcher.h"
39 #include "matcher_parser.h"
40 #include "prefs_gtk.h"
41 #include "addr_compl.h"
42 #include "codeconv.h"
43 #include "quoted-printable.h"
44 #include "claws.h"
45 #include <ctype.h>
46
47 /*!
48  *\brief        Keyword lookup element
49  */
50 struct _MatchParser {
51         gint id;                /*!< keyword id */ 
52         gchar *str;             /*!< keyword */
53 };
54 typedef struct _MatchParser MatchParser;
55
56 /*!
57  *\brief        Table with strings and ids used by the lexer and
58  *              the parser. New keywords can be added here.
59  */
60 static const MatchParser matchparser_tab[] = {
61         /* msginfo flags */
62         {MATCHCRITERIA_ALL, "all"},
63         {MATCHCRITERIA_UNREAD, "unread"},
64         {MATCHCRITERIA_NOT_UNREAD, "~unread"},
65         {MATCHCRITERIA_NEW, "new"},
66         {MATCHCRITERIA_NOT_NEW, "~new"},
67         {MATCHCRITERIA_MARKED, "marked"},
68         {MATCHCRITERIA_NOT_MARKED, "~marked"},
69         {MATCHCRITERIA_DELETED, "deleted"},
70         {MATCHCRITERIA_NOT_DELETED, "~deleted"},
71         {MATCHCRITERIA_REPLIED, "replied"},
72         {MATCHCRITERIA_NOT_REPLIED, "~replied"},
73         {MATCHCRITERIA_FORWARDED, "forwarded"},
74         {MATCHCRITERIA_NOT_FORWARDED, "~forwarded"},
75         {MATCHCRITERIA_LOCKED, "locked"},
76         {MATCHCRITERIA_NOT_LOCKED, "~locked"},
77         {MATCHCRITERIA_COLORLABEL, "colorlabel"},
78         {MATCHCRITERIA_NOT_COLORLABEL, "~colorlabel"},
79         {MATCHCRITERIA_IGNORE_THREAD, "ignore_thread"},
80         {MATCHCRITERIA_NOT_IGNORE_THREAD, "~ignore_thread"},
81         {MATCHCRITERIA_SPAM, "spam"},
82         {MATCHCRITERIA_NOT_SPAM, "~spam"},
83
84         /* msginfo headers */
85         {MATCHCRITERIA_SUBJECT, "subject"},
86         {MATCHCRITERIA_NOT_SUBJECT, "~subject"},
87         {MATCHCRITERIA_FROM, "from"},
88         {MATCHCRITERIA_NOT_FROM, "~from"},
89         {MATCHCRITERIA_TO, "to"},
90         {MATCHCRITERIA_NOT_TO, "~to"},
91         {MATCHCRITERIA_CC, "cc"},
92         {MATCHCRITERIA_NOT_CC, "~cc"},
93         {MATCHCRITERIA_TO_OR_CC, "to_or_cc"},
94         {MATCHCRITERIA_NOT_TO_AND_NOT_CC, "~to_or_cc"},
95         {MATCHCRITERIA_AGE_GREATER, "age_greater"},
96         {MATCHCRITERIA_AGE_LOWER, "age_lower"},
97         {MATCHCRITERIA_NEWSGROUPS, "newsgroups"},
98         {MATCHCRITERIA_NOT_NEWSGROUPS, "~newsgroups"},
99         {MATCHCRITERIA_INREPLYTO, "inreplyto"},
100         {MATCHCRITERIA_NOT_INREPLYTO, "~inreplyto"},
101         {MATCHCRITERIA_REFERENCES, "references"},
102         {MATCHCRITERIA_NOT_REFERENCES, "~references"},
103         {MATCHCRITERIA_SCORE_GREATER, "score_greater"},
104         {MATCHCRITERIA_SCORE_LOWER, "score_lower"},
105         {MATCHCRITERIA_SCORE_EQUAL, "score_equal"},
106         {MATCHCRITERIA_PARTIAL, "partial"},
107         {MATCHCRITERIA_NOT_PARTIAL, "~partial"},
108         {MATCHCRITERIA_FOUND_IN_ADDRESSBOOK, "found_in_addressbook"},
109         {MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK, "~found_in_addressbook"},
110
111         {MATCHCRITERIA_SIZE_GREATER, "size_greater"},
112         {MATCHCRITERIA_SIZE_SMALLER, "size_smaller"},
113         {MATCHCRITERIA_SIZE_EQUAL,   "size_equal"},
114
115         /* content have to be read */
116         {MATCHCRITERIA_HEADER, "header"},
117         {MATCHCRITERIA_NOT_HEADER, "~header"},
118         {MATCHCRITERIA_HEADERS_PART, "headers_part"},
119         {MATCHCRITERIA_NOT_HEADERS_PART, "~headers_part"},
120         {MATCHCRITERIA_MESSAGE, "message"},
121         {MATCHCRITERIA_NOT_MESSAGE, "~message"},
122         {MATCHCRITERIA_BODY_PART, "body_part"},
123         {MATCHCRITERIA_NOT_BODY_PART, "~body_part"},
124         {MATCHCRITERIA_TEST, "test"},
125         {MATCHCRITERIA_NOT_TEST, "~test"},
126
127         /* match type */
128         {MATCHTYPE_MATCHCASE, "matchcase"},
129         {MATCHTYPE_MATCH, "match"},
130         {MATCHTYPE_REGEXPCASE, "regexpcase"},
131         {MATCHTYPE_REGEXP, "regexp"},
132
133         /* actions */
134         {MATCHACTION_SCORE, "score"},    /* for backward compatibility */
135         {MATCHACTION_MOVE, "move"},
136         {MATCHACTION_COPY, "copy"},
137         {MATCHACTION_DELETE, "delete"},
138         {MATCHACTION_MARK, "mark"},
139         {MATCHACTION_UNMARK, "unmark"},
140         {MATCHACTION_LOCK, "lock"},
141         {MATCHACTION_UNLOCK, "unlock"},
142         {MATCHACTION_MARK_AS_READ, "mark_as_read"},
143         {MATCHACTION_MARK_AS_UNREAD, "mark_as_unread"},
144         {MATCHACTION_FORWARD, "forward"},
145         {MATCHACTION_FORWARD_AS_ATTACHMENT, "forward_as_attachment"},
146         {MATCHACTION_EXECUTE, "execute"},
147         {MATCHACTION_COLOR, "color"},
148         {MATCHACTION_REDIRECT, "redirect"},
149         {MATCHACTION_CHANGE_SCORE, "change_score"},
150         {MATCHACTION_SET_SCORE, "set_score"},
151         {MATCHACTION_STOP, "stop"},
152         {MATCHACTION_HIDE, "hide"},
153         {MATCHACTION_IGNORE, "ignore"},
154 };
155
156 enum {
157         MATCH_ANY = 0,
158         MATCH_ALL = 1,
159         MATCH_ONE = 2
160 };
161
162 /*!
163  *\brief        Look up table with keywords defined in \sa matchparser_tab
164  */
165 static GHashTable *matchparser_hashtab;
166
167 /*!
168  *\brief        Translate keyword id to keyword string
169  *
170  *\param        id Id of keyword
171  *
172  *\return       const gchar * Keyword
173  */
174 const gchar *get_matchparser_tab_str(gint id)
175 {
176         gint i;
177
178         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
179                 if (matchparser_tab[i].id == id)
180                         return matchparser_tab[i].str;
181         }
182         return NULL;
183 }
184
185 /*!
186  *\brief        Create keyword lookup table
187  */
188 static void create_matchparser_hashtab(void)
189 {
190         int i;
191         
192         if (matchparser_hashtab) return;
193         matchparser_hashtab = g_hash_table_new(g_str_hash, g_str_equal);
194         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++)
195                 g_hash_table_insert(matchparser_hashtab,
196                                     matchparser_tab[i].str,
197                                     (gpointer) &matchparser_tab[i]);
198 }
199
200 /*!
201  *\brief        Return a keyword id from a keyword string
202  *
203  *\param        str Keyword string
204  *
205  *\return       gint Keyword id
206  */
207 gint get_matchparser_tab_id(const gchar *str)
208 {
209         MatchParser *res;
210
211         if (NULL != (res = g_hash_table_lookup(matchparser_hashtab, str))) {
212                 return res->id;
213         } else
214                 return -1;
215 }
216
217 /* **************** data structure allocation **************** */
218
219 /*!
220  *\brief        Allocate a structure for a filtering / scoring
221  *              "condition" (a matcher structure)
222  *
223  *\param        criteria Criteria ID (MATCHCRITERIA_XXXX)
224  *\param        header Header string (if criteria is MATCHCRITERIA_HEADER
225                         or MATCHCRITERIA_FOUND_IN_ADDRESSBOOK)
226  *\param        matchtype Type of action (MATCHTYPE_XXX)
227  *\param        expr String value or expression to check
228  *\param        value Integer value to check
229  *
230  *\return       MatcherProp * Pointer to newly allocated structure
231  */
232 MatcherProp *matcherprop_new(gint criteria, const gchar *header,
233                               gint matchtype, const gchar *expr,
234                               int value)
235 {
236         MatcherProp *prop;
237
238         prop = g_new0(MatcherProp, 1);
239         prop->criteria = criteria;
240         prop->header = header != NULL ? g_strdup(header) : NULL;
241         prop->expr = expr != NULL ? g_strdup(expr) : NULL;
242         prop->matchtype = matchtype;
243         prop->preg = NULL;
244         prop->value = value;
245         prop->error = 0;
246
247         return prop;
248 }
249
250 /*!
251  *\brief        Free a matcher structure
252  *
253  *\param        prop Pointer to matcher structure allocated with
254  *              #matcherprop_new
255  */
256 void matcherprop_free(MatcherProp *prop)
257 {
258         g_free(prop->expr);
259         g_free(prop->header);
260         if (prop->preg != NULL) {
261                 regfree(prop->preg);
262                 g_free(prop->preg);
263         }
264         g_free(prop);
265 }
266
267 /*!
268  *\brief        Copy a matcher structure
269  *
270  *\param        src Matcher structure to copy
271  *
272  *\return       MatcherProp * Pointer to newly allocated matcher structure
273  */
274 MatcherProp *matcherprop_copy(const MatcherProp *src)
275 {
276         MatcherProp *prop = g_new0(MatcherProp, 1);
277         
278         prop->criteria = src->criteria;
279         prop->header = src->header ? g_strdup(src->header) : NULL;
280         prop->expr = src->expr ? g_strdup(src->expr) : NULL;
281         prop->matchtype = src->matchtype;
282         
283         prop->preg = NULL; /* will be re-evaluated */
284         prop->value = src->value;
285         prop->error = src->error;       
286         return prop;            
287 }
288
289 /* ************** match ******************************/
290
291 static gboolean match_with_addresses_in_addressbook
292         (MatcherProp *prop, GSList *address_list, gint type,
293          gchar* folderpath, gint match)
294 {
295         GSList *walk = NULL;
296         gboolean found = FALSE;
297         gchar *path = NULL;
298
299         g_return_val_if_fail(address_list != NULL, FALSE);
300
301         debug_print("match_with_addresses_in_addressbook(%d, %s)\n",
302                                 g_slist_length(address_list), folderpath);
303
304         if (folderpath == NULL ||
305                 strcasecmp(folderpath, _("Any")) == 0 ||
306                 *folderpath == '\0')
307                 path = NULL;
308         else
309                 path = folderpath;
310         
311         start_address_completion(path);
312
313         for (walk = address_list; walk != NULL; walk = walk->next) {
314                 /* exact matching of email address */
315                 guint num_addr = complete_address(walk->data);
316                 found = FALSE;
317                 if (num_addr > 1) {
318                         /* skip first item (this is the search string itself) */
319                         int i = 1;
320                         for (; i < num_addr && !found; i++) {
321                                 gchar *addr = get_complete_address(i);
322                                 extract_address(addr);
323                                 if (strcasecmp(addr, walk->data) == 0)
324                                         found = TRUE;
325                                 g_free(addr);
326                         }
327                 }
328                 g_free(walk->data);
329
330                 if (match == MATCH_ALL) {
331                         /* if matching all addresses, stop if one doesn't match */
332                         if (!found)
333                         break;
334                 } else if (match == MATCH_ANY) {
335                         /* if matching any address, stop if one does match */
336                         if (found)
337                                 break;
338         }
339                 /* MATCH_ONE: there should be only one loop iteration */
340         }
341
342         end_address_completion();
343         
344         return found;
345 }
346
347 /*!
348  *\brief        Find out if a string matches a condition
349  *
350  *\param        prop Matcher structure
351  *\param        str String to check 
352  *
353  *\return       gboolean TRUE if str matches the condition in the 
354  *              matcher structure
355  */
356 static gboolean matcherprop_string_match(MatcherProp *prop, const gchar *str)
357 {
358         gchar *str1;
359         gchar *str2;
360
361         if (str == NULL)
362                 return FALSE;
363
364         switch (prop->matchtype) {
365         case MATCHTYPE_REGEXPCASE:
366         case MATCHTYPE_REGEXP:
367                 if (!prop->preg && (prop->error == 0)) {
368                         prop->preg = g_new0(regex_t, 1);
369                         /* if regexp then don't use the escaped string */
370                         if (regcomp(prop->preg, prop->expr,
371                                     REG_NOSUB | REG_EXTENDED
372                                     | ((prop->matchtype == MATCHTYPE_REGEXPCASE)
373                                     ? REG_ICASE : 0)) != 0) {
374                                 prop->error = 1;
375                                 g_free(prop->preg);
376                                 prop->preg = NULL;
377                         }
378                 }
379                 if (prop->preg == NULL)
380                         return FALSE;
381                 
382                 if (regexec(prop->preg, str, 0, NULL, 0) == 0)
383                         return TRUE;
384                 else
385                         return FALSE;
386                         
387         case MATCHTYPE_MATCH:
388                 return (strstr(str, prop->expr) != NULL);
389
390         /* FIXME: put upper in unesc_str */
391         case MATCHTYPE_MATCHCASE:
392                 str2 = alloca(strlen(prop->expr) + 1);
393                 strcpy(str2, prop->expr);
394                 g_strup(str2);
395                 str1 = alloca(strlen(str) + 1);
396                 strcpy(str1, str);
397                 g_strup(str1);
398                 return (strstr(str1, str2) != NULL);
399                 
400         default:
401                 return FALSE;
402         }
403 }
404
405 /* FIXME body search is a hack. */
406 static gboolean matcherprop_string_decode_match(MatcherProp *prop, const gchar *str)
407 {
408         gchar *utf = NULL;
409         gchar tmp[BUFFSIZE];
410         gboolean res = FALSE;
411
412         if (str == NULL)
413                 return FALSE;
414
415         /* we try to decode QP first, because it's faster than base64 */
416         qp_decode_const(tmp, BUFFSIZE-1, str);
417         if (!g_utf8_validate(tmp, -1, NULL)) {
418                 utf = conv_codeset_strdup
419                         (tmp, conv_get_locale_charset_str_no_utf8(),
420                          CS_INTERNAL);
421                 res = matcherprop_string_match(prop, utf);
422                 g_free(utf);
423         } else {
424                 res = matcherprop_string_match(prop, tmp);
425         }
426         
427         if (res == FALSE && (strchr(prop->expr, '=') || strchr(prop->expr, '_')
428                             || strchr(str, '=') || strchr(str, '_'))) {
429                 /* if searching for something with an equal char, maybe 
430                  * we should try to match the non-decoded string. 
431                  * In case it was not qp-encoded. */
432                 if (!g_utf8_validate(str, -1, NULL)) {
433                         utf = conv_codeset_strdup
434                                 (str, conv_get_locale_charset_str_no_utf8(),
435                                  CS_INTERNAL);
436                         res = matcherprop_string_match(prop, utf);
437                         g_free(utf);
438                 } else {
439                         res = matcherprop_string_match(prop, str);
440                 }
441         }
442
443         /* FIXME base64 decoding is too slow, especially since text can 
444          * easily be handled as base64. Don't even try now. */
445
446         return res;
447 }
448
449 #ifdef USE_PTHREAD
450 typedef struct _thread_data {
451         const gchar *cmd;
452         gboolean done;
453 } thread_data;
454 #endif
455
456 #ifdef USE_PTHREAD
457 static void *matcher_test_thread(void *data)
458 {
459         thread_data *td = (thread_data *)data;
460         int result = -1;
461
462         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
463         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
464
465         result = system(td->cmd);
466         if (result) perror("system");
467         td->done = TRUE; /* let the caller thread join() */
468         return GINT_TO_POINTER(result);
469 }
470 #endif
471
472 /*!
473  *\brief        Execute a command defined in the matcher structure
474  *
475  *\param        prop Pointer to matcher structure
476  *\param        info Pointer to message info structure
477  *
478  *\return       gboolean TRUE if command was executed succesfully
479  */
480 static gboolean matcherprop_match_test(const MatcherProp *prop, 
481                                           MsgInfo *info)
482 {
483         gchar *file;
484         gchar *cmd;
485         gint retval;
486 #ifdef USE_PTHREAD
487         pthread_t pt;
488         thread_data *td = g_new0(thread_data, 1);
489         void *res = NULL;
490         time_t start_time = time(NULL);
491 #endif
492
493         file = procmsg_get_message_file(info);
494         if (file == NULL)
495                 return FALSE;
496         g_free(file);           
497
498         cmd = matching_build_command(prop->expr, info);
499         if (cmd == NULL)
500                 return FALSE;
501
502 #if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
503         td->cmd = cmd;
504         td->done = FALSE;
505         if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE, 
506                         matcher_test_thread, td) != 0)
507                 retval = system(cmd);
508         else {
509                 printf("waiting for test thread\n");
510                 while(!td->done) {
511                         /* don't let the interface freeze while waiting */
512                         claws_do_idle();
513                         if (time(NULL) - start_time > 30) {
514                                 pthread_cancel(pt);
515                                 td->done = TRUE;
516                                 retval = -1;
517                         }
518                 }
519                 pthread_join(pt, &res);
520                 retval = GPOINTER_TO_INT(res);
521                 printf(" test thread returned %d\n", retval);
522         }
523         g_free(td);
524 #else
525         retval = system(cmd);
526 #endif
527         debug_print("Command exit code: %d\n", retval);
528
529         g_free(cmd);
530         return (retval == 0);
531 }
532
533 /*!
534  *\brief        Check if a message matches the condition in a matcher
535  *              structure.
536  *
537  *\param        prop Pointer to matcher structure
538  *\param        info Pointer to message info
539  *
540  *\return       gboolean TRUE if a match
541  */
542 gboolean matcherprop_match(MatcherProp *prop, 
543                            MsgInfo *info)
544 {
545         time_t t;
546
547         switch(prop->criteria) {
548         case MATCHCRITERIA_ALL:
549                 return 1;
550         case MATCHCRITERIA_UNREAD:
551                 return MSG_IS_UNREAD(info->flags);
552         case MATCHCRITERIA_NOT_UNREAD:
553                 return !MSG_IS_UNREAD(info->flags);
554         case MATCHCRITERIA_NEW:
555                 return MSG_IS_NEW(info->flags);
556         case MATCHCRITERIA_NOT_NEW:
557                 return !MSG_IS_NEW(info->flags);
558         case MATCHCRITERIA_MARKED:
559                 return MSG_IS_MARKED(info->flags);
560         case MATCHCRITERIA_NOT_MARKED:
561                 return !MSG_IS_MARKED(info->flags);
562         case MATCHCRITERIA_DELETED:
563                 return MSG_IS_DELETED(info->flags);
564         case MATCHCRITERIA_NOT_DELETED:
565                 return !MSG_IS_DELETED(info->flags);
566         case MATCHCRITERIA_REPLIED:
567                 return MSG_IS_REPLIED(info->flags);
568         case MATCHCRITERIA_NOT_REPLIED:
569                 return !MSG_IS_REPLIED(info->flags);
570         case MATCHCRITERIA_FORWARDED:
571                 return MSG_IS_FORWARDED(info->flags);
572         case MATCHCRITERIA_NOT_FORWARDED:
573                 return !MSG_IS_FORWARDED(info->flags);
574         case MATCHCRITERIA_LOCKED:
575                 return MSG_IS_LOCKED(info->flags);
576         case MATCHCRITERIA_NOT_LOCKED:
577                 return !MSG_IS_LOCKED(info->flags);
578         case MATCHCRITERIA_SPAM:
579                 return MSG_IS_SPAM(info->flags);
580         case MATCHCRITERIA_NOT_SPAM:
581                 return !MSG_IS_SPAM(info->flags);
582         case MATCHCRITERIA_COLORLABEL:
583                 return MSG_GET_COLORLABEL_VALUE(info->flags) == prop->value; 
584         case MATCHCRITERIA_NOT_COLORLABEL:
585                 return MSG_GET_COLORLABEL_VALUE(info->flags) != prop->value;
586         case MATCHCRITERIA_IGNORE_THREAD:
587                 return MSG_IS_IGNORE_THREAD(info->flags);
588         case MATCHCRITERIA_NOT_IGNORE_THREAD:
589                 return !MSG_IS_IGNORE_THREAD(info->flags);
590         case MATCHCRITERIA_SUBJECT:
591                 return matcherprop_string_match(prop, info->subject);
592         case MATCHCRITERIA_NOT_SUBJECT:
593                 return !matcherprop_string_match(prop, info->subject);
594         case MATCHCRITERIA_FROM:
595                 return matcherprop_string_match(prop, info->from);
596         case MATCHCRITERIA_NOT_FROM:
597                 return !matcherprop_string_match(prop, info->from);
598         case MATCHCRITERIA_TO:
599                 return matcherprop_string_match(prop, info->to);
600         case MATCHCRITERIA_NOT_TO:
601                 return !matcherprop_string_match(prop, info->to);
602         case MATCHCRITERIA_CC:
603                 return matcherprop_string_match(prop, info->cc);
604         case MATCHCRITERIA_NOT_CC:
605                 return !matcherprop_string_match(prop, info->cc);
606         case MATCHCRITERIA_TO_OR_CC:
607                 return matcherprop_string_match(prop, info->to)
608                         || matcherprop_string_match(prop, info->cc);
609         case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
610                 return !(matcherprop_string_match(prop, info->to)
611                 || matcherprop_string_match(prop, info->cc));
612         case MATCHCRITERIA_AGE_GREATER:
613                 t = time(NULL);
614                 return ((t - info->date_t) / (60 * 60 * 24)) > prop->value;
615         case MATCHCRITERIA_AGE_LOWER:
616                 t = time(NULL);
617                 return ((t - info->date_t) / (60 * 60 * 24)) < prop->value;
618         case MATCHCRITERIA_SCORE_GREATER:
619                 return info->score > prop->value;
620         case MATCHCRITERIA_SCORE_LOWER:
621                 return info->score < prop->value;
622         case MATCHCRITERIA_SCORE_EQUAL:
623                 return info->score == prop->value;
624         case MATCHCRITERIA_SIZE_GREATER:
625                 /* FIXME: info->size is an off_t */
626                 return info->size > (off_t) prop->value;
627         case MATCHCRITERIA_SIZE_EQUAL:
628                 /* FIXME: info->size is an off_t */
629                 return info->size == (off_t) prop->value;
630         case MATCHCRITERIA_SIZE_SMALLER:
631                 /* FIXME: info->size is an off_t */
632                 return info->size <  (off_t) prop->value;
633         case MATCHCRITERIA_PARTIAL:
634                 /* FIXME: info->size is an off_t */
635                 return (info->total_size != 0 && info->size != (off_t)info->total_size);
636         case MATCHCRITERIA_NOT_PARTIAL:
637                 /* FIXME: info->size is an off_t */
638                 return (info->total_size == 0 || info->size == (off_t)info->total_size);
639         case MATCHCRITERIA_NEWSGROUPS:
640                 return matcherprop_string_match(prop, info->newsgroups);
641         case MATCHCRITERIA_NOT_NEWSGROUPS:
642                 return !matcherprop_string_match(prop, info->newsgroups);
643         case MATCHCRITERIA_INREPLYTO:
644                 return matcherprop_string_match(prop, info->inreplyto);
645         case MATCHCRITERIA_NOT_INREPLYTO:
646                 return !matcherprop_string_match(prop, info->inreplyto);
647         /* FIXME: Using inreplyto, but matching the (newly implemented)
648          * list of references is better */
649         case MATCHCRITERIA_REFERENCES:
650                 return matcherprop_string_match(prop, info->inreplyto);
651         case MATCHCRITERIA_NOT_REFERENCES:
652                 return !matcherprop_string_match(prop, info->inreplyto);
653         case MATCHCRITERIA_TEST:
654                 return matcherprop_match_test(prop, info);
655         case MATCHCRITERIA_NOT_TEST:
656                 return !matcherprop_match_test(prop, info);
657         default:
658                 return FALSE;
659         }
660 }
661
662 /* ********************* MatcherList *************************** */
663
664 /*!
665  *\brief        Create a new list of matchers 
666  *
667  *\param        matchers List of matcher structures
668  *\param        bool_and Operator
669  *
670  *\return       MatcherList * New list
671  */
672 MatcherList *matcherlist_new(GSList *matchers, gboolean bool_and)
673 {
674         MatcherList *cond;
675
676         cond = g_new0(MatcherList, 1);
677
678         cond->matchers = matchers;
679         cond->bool_and = bool_and;
680
681         return cond;
682 }
683
684 /*!
685  *\brief        Frees a list of matchers
686  *
687  *\param        cond List of matchers
688  */
689 void matcherlist_free(MatcherList *cond)
690 {
691         GSList *l;
692
693         g_return_if_fail(cond);
694         for (l = cond->matchers ; l != NULL ; l = g_slist_next(l)) {
695                 matcherprop_free((MatcherProp *) l->data);
696         }
697         g_free(cond);
698 }
699
700 /*!
701  *\brief        Skip all headers in a message file
702  *
703  *\param        fp Message file
704  */
705 static void matcherlist_skip_headers(FILE *fp)
706 {
707         gchar buf[BUFFSIZE];
708
709         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1)
710                 ;
711 }
712
713 /*!
714  *\brief        Check if a header matches a matcher condition
715  *
716  *\param        matcher Matcher structure to check header for
717  *\param        buf Header name
718  *
719  *\return       boolean TRUE if matching header
720  */
721 static gboolean matcherprop_match_one_header(MatcherProp *matcher,
722                                              gchar *buf)
723 {
724         gboolean result = FALSE;
725         Header *header = NULL;
726
727         switch (matcher->criteria) {
728         case MATCHCRITERIA_HEADER:
729         case MATCHCRITERIA_NOT_HEADER:
730                 header = procheader_parse_header(buf);
731                 if (!header)
732                         return FALSE;
733                 if (procheader_headername_equal(header->name,
734                                                 matcher->header)) {
735                         if (matcher->criteria == MATCHCRITERIA_HEADER)
736                                 result = matcherprop_string_match(matcher, header->body);
737                         else
738                                 result = !matcherprop_string_match(matcher, header->body);
739                         procheader_header_free(header);
740                         return result;
741                 }
742                 else {
743                         procheader_header_free(header);
744                 }
745                 break;
746         case MATCHCRITERIA_HEADERS_PART:
747                 return matcherprop_string_match(matcher, buf);
748         case MATCHCRITERIA_MESSAGE:
749                 return matcherprop_string_decode_match(matcher, buf);
750         case MATCHCRITERIA_NOT_MESSAGE:
751                 return !matcherprop_string_decode_match(matcher, buf);
752         case MATCHCRITERIA_NOT_HEADERS_PART:
753                 return !matcherprop_string_match(matcher, buf);
754         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
755         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
756                 {
757                         GSList *address_list = NULL;
758                         gint match = MATCH_ONE;
759                         gboolean found = FALSE;
760
761                         /* how many address headers are me trying to mach? */
762                         if (strcasecmp(matcher->header, _("Any")) == 0)
763                                 match = MATCH_ANY;
764                         else if (strcasecmp(matcher->header, Q_("Filtering Matcher Menu|All")) == 0)
765                                         match = MATCH_ALL;
766
767                         if (match == MATCH_ONE) {
768                                 /* matching one address header exactly, is that the right one? */
769                                 header = procheader_parse_header(buf);
770                                 if (!header ||
771                                                 !procheader_headername_equal(header->name, matcher->header))
772                                         return FALSE;
773                                 address_list = address_list_append(address_list, header->body);
774                                 if (address_list == NULL)
775                                         return FALSE;
776
777                         } else {
778                                 header = procheader_parse_header(buf);
779                                 if (!header)
780                                         return FALSE;
781                                 /* address header is one of the headers we have to match when checking
782                                    for any address header or all address headers? */
783                                 if (procheader_headername_equal(header->name, "From") ||
784                                          procheader_headername_equal(header->name, "To") ||
785                                          procheader_headername_equal(header->name, "Cc") ||
786                                          procheader_headername_equal(header->name, "Reply-To") ||
787                                          procheader_headername_equal(header->name, "Sender"))
788                                         address_list = address_list_append(address_list, header->body);
789                                 if (address_list == NULL)
790                                         return FALSE;
791                         }
792
793                         found = match_with_addresses_in_addressbook
794                                                         (matcher, address_list, matcher->criteria,
795                                                          matcher->expr, match);
796                         g_slist_free(address_list);
797
798                         if (matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK)
799                                 return !found;
800                         else
801                                 return found;
802         }
803         }
804
805         return FALSE;
806 }
807
808 /*!
809  *\brief        Check if the matcher structure wants headers to
810  *              be matched
811  *
812  *\param        matcher Matcher structure
813  *
814  *\return       gboolean TRUE if the matcher structure describes
815  *              a header match condition
816  */
817 static gboolean matcherprop_criteria_headers(const MatcherProp *matcher)
818 {
819         switch (matcher->criteria) {
820         case MATCHCRITERIA_HEADER:
821         case MATCHCRITERIA_NOT_HEADER:
822         case MATCHCRITERIA_HEADERS_PART:
823         case MATCHCRITERIA_NOT_HEADERS_PART:
824         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
825         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
826                 return TRUE;
827         default:
828                 return FALSE;
829         }
830 }
831
832 /*!
833  *\brief        Check if the matcher structure wants the message
834  *              to be matched (just perform an action on any
835  *              message)
836  *
837  *\param        matcher Matcher structure
838  *
839  *\return       gboolean TRUE if matcher condition should match
840  *              a message
841  */
842 static gboolean matcherprop_criteria_message(MatcherProp *matcher)
843 {
844         switch (matcher->criteria) {
845         case MATCHCRITERIA_MESSAGE:
846         case MATCHCRITERIA_NOT_MESSAGE:
847                 return TRUE;
848         default:
849                 return FALSE;
850         }
851 }
852
853 /*!
854  *\brief        Check if a list of conditions matches one header in
855  *              a message file.
856  *
857  *\param        matchers List of conditions
858  *\param        fp Message file
859  *
860  *\return       gboolean TRUE if one of the headers is matched by
861  *              the list of conditions. 
862  */
863 static gboolean matcherlist_match_headers(MatcherList *matchers, FILE *fp)
864 {
865         GSList *l;
866         gchar buf[BUFFSIZE];
867
868         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1) {
869                 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
870                         MatcherProp *matcher = (MatcherProp *) l->data;
871                         gint match = MATCH_ANY;
872
873                         if (matcher->done)
874                                 continue;
875
876                         /* determine the match range (all, any are our concern here) */
877                         if (matcher->criteria == MATCHCRITERIA_NOT_HEADERS_PART ||
878                             matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
879                                 match = MATCH_ALL;
880
881                         } else if (matcher->criteria == MATCHCRITERIA_FOUND_IN_ADDRESSBOOK ||
882                                            matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK) {
883                                 Header *header = NULL;
884
885                                 /* address header is one of the headers we have to match when checking
886                                    for any address header or all address headers? */
887                                 header = procheader_parse_header(buf);
888                                 if (header &&
889                                         (procheader_headername_equal(header->name, "From") ||
890                                          procheader_headername_equal(header->name, "To") ||
891                                          procheader_headername_equal(header->name, "Cc") ||
892                                          procheader_headername_equal(header->name, "Reply-To") ||
893                                          procheader_headername_equal(header->name, "Sender"))) {
894
895                                         if (strcasecmp(matcher->header, _("Any")) == 0)
896                                                 match = MATCH_ANY;
897                                         else if (strcasecmp(matcher->header, Q_("Filtering Matcher Menu|All")) == 0)
898                                                 match = MATCH_ALL;
899                                         else
900                                                 match = MATCH_ONE;
901                                 } else {
902                                         /* further call to matcherprop_match_one_header() can't match
903                                            and it irrelevant, so: don't alter the match result */
904                                         continue;
905                                 }
906                         }
907
908                         /* ZERO line must NOT match for the rule to match.
909                          */
910                         if (match == MATCH_ALL) {
911                                 if (matcherprop_match_one_header(matcher, buf)) {
912                                         matcher->result = TRUE;
913                                 } else {
914                                         matcher->result = FALSE;
915                                         matcher->done = TRUE;
916                                 }
917                         /* else, just one line matching is enough for the rule to match
918                          */
919                         } else if (matcherprop_criteria_headers(matcher) ||
920                                    matcherprop_criteria_message(matcher)) {
921                                 if (matcherprop_match_one_header(matcher, buf)) {
922                                         matcher->result = TRUE;
923                                         matcher->done = TRUE;
924                                 }
925                         }
926                         
927                         /* if the rule matched and the matchers are OR, no need to
928                          * check the others */
929                         if (matcher->result && matcher->done) {
930                                 if (!matchers->bool_and)
931                                         return TRUE;
932                         }
933                 }
934         }
935
936         return FALSE;
937 }
938
939 /*!
940  *\brief        Check if a matcher wants to check the message body
941  *
942  *\param        matcher Matcher structure
943  *
944  *\return       gboolean TRUE if body must be matched.
945  */
946 static gboolean matcherprop_criteria_body(const MatcherProp *matcher)
947 {
948         switch (matcher->criteria) {
949         case MATCHCRITERIA_BODY_PART:
950         case MATCHCRITERIA_NOT_BODY_PART:
951                 return TRUE;
952         default:
953                 return FALSE;
954         }
955 }
956
957 /*!
958  *\brief        Check if a (line) string matches the criteria
959  *              described by a matcher structure
960  *
961  *\param        matcher Matcher structure
962  *\param        line String
963  *
964  *\return       gboolean TRUE if string matches criteria
965  */
966 static gboolean matcherprop_match_line(MatcherProp *matcher, const gchar *line)
967 {
968         switch (matcher->criteria) {
969         case MATCHCRITERIA_BODY_PART:
970         case MATCHCRITERIA_MESSAGE:
971                 return matcherprop_string_decode_match(matcher, line);
972         case MATCHCRITERIA_NOT_BODY_PART:
973         case MATCHCRITERIA_NOT_MESSAGE:
974                 return !matcherprop_string_decode_match(matcher, line);
975         }
976         return FALSE;
977 }
978
979 /*!
980  *\brief        Check if a line in a message file's body matches
981  *              the criteria
982  *
983  *\param        matchers List of conditions
984  *\param        fp Message file
985  *
986  *\return       gboolean TRUE if succesful match
987  */
988 static gboolean matcherlist_match_body(MatcherList *matchers, FILE *fp)
989 {
990         GSList *l;
991         gchar buf[BUFFSIZE];
992         
993         while (fgets(buf, sizeof(buf), fp) != NULL) {
994                 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
995                         MatcherProp *matcher = (MatcherProp *) l->data;
996                         
997                         if (matcher->done) 
998                                 continue;
999
1000                         /* if the criteria is ~body_part or ~message, ZERO lines
1001                          * must NOT match for the rule to match. */
1002                         if (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1003                             matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1004                                 if (matcherprop_match_line(matcher, buf)) {
1005                                         matcher->result = TRUE;
1006                                 } else {
1007                                         matcher->result = FALSE;
1008                                         matcher->done = TRUE;
1009                                 }
1010                         /* else, just one line has to match */
1011                         } else if (matcherprop_criteria_body(matcher) ||
1012                                    matcherprop_criteria_message(matcher)) {
1013                                 if (matcherprop_match_line(matcher, buf)) {
1014                                         matcher->result = TRUE;
1015                                         matcher->done = TRUE;
1016                                 }
1017                         }
1018
1019                         /* if the matchers are OR'ed and the rule matched,
1020                          * no need to check the others. */
1021                         if (matcher->result && matcher->done) {
1022                                 if (!matchers->bool_and)
1023                                         return TRUE;
1024                         }
1025                 }
1026         }
1027         return FALSE;
1028 }
1029
1030 /*!
1031  *\brief        Check if a message file matches criteria
1032  *
1033  *\param        matchers Criteria
1034  *\param        info Message info
1035  *\param        result Default result
1036  *
1037  *\return       gboolean TRUE if matched
1038  */
1039 static gboolean matcherlist_match_file(MatcherList *matchers, MsgInfo *info,
1040                                 gboolean result)
1041 {
1042         gboolean read_headers;
1043         gboolean read_body;
1044         GSList *l;
1045         FILE *fp;
1046         gchar *file;
1047
1048         /* file need to be read ? */
1049
1050         read_headers = FALSE;
1051         read_body = FALSE;
1052         for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1053                 MatcherProp *matcher = (MatcherProp *) l->data;
1054
1055                 if (matcherprop_criteria_headers(matcher))
1056                         read_headers = TRUE;
1057                 if (matcherprop_criteria_body(matcher))
1058                         read_body = TRUE;
1059                 if (matcherprop_criteria_message(matcher)) {
1060                         read_headers = TRUE;
1061                         read_body = TRUE;
1062                 }
1063                 matcher->result = FALSE;
1064                 matcher->done = FALSE;
1065         }
1066
1067         if (!read_headers && !read_body)
1068                 return result;
1069
1070         file = procmsg_get_message_file_full(info, read_headers, read_body);
1071         if (file == NULL)
1072                 return FALSE;
1073
1074         if ((fp = g_fopen(file, "rb")) == NULL) {
1075                 FILE_OP_ERROR(file, "fopen");
1076                 g_free(file);
1077                 return result;
1078         }
1079
1080         /* read the headers */
1081
1082         if (read_headers) {
1083                 if (matcherlist_match_headers(matchers, fp))
1084                         read_body = FALSE;
1085         } else {
1086                 matcherlist_skip_headers(fp);
1087         }
1088
1089         /* read the body */
1090         if (read_body) {
1091                 matcherlist_match_body(matchers, fp);
1092         }
1093         
1094         for (l = matchers->matchers; l != NULL; l = g_slist_next(l)) {
1095                 MatcherProp *matcher = (MatcherProp *) l->data;
1096
1097                 if (matcherprop_criteria_headers(matcher) ||
1098                     matcherprop_criteria_body(matcher)    ||
1099                     matcherprop_criteria_message(matcher)) {
1100                         if (matcher->result) {
1101                                 if (!matchers->bool_and) {
1102                                         result = TRUE;
1103                                         break;
1104                                 }
1105                         }
1106                         else {
1107                                 if (matchers->bool_and) {
1108                                         result = FALSE;
1109                                         break;
1110                                 }
1111                         }
1112                 }                       
1113         }
1114
1115         g_free(file);
1116
1117         fclose(fp);
1118         
1119         return result;
1120 }
1121
1122 /*!
1123  *\brief        Test list of conditions on a message.
1124  *
1125  *\param        matchers List of conditions
1126  *\param        info Message info
1127  *
1128  *\return       gboolean TRUE if matched
1129  */
1130 gboolean matcherlist_match(MatcherList *matchers, MsgInfo *info)
1131 {
1132         GSList *l;
1133         gboolean result;
1134
1135         if (!matchers)
1136                 return FALSE;
1137
1138         if (matchers->bool_and)
1139                 result = TRUE;
1140         else
1141                 result = FALSE;
1142
1143         /* test the cached elements */
1144
1145         for (l = matchers->matchers; l != NULL ;l = g_slist_next(l)) {
1146                 MatcherProp *matcher = (MatcherProp *) l->data;
1147
1148                 switch(matcher->criteria) {
1149                 case MATCHCRITERIA_ALL:
1150                 case MATCHCRITERIA_UNREAD:
1151                 case MATCHCRITERIA_NOT_UNREAD:
1152                 case MATCHCRITERIA_NEW:
1153                 case MATCHCRITERIA_NOT_NEW:
1154                 case MATCHCRITERIA_MARKED:
1155                 case MATCHCRITERIA_NOT_MARKED:
1156                 case MATCHCRITERIA_DELETED:
1157                 case MATCHCRITERIA_NOT_DELETED:
1158                 case MATCHCRITERIA_REPLIED:
1159                 case MATCHCRITERIA_NOT_REPLIED:
1160                 case MATCHCRITERIA_FORWARDED:
1161                 case MATCHCRITERIA_NOT_FORWARDED:
1162                 case MATCHCRITERIA_LOCKED:
1163                 case MATCHCRITERIA_NOT_LOCKED:
1164                 case MATCHCRITERIA_SPAM:
1165                 case MATCHCRITERIA_NOT_SPAM:
1166                 case MATCHCRITERIA_COLORLABEL:
1167                 case MATCHCRITERIA_NOT_COLORLABEL:
1168                 case MATCHCRITERIA_IGNORE_THREAD:
1169                 case MATCHCRITERIA_NOT_IGNORE_THREAD:
1170                 case MATCHCRITERIA_SUBJECT:
1171                 case MATCHCRITERIA_NOT_SUBJECT:
1172                 case MATCHCRITERIA_FROM:
1173                 case MATCHCRITERIA_NOT_FROM:
1174                 case MATCHCRITERIA_TO:
1175                 case MATCHCRITERIA_NOT_TO:
1176                 case MATCHCRITERIA_CC:
1177                 case MATCHCRITERIA_NOT_CC:
1178                 case MATCHCRITERIA_TO_OR_CC:
1179                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
1180                 case MATCHCRITERIA_AGE_GREATER:
1181                 case MATCHCRITERIA_AGE_LOWER:
1182                 case MATCHCRITERIA_NEWSGROUPS:
1183                 case MATCHCRITERIA_NOT_NEWSGROUPS:
1184                 case MATCHCRITERIA_INREPLYTO:
1185                 case MATCHCRITERIA_NOT_INREPLYTO:
1186                 case MATCHCRITERIA_REFERENCES:
1187                 case MATCHCRITERIA_NOT_REFERENCES:
1188                 case MATCHCRITERIA_SCORE_GREATER:
1189                 case MATCHCRITERIA_SCORE_LOWER:
1190                 case MATCHCRITERIA_SCORE_EQUAL:
1191                 case MATCHCRITERIA_SIZE_GREATER:
1192                 case MATCHCRITERIA_SIZE_SMALLER:
1193                 case MATCHCRITERIA_SIZE_EQUAL:
1194                 case MATCHCRITERIA_TEST:
1195                 case MATCHCRITERIA_NOT_TEST:
1196                 case MATCHCRITERIA_PARTIAL:
1197                 case MATCHCRITERIA_NOT_PARTIAL:
1198                         if (matcherprop_match(matcher, info)) {
1199                                 if (!matchers->bool_and) {
1200                                         return TRUE;
1201                                 }
1202                         }
1203                         else {
1204                                 if (matchers->bool_and) {
1205                                         return FALSE;
1206                                 }
1207                         }
1208                 }
1209         }
1210
1211         /* test the condition on the file */
1212
1213         if (matcherlist_match_file(matchers, info, result)) {
1214                 if (!matchers->bool_and)
1215                         return TRUE;
1216         }
1217         else {
1218                 if (matchers->bool_and)
1219                         return FALSE;
1220         }
1221
1222         return result;
1223 }
1224
1225
1226 static gint quote_filter_str(gchar * result, guint size,
1227                              const gchar * path)
1228 {
1229         const gchar * p;
1230         gchar * result_p;
1231         guint remaining;
1232
1233         result_p = result;
1234         remaining = size;
1235
1236         for(p = path ; * p != '\0' ; p ++) {
1237
1238                 if ((* p != '\"') && (* p != '\\')) {
1239                         if (remaining > 0) {
1240                                 * result_p = * p;
1241                                 result_p ++; 
1242                                 remaining --;
1243                         }
1244                         else {
1245                                 result[size - 1] = '\0';
1246                                 return -1;
1247                         }
1248                 }
1249                 else { 
1250                         if (remaining >= 2) {
1251                                 * result_p = '\\';
1252                                 result_p ++; 
1253                                 * result_p = * p;
1254                                 result_p ++; 
1255                                 remaining -= 2;
1256                         }
1257                         else {
1258                                 result[size - 1] = '\0';
1259                                 return -1;
1260                         }
1261                 }
1262         }
1263         if (remaining > 0) {
1264                 * result_p = '\0';
1265         }
1266         else {
1267                 result[size - 1] = '\0';
1268                 return -1;
1269         }
1270   
1271         return 0;
1272 }
1273
1274
1275 gchar * matcher_quote_str(const gchar * src)
1276 {
1277         gchar * res;
1278         gint len;
1279         
1280         len = strlen(src) * 2 + 1;
1281         res = g_malloc(len);
1282         quote_filter_str(res, len, src);
1283         
1284         return res;
1285 }
1286
1287 /*!
1288  *\brief        Convert a matcher structure to a string
1289  *
1290  *\param        matcher Matcher structure
1291  *
1292  *\return       gchar * Newly allocated string
1293  */
1294 gchar *matcherprop_to_string(MatcherProp *matcher)
1295 {
1296         gchar *matcher_str = NULL;
1297         const gchar *criteria_str;
1298         const gchar *matchtype_str;
1299         int i;
1300         gchar * quoted_expr;
1301         gchar * quoted_header;
1302         
1303         criteria_str = NULL;
1304         for (i = 0; i < (int) (sizeof(matchparser_tab) / sizeof(MatchParser)); i++) {
1305                 if (matchparser_tab[i].id == matcher->criteria)
1306                         criteria_str = matchparser_tab[i].str;
1307         }
1308         if (criteria_str == NULL)
1309                 return NULL;
1310
1311         switch (matcher->criteria) {
1312         case MATCHCRITERIA_AGE_GREATER:
1313         case MATCHCRITERIA_AGE_LOWER:
1314         case MATCHCRITERIA_SCORE_GREATER:
1315         case MATCHCRITERIA_SCORE_LOWER:
1316         case MATCHCRITERIA_SCORE_EQUAL:
1317         case MATCHCRITERIA_SIZE_GREATER:
1318         case MATCHCRITERIA_SIZE_SMALLER:
1319         case MATCHCRITERIA_SIZE_EQUAL:
1320         case MATCHCRITERIA_COLORLABEL:
1321         case MATCHCRITERIA_NOT_COLORLABEL:
1322                 return g_strdup_printf("%s %i", criteria_str, matcher->value);
1323         case MATCHCRITERIA_ALL:
1324         case MATCHCRITERIA_UNREAD:
1325         case MATCHCRITERIA_NOT_UNREAD:
1326         case MATCHCRITERIA_NEW:
1327         case MATCHCRITERIA_NOT_NEW:
1328         case MATCHCRITERIA_MARKED:
1329         case MATCHCRITERIA_NOT_MARKED:
1330         case MATCHCRITERIA_DELETED:
1331         case MATCHCRITERIA_NOT_DELETED:
1332         case MATCHCRITERIA_REPLIED:
1333         case MATCHCRITERIA_NOT_REPLIED:
1334         case MATCHCRITERIA_FORWARDED:
1335         case MATCHCRITERIA_NOT_FORWARDED:
1336         case MATCHCRITERIA_LOCKED:
1337         case MATCHCRITERIA_NOT_LOCKED:
1338         case MATCHCRITERIA_SPAM:
1339         case MATCHCRITERIA_NOT_SPAM:
1340         case MATCHCRITERIA_PARTIAL:
1341         case MATCHCRITERIA_NOT_PARTIAL:
1342         case MATCHCRITERIA_IGNORE_THREAD:
1343         case MATCHCRITERIA_NOT_IGNORE_THREAD:
1344                 return g_strdup(criteria_str);
1345         case MATCHCRITERIA_TEST:
1346         case MATCHCRITERIA_NOT_TEST:
1347                 quoted_expr = matcher_quote_str(matcher->expr);
1348                 matcher_str = g_strdup_printf("%s \"%s\"",
1349                                               criteria_str, quoted_expr);
1350                 g_free(quoted_expr);
1351                 return matcher_str;
1352         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1353         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1354                 quoted_header = matcher_quote_str(matcher->header);
1355                 quoted_expr = matcher_quote_str(matcher->expr);
1356                 matcher_str = g_strdup_printf("%s \"%s\" in \"%s\"",
1357                                               criteria_str, quoted_header, quoted_expr);
1358                 g_free(quoted_header);
1359                 g_free(quoted_expr);
1360                 return matcher_str;
1361         }
1362
1363         matchtype_str = NULL;
1364         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
1365                 if (matchparser_tab[i].id == matcher->matchtype)
1366                         matchtype_str = matchparser_tab[i].str;
1367         }
1368
1369         if (matchtype_str == NULL)
1370                 return NULL;
1371
1372         switch (matcher->matchtype) {
1373         case MATCHTYPE_MATCH:
1374         case MATCHTYPE_MATCHCASE:
1375         case MATCHTYPE_REGEXP:
1376         case MATCHTYPE_REGEXPCASE:
1377                 quoted_expr = matcher_quote_str(matcher->expr);
1378                 if (matcher->header) {
1379                         quoted_header = matcher_quote_str(matcher->header);
1380                         matcher_str = g_strdup_printf
1381                                         ("%s \"%s\" %s \"%s\"",
1382                                          criteria_str, quoted_header,
1383                                          matchtype_str, quoted_expr);
1384                         g_free(quoted_header);
1385                 }
1386                 else
1387                         matcher_str = g_strdup_printf
1388                                         ("%s %s \"%s\"", criteria_str,
1389                                          matchtype_str, quoted_expr);
1390                 g_free(quoted_expr);
1391                 break;
1392         }
1393
1394         return matcher_str;
1395 }
1396
1397 /*!
1398  *\brief        Convert a list of conditions to a string
1399  *
1400  *\param        matchers List of conditions
1401  *
1402  *\return       gchar * Newly allocated string
1403  */
1404 gchar *matcherlist_to_string(const MatcherList *matchers)
1405 {
1406         gint count;
1407         gchar **vstr;
1408         GSList *l;
1409         gchar **cur_str;
1410         gchar *result = NULL;
1411
1412         count = g_slist_length(matchers->matchers);
1413         vstr = g_new(gchar *, count + 1);
1414
1415         for (l = matchers->matchers, cur_str = vstr; l != NULL;
1416              l = g_slist_next(l), cur_str ++) {
1417                 *cur_str = matcherprop_to_string((MatcherProp *) l->data);
1418                 if (*cur_str == NULL)
1419                         break;
1420         }
1421         *cur_str = NULL;
1422         
1423         if (matchers->bool_and)
1424                 result = g_strjoinv(" & ", vstr);
1425         else
1426                 result = g_strjoinv(" | ", vstr);
1427
1428         for (cur_str = vstr ; *cur_str != NULL ; cur_str ++)
1429                 g_free(*cur_str);
1430         g_free(vstr);
1431
1432         return result;
1433 }
1434
1435
1436 #define STRLEN_ZERO(s) ((s) ? strlen(s) : 0)
1437 #define STRLEN_DEFAULT(s,d) ((s) ? strlen(s) : STRLEN_ZERO(d))
1438
1439 static void add_str_default(gchar ** dest,
1440                             const gchar * s, const gchar * d)
1441 {
1442         gchar quoted_str[4096];
1443         const gchar * str;
1444         
1445         if (s != NULL)
1446                 str = s;
1447         else
1448                 str = d;
1449         
1450         quote_cmd_argument(quoted_str, sizeof(quoted_str), str);
1451         strcpy(* dest, quoted_str);
1452         
1453         (* dest) += strlen(* dest);
1454 }
1455
1456 /* matching_build_command() - preferably cmd should be unescaped */
1457 /*!
1458  *\brief        Build the command line to execute
1459  *
1460  *\param        cmd String with command line specifiers
1461  *\param        info Message info to use for command
1462  *
1463  *\return       gchar * Newly allocated string
1464  */
1465 gchar *matching_build_command(const gchar *cmd, MsgInfo *info)
1466 {
1467         const gchar *s = cmd;
1468         gchar *filename = NULL;
1469         gchar *processed_cmd;
1470         gchar *p;
1471         gint size;
1472
1473         const gchar *const no_subject    = _("(none)") ;
1474         const gchar *const no_from       = _("(none)") ;
1475         const gchar *const no_to         = _("(none)") ;
1476         const gchar *const no_cc         = _("(none)") ;
1477         const gchar *const no_date       = _("(none)") ;
1478         const gchar *const no_msgid      = _("(none)") ;
1479         const gchar *const no_newsgroups = _("(none)") ;
1480         const gchar *const no_references = _("(none)") ;
1481
1482         size = STRLEN_ZERO(cmd) + 1;
1483         while (*s != '\0') {
1484                 if (*s == '%') {
1485                         s++;
1486                         switch (*s) {
1487                         case '%':
1488                                 size -= 1;
1489                                 break;
1490                         case 's': /* subject */
1491                                 size += STRLEN_DEFAULT(info->subject, no_subject) - 2;
1492                                 break;
1493                         case 'f': /* from */
1494                                 size += STRLEN_DEFAULT(info->from, no_from) - 2;
1495                                 break;
1496                         case 't': /* to */
1497                                 size += STRLEN_DEFAULT(info->to, no_to) - 2;
1498                                 break;
1499                         case 'c': /* cc */
1500                                 size += STRLEN_DEFAULT(info->cc, no_cc) - 2;
1501                                 break;
1502                         case 'd': /* date */
1503                                 size += STRLEN_DEFAULT(info->date, no_date) - 2;
1504                                 break;
1505                         case 'i': /* message-id */
1506                                 size += STRLEN_DEFAULT(info->msgid, no_msgid) - 2;
1507                                 break;
1508                         case 'n': /* newsgroups */
1509                                 size += STRLEN_DEFAULT(info->newsgroups, no_newsgroups) - 2;
1510                                 break;
1511                         case 'r': /* references */
1512                                 /* FIXME: using the inreplyto header for reference */
1513                                 size += STRLEN_DEFAULT(info->inreplyto, no_references) - 2;
1514                                 break;
1515                         case 'F': /* file */
1516                                 if (filename == NULL)
1517                                         filename = folder_item_fetch_msg(info->folder, info->msgnum);
1518                                 
1519                                 if (filename == NULL) {
1520                                         g_warning("filename is not set");
1521                                         return NULL;
1522                                 }
1523                                 else {
1524                                         size += strlen(filename) - 2;
1525                                 }
1526                                 break;
1527                         }
1528                         s++;
1529                 }
1530                 else s++;
1531         }
1532         
1533         /* as the string can be quoted, we double the result */
1534         size *= 2;
1535
1536         processed_cmd = g_new0(gchar, size);
1537         s = cmd;
1538         p = processed_cmd;
1539
1540         while (*s != '\0') {
1541                 if (*s == '%') {
1542                         s++;
1543                         switch (*s) {
1544                         case '%':
1545                                 *p = '%';
1546                                 p++;
1547                                 break;
1548                         case 's': /* subject */
1549                                 add_str_default(&p, info->subject,
1550                                                 no_subject);
1551                                 break;
1552                         case 'f': /* from */
1553                                 add_str_default(&p, info->from,
1554                                                 no_from);
1555                                 break;
1556                         case 't': /* to */
1557                                 add_str_default(&p, info->to,
1558                                                 no_to);
1559                                 break;
1560                         case 'c': /* cc */
1561                                 add_str_default(&p, info->cc,
1562                                                 no_cc);
1563                                 break;
1564                         case 'd': /* date */
1565                                 add_str_default(&p, info->date,
1566                                                 no_date);
1567                                 break;
1568                         case 'i': /* message-id */
1569                                 add_str_default(&p, info->msgid,
1570                                                 no_msgid);
1571                                 break;
1572                         case 'n': /* newsgroups */
1573                                 add_str_default(&p, info->newsgroups,
1574                                                 no_newsgroups);
1575                                 break;
1576                         case 'r': /* references */
1577                                 /* FIXME: using the inreplyto header for references */
1578                                 add_str_default(&p, info->inreplyto, no_references);
1579                                 break;
1580                         case 'F': /* file */
1581                                 if (filename != NULL)
1582                                         add_str_default(&p, filename, NULL);
1583                                 break;
1584                         default:
1585                                 *p = '%';
1586                                 p++;
1587                                 *p = *s;
1588                                 p++;
1589                                 break;
1590                         }
1591                         s++;
1592                 }
1593                 else {
1594                         *p = *s;
1595                         p++;
1596                         s++;
1597                 }
1598         }
1599         g_free(filename);
1600         
1601         return processed_cmd;
1602 }
1603 #undef STRLEN_DEFAULT
1604 #undef STRLEN_ZERO
1605
1606 /* ************************************************************ */
1607
1608
1609 /*!
1610  *\brief        Write filtering list to file
1611  *
1612  *\param        fp File
1613  *\param        prefs_filtering List of filtering conditions
1614  */
1615 static void prefs_filtering_write(FILE *fp, GSList *prefs_filtering)
1616 {
1617         GSList *cur = NULL;
1618
1619         for (cur = prefs_filtering; cur != NULL; cur = cur->next) {
1620                 gchar *filtering_str = NULL;
1621                 gchar *tmp_name = NULL;
1622                 FilteringProp *prop = NULL;
1623
1624                 if (NULL == (prop = (FilteringProp *) cur->data))
1625                         continue;
1626                 
1627                 if (NULL == (filtering_str = filteringprop_to_string(prop)))
1628                         continue;
1629
1630                 if (prop->enabled) {
1631                         if (fputs("enabled ", fp) == EOF) {
1632                                 FILE_OP_ERROR("filtering config", "fputs");
1633                                 return;
1634                         }
1635                 } else {
1636                         if (fputs("disabled ", fp) == EOF) {
1637                                 FILE_OP_ERROR("filtering config", "fputs");
1638                                 return;
1639                         }
1640                 }
1641
1642                 if (fputs("rulename \"", fp) == EOF) {
1643                         FILE_OP_ERROR("filtering config", "fputs");
1644                         g_free(filtering_str);
1645                         return;
1646                 }
1647                 tmp_name = prop->name;
1648                 while (tmp_name && *tmp_name != '\0') {
1649                         if (*tmp_name != '"') {
1650                                 if (fputc(*tmp_name, fp) == EOF) {
1651                                         FILE_OP_ERROR("filtering config", "fputs || fputc");
1652                                         g_free(filtering_str);
1653                                         return;
1654                                 }
1655                         } else if (*tmp_name == '"') {
1656                                 if (fputc('\\', fp) == EOF ||
1657                                     fputc('"', fp) == EOF) {
1658                                         FILE_OP_ERROR("filtering config", "fputs || fputc");
1659                                         g_free(filtering_str);
1660                                         return;
1661                                 }
1662                         }
1663                         tmp_name ++;
1664                 }
1665                 if (fputs("\" ", fp) == EOF) {
1666                         FILE_OP_ERROR("filtering config", "fputs");
1667                         g_free(filtering_str);
1668                         return;
1669                 }
1670
1671                 if (prop->account_id != 0) {
1672                         gchar *tmp = NULL;
1673
1674                         tmp = g_strdup_printf("account %d ", prop->account_id);
1675                         if (fputs(tmp, fp) == EOF) {
1676                                 FILE_OP_ERROR("filtering config", "fputs");
1677                                 g_free(tmp);
1678                                 return;
1679                         }
1680                         g_free(tmp);
1681                 }
1682
1683                 if(fputs(filtering_str, fp) == EOF ||
1684                     fputc('\n', fp) == EOF) {
1685                         FILE_OP_ERROR("filtering config", "fputs || fputc");
1686                         g_free(filtering_str);
1687                         return;
1688                 }
1689                 g_free(filtering_str);
1690         }
1691 }
1692
1693 /*!
1694  *\brief        Write matchers from a folder item
1695  *
1696  *\param        node Node with folder info
1697  *\param        data File pointer
1698  *
1699  *\return       gboolean FALSE
1700  */
1701 static gboolean prefs_matcher_write_func(GNode *node, gpointer data)
1702 {
1703         FolderItem *item;
1704         FILE *fp = data;
1705         gchar *id;
1706         GSList *prefs_filtering;
1707
1708         item = node->data;
1709         /* prevent warning */
1710         if (item->path == NULL)
1711                 return FALSE;
1712         id = folder_item_get_identifier(item);
1713         if (id == NULL)
1714                 return FALSE;
1715         prefs_filtering = item->prefs->processing;
1716
1717         if (prefs_filtering != NULL) {
1718                 fprintf(fp, "[%s]\n", id);
1719                 prefs_filtering_write(fp, prefs_filtering);
1720                 fputc('\n', fp);
1721         }
1722
1723         g_free(id);
1724
1725         return FALSE;
1726 }
1727
1728 /*!
1729  *\brief        Save matchers from folder items
1730  *
1731  *\param        fp File
1732  */
1733 static void prefs_matcher_save(FILE *fp)
1734 {
1735         GList *cur;
1736
1737         for (cur = folder_get_list() ; cur != NULL ; cur = g_list_next(cur)) {
1738                 Folder *folder;
1739
1740                 folder = (Folder *) cur->data;
1741                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
1742                                 prefs_matcher_write_func, fp);
1743         }
1744         
1745         /* pre global rules */
1746         fprintf(fp, "[preglobal]\n");
1747         prefs_filtering_write(fp, pre_global_processing);
1748         fputc('\n', fp);
1749
1750         /* post global rules */
1751         fprintf(fp, "[postglobal]\n");
1752         prefs_filtering_write(fp, post_global_processing);
1753         fputc('\n', fp);
1754         
1755         /* filtering rules */
1756         fprintf(fp, "[filtering]\n");
1757         prefs_filtering_write(fp, filtering_rules);
1758         fputc('\n', fp);
1759 }
1760
1761 /*!
1762  *\brief        Write filtering / matcher configuration file
1763  */
1764 void prefs_matcher_write_config(void)
1765 {
1766         gchar *rcpath;
1767         PrefFile *pfile;
1768
1769         debug_print("Writing matcher configuration...\n");
1770
1771         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1772                              MATCHER_RC, NULL);
1773
1774         if ((pfile = prefs_write_open(rcpath)) == NULL) {
1775                 g_warning("failed to write configuration to file\n");
1776                 g_free(rcpath);
1777                 return;
1778         }
1779
1780
1781         prefs_matcher_save(pfile->fp);
1782
1783         g_free(rcpath);
1784
1785         if (prefs_file_close(pfile) < 0) {
1786                 g_warning("failed to write configuration to file\n");
1787                 return;
1788         }
1789 }
1790
1791 /* ******************************************************************* */
1792
1793 static void matcher_add_rulenames(const gchar *rcpath)
1794 {
1795         gchar *newpath = g_strconcat(rcpath, ".new", NULL);
1796         FILE *src = g_fopen(rcpath, "rb");
1797         FILE *dst = g_fopen(newpath, "wb");
1798         gchar buf[BUFFSIZE];
1799
1800         if (dst == NULL) {
1801                 perror("fopen");
1802                 g_free(newpath);
1803                 return;
1804         }
1805
1806         while (fgets (buf, sizeof(buf), src) != NULL) {
1807                 if (strlen(buf) > 2 && buf[0] != '['
1808                 && strncmp(buf, "rulename \"", 10)
1809                 && strncmp(buf, "enabled rulename \"", 18)
1810                 && strncmp(buf, "disabled rulename \"", 18)) {
1811                         fwrite("enabled rulename \"\" ",
1812                                 strlen("enabled rulename \"\" "), 1, dst);
1813                 }
1814                 fwrite(buf, strlen(buf), 1, dst);
1815         }
1816         fclose(dst);
1817         fclose(src);
1818         move_file(newpath, rcpath, TRUE);
1819         g_free(newpath);
1820 }
1821
1822 /*!
1823  *\brief        Read matcher configuration
1824  */
1825 void prefs_matcher_read_config(void)
1826 {
1827         gchar *rcpath;
1828         gchar *rc_old_format;
1829         FILE *f;
1830
1831         create_matchparser_hashtab();
1832         prefs_filtering_clear();
1833
1834         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, NULL);
1835         rc_old_format = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, 
1836                                 ".pre_names", NULL);
1837         
1838         if (!is_file_exist(rc_old_format) && is_file_exist(rcpath)) {
1839                 /* backup file with no rules names, in case 
1840                  * anything goes wrong */
1841                 copy_file(rcpath, rc_old_format, FALSE);
1842                 /* now hack the file in order to have it to the new format */
1843                 matcher_add_rulenames(rcpath);
1844         }
1845         
1846         g_free(rc_old_format);
1847
1848         f = g_fopen(rcpath, "rb");
1849         g_free(rcpath);
1850
1851         if (f != NULL) {
1852                 matcher_parser_start_parsing(f);
1853                 fclose(matcher_parserin);
1854         }
1855         else {
1856                 /* previous version compatibility */
1857
1858                 /* printf("reading filtering\n"); */
1859                 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1860                                      FILTERING_RC, NULL);
1861                 f = g_fopen(rcpath, "rb");
1862                 g_free(rcpath);
1863                 
1864                 if (f != NULL) {
1865                         matcher_parser_start_parsing(f);
1866                         fclose(matcher_parserin);
1867                 }
1868                 
1869                 /* printf("reading scoring\n"); */
1870                 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1871                                      SCORING_RC, NULL);
1872                 f = g_fopen(rcpath, "rb");
1873                 g_free(rcpath);
1874                 
1875                 if (f != NULL) {
1876                         matcher_parser_start_parsing(f);
1877                         fclose(matcher_parserin);
1878                 }
1879         }
1880 }