Fix printed PDF quality
[claws.git] / src / matcher.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2002-2012 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 3 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, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <errno.h>
31
32 #ifdef USE_PTHREAD
33 #include <pthread.h>
34 #endif
35
36 #include "defs.h"
37 #include "utils.h"
38 #include "procheader.h"
39 #include "matcher.h"
40 #include "matcher_parser.h"
41 #include "prefs_gtk.h"
42 #include "addr_compl.h"
43 #include "codeconv.h"
44 #include "quoted-printable.h"
45 #include "claws.h"
46 #include <ctype.h>
47 #include "prefs_common.h"
48 #include "log.h"
49 #include "tags.h"
50 #include "folder_item_prefs.h"
51 #include "procmsg.h"
52
53 /*!
54  *\brief        Keyword lookup element
55  */
56 struct _MatchParser {
57         gint id;                /*!< keyword id */ 
58         gchar *str;             /*!< keyword */
59 };
60 typedef struct _MatchParser MatchParser;
61
62 /*!
63  *\brief        Table with strings and ids used by the lexer and
64  *              the parser. New keywords can be added here.
65  */
66 static const MatchParser matchparser_tab[] = {
67         /* msginfo flags */
68         {MATCHCRITERIA_ALL, "all"},
69         {MATCHCRITERIA_UNREAD, "unread"},
70         {MATCHCRITERIA_NOT_UNREAD, "~unread"},
71         {MATCHCRITERIA_NEW, "new"},
72         {MATCHCRITERIA_NOT_NEW, "~new"},
73         {MATCHCRITERIA_MARKED, "marked"},
74         {MATCHCRITERIA_NOT_MARKED, "~marked"},
75         {MATCHCRITERIA_DELETED, "deleted"},
76         {MATCHCRITERIA_NOT_DELETED, "~deleted"},
77         {MATCHCRITERIA_REPLIED, "replied"},
78         {MATCHCRITERIA_NOT_REPLIED, "~replied"},
79         {MATCHCRITERIA_FORWARDED, "forwarded"},
80         {MATCHCRITERIA_NOT_FORWARDED, "~forwarded"},
81         {MATCHCRITERIA_LOCKED, "locked"},
82         {MATCHCRITERIA_NOT_LOCKED, "~locked"},
83         {MATCHCRITERIA_COLORLABEL, "colorlabel"},
84         {MATCHCRITERIA_NOT_COLORLABEL, "~colorlabel"},
85         {MATCHCRITERIA_IGNORE_THREAD, "ignore_thread"},
86         {MATCHCRITERIA_NOT_IGNORE_THREAD, "~ignore_thread"},
87         {MATCHCRITERIA_WATCH_THREAD, "watch_thread"},
88         {MATCHCRITERIA_NOT_WATCH_THREAD, "~watch_thread"},
89         {MATCHCRITERIA_SPAM, "spam"},
90         {MATCHCRITERIA_NOT_SPAM, "~spam"},
91         {MATCHCRITERIA_HAS_ATTACHMENT, "has_attachment"},
92         {MATCHCRITERIA_HAS_NO_ATTACHMENT, "~has_attachment"},
93         {MATCHCRITERIA_SIGNED, "signed"},
94         {MATCHCRITERIA_NOT_SIGNED, "~signed"},
95
96         /* msginfo headers */
97         {MATCHCRITERIA_SUBJECT, "subject"},
98         {MATCHCRITERIA_NOT_SUBJECT, "~subject"},
99         {MATCHCRITERIA_FROM, "from"},
100         {MATCHCRITERIA_NOT_FROM, "~from"},
101         {MATCHCRITERIA_TO, "to"},
102         {MATCHCRITERIA_NOT_TO, "~to"},
103         {MATCHCRITERIA_CC, "cc"},
104         {MATCHCRITERIA_NOT_CC, "~cc"},
105         {MATCHCRITERIA_TO_OR_CC, "to_or_cc"},
106         {MATCHCRITERIA_NOT_TO_AND_NOT_CC, "~to_or_cc"},
107         {MATCHCRITERIA_TAG, "tag"},
108         {MATCHCRITERIA_NOT_TAG, "~tag"},
109         {MATCHCRITERIA_TAGGED, "tagged"},
110         {MATCHCRITERIA_NOT_TAGGED, "~tagged"},
111         {MATCHCRITERIA_AGE_GREATER, "age_greater"},
112         {MATCHCRITERIA_AGE_LOWER, "age_lower"},
113         {MATCHCRITERIA_AGE_GREATER_HOURS, "age_greater_hours"},
114         {MATCHCRITERIA_AGE_LOWER_HOURS, "age_lower_hours"},
115         {MATCHCRITERIA_NEWSGROUPS, "newsgroups"},
116         {MATCHCRITERIA_NOT_NEWSGROUPS, "~newsgroups"},
117         {MATCHCRITERIA_INREPLYTO, "inreplyto"},
118         {MATCHCRITERIA_NOT_INREPLYTO, "~inreplyto"},
119         {MATCHCRITERIA_REFERENCES, "references"},
120         {MATCHCRITERIA_NOT_REFERENCES, "~references"},
121         {MATCHCRITERIA_SCORE_GREATER, "score_greater"},
122         {MATCHCRITERIA_SCORE_LOWER, "score_lower"},
123         {MATCHCRITERIA_SCORE_EQUAL, "score_equal"},
124         {MATCHCRITERIA_PARTIAL, "partial"},
125         {MATCHCRITERIA_NOT_PARTIAL, "~partial"},
126         {MATCHCRITERIA_FOUND_IN_ADDRESSBOOK, "found_in_addressbook"},
127         {MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK, "~found_in_addressbook"},
128
129         {MATCHCRITERIA_SIZE_GREATER, "size_greater"},
130         {MATCHCRITERIA_SIZE_SMALLER, "size_smaller"},
131         {MATCHCRITERIA_SIZE_EQUAL,   "size_equal"},
132
133         /* content have to be read */
134         {MATCHCRITERIA_HEADER, "header"},
135         {MATCHCRITERIA_NOT_HEADER, "~header"},
136         {MATCHCRITERIA_HEADERS_PART, "headers_part"},
137         {MATCHCRITERIA_NOT_HEADERS_PART, "~headers_part"},
138         {MATCHCRITERIA_MESSAGE, "message"},
139         {MATCHCRITERIA_NOT_MESSAGE, "~message"},
140         {MATCHCRITERIA_BODY_PART, "body_part"},
141         {MATCHCRITERIA_NOT_BODY_PART, "~body_part"},
142         {MATCHCRITERIA_TEST, "test"},
143         {MATCHCRITERIA_NOT_TEST, "~test"},
144
145         /* match type */
146         {MATCHTYPE_MATCHCASE, "matchcase"},
147         {MATCHTYPE_MATCH, "match"},
148         {MATCHTYPE_REGEXPCASE, "regexpcase"},
149         {MATCHTYPE_REGEXP, "regexp"},
150
151         /* actions */
152         {MATCHACTION_SCORE, "score"},    /* for backward compatibility */
153         {MATCHACTION_MOVE, "move"},
154         {MATCHACTION_COPY, "copy"},
155         {MATCHACTION_DELETE, "delete"},
156         {MATCHACTION_MARK, "mark"},
157         {MATCHACTION_UNMARK, "unmark"},
158         {MATCHACTION_LOCK, "lock"},
159         {MATCHACTION_UNLOCK, "unlock"},
160         {MATCHACTION_MARK_AS_READ, "mark_as_read"},
161         {MATCHACTION_MARK_AS_UNREAD, "mark_as_unread"},
162         {MATCHACTION_MARK_AS_SPAM, "mark_as_spam"},
163         {MATCHACTION_MARK_AS_HAM, "mark_as_ham"},
164         {MATCHACTION_FORWARD, "forward"},
165         {MATCHACTION_FORWARD_AS_ATTACHMENT, "forward_as_attachment"},
166         {MATCHACTION_EXECUTE, "execute"},
167         {MATCHACTION_COLOR, "color"},
168         {MATCHACTION_REDIRECT, "redirect"},
169         {MATCHACTION_CHANGE_SCORE, "change_score"},
170         {MATCHACTION_SET_SCORE, "set_score"},
171         {MATCHACTION_STOP, "stop"},
172         {MATCHACTION_HIDE, "hide"},
173         {MATCHACTION_IGNORE, "ignore"},
174         {MATCHACTION_WATCH, "watch"},
175         {MATCHACTION_ADD_TO_ADDRESSBOOK, "add_to_addressbook"},
176         {MATCHACTION_SET_TAG, "set_tag"},
177         {MATCHACTION_UNSET_TAG, "unset_tag"},
178         {MATCHACTION_CLEAR_TAGS, "clear_tags"},
179 };
180
181 enum {
182         MATCH_ANY = 0,
183         MATCH_ALL = 1,
184         MATCH_ONE = 2
185 };
186
187 enum {
188         CONTEXT_SUBJECT,
189         CONTEXT_FROM,
190         CONTEXT_TO,
191         CONTEXT_CC,
192         CONTEXT_NEWSGROUPS,
193         CONTEXT_IN_REPLY_TO,
194         CONTEXT_REFERENCES,
195         CONTEXT_HEADER,
196         CONTEXT_HEADER_LINE,
197         CONTEXT_BODY_LINE,
198         CONTEXT_TAG,
199         N_CONTEXT_STRS
200 };
201
202 static gchar *context_str[N_CONTEXT_STRS];
203
204 void matcher_init(void)
205 {
206         if (context_str[CONTEXT_SUBJECT] != NULL)
207                 return;
208
209         context_str[CONTEXT_SUBJECT] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Subject:"));
210         context_str[CONTEXT_FROM] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("From:"));
211         context_str[CONTEXT_TO] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("To:"));
212         context_str[CONTEXT_CC] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Cc:"));
213         context_str[CONTEXT_NEWSGROUPS] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("Newsgroups:"));
214         context_str[CONTEXT_IN_REPLY_TO] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("In-Reply-To:"));
215         context_str[CONTEXT_REFERENCES] = g_strdup_printf(_("%s header"), prefs_common_translated_header_name("References:"));
216         context_str[CONTEXT_HEADER] = g_strdup(_("header"));
217         context_str[CONTEXT_HEADER_LINE] = g_strdup(_("header line"));
218         context_str[CONTEXT_BODY_LINE] = g_strdup(_("body line"));
219         context_str[CONTEXT_TAG]  = g_strdup(_("tag"));
220 }
221
222 void matcher_done(void)
223 {
224         int i;
225         for (i = 0; i < N_CONTEXT_STRS; i++) {
226                 g_free(context_str[i]);
227                 context_str[i] = NULL;
228         }
229 }
230
231 extern gboolean debug_filtering_session;
232
233 /*!
234  *\brief        Look up table with keywords defined in \sa matchparser_tab
235  */
236 static GHashTable *matchparser_hashtab;
237
238 /*!
239  *\brief        Translate keyword id to keyword string
240  *
241  *\param        id Id of keyword
242  *
243  *\return       const gchar * Keyword
244  */
245 const gchar *get_matchparser_tab_str(gint id)
246 {
247         gint i;
248
249         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
250                 if (matchparser_tab[i].id == id)
251                         return matchparser_tab[i].str;
252         }
253         return NULL;
254 }
255
256 /*!
257  *\brief        Create keyword lookup table
258  */
259 static void create_matchparser_hashtab(void)
260 {
261         int i;
262         
263         if (matchparser_hashtab) return;
264         matchparser_hashtab = g_hash_table_new(g_str_hash, g_str_equal);
265         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++)
266                 g_hash_table_insert(matchparser_hashtab,
267                                     matchparser_tab[i].str,
268                                     (gpointer) &matchparser_tab[i]);
269 }
270
271 /*!
272  *\brief        Return a keyword id from a keyword string
273  *
274  *\param        str Keyword string
275  *
276  *\return       gint Keyword id
277  */
278 gint get_matchparser_tab_id(const gchar *str)
279 {
280         MatchParser *res;
281
282         if (NULL != (res = g_hash_table_lookup(matchparser_hashtab, str))) {
283                 return res->id;
284         } else
285                 return -1;
286 }
287
288 /* **************** data structure allocation **************** */
289
290 /*!
291  *\brief        Allocate a structure for a filtering / scoring
292  *              "condition" (a matcher structure)
293  *
294  *\param        criteria Criteria ID (MATCHCRITERIA_XXXX)
295  *\param        header Header string (if criteria is MATCHCRITERIA_HEADER
296                         or MATCHCRITERIA_FOUND_IN_ADDRESSBOOK)
297  *\param        matchtype Type of action (MATCHTYPE_XXX)
298  *\param        expr String value or expression to check
299  *\param        value Integer value to check
300  *
301  *\return       MatcherProp * Pointer to newly allocated structure
302  */
303 MatcherProp *matcherprop_new(gint criteria, const gchar *header,
304                               gint matchtype, const gchar *expr,
305                               int value)
306 {
307         MatcherProp *prop;
308
309         prop = g_new0(MatcherProp, 1);
310         prop->criteria = criteria;
311         prop->header = header != NULL ? g_strdup(header) : NULL;
312
313         prop->expr = expr != NULL ? g_strdup(expr) : NULL;
314
315         prop->matchtype = matchtype;
316         prop->preg = NULL;
317         prop->value = value;
318         prop->error = 0;
319
320         return prop;
321 }
322
323 /*!
324  *\brief        Free a matcher structure
325  *
326  *\param        prop Pointer to matcher structure allocated with
327  *              #matcherprop_new
328  */
329 void matcherprop_free(MatcherProp *prop)
330 {
331         g_free(prop->expr);
332         g_free(prop->header);
333         if (prop->preg != NULL) {
334                 regfree(prop->preg);
335                 g_free(prop->preg);
336         }
337         g_free(prop);
338 }
339
340 /*!
341  *\brief        Copy a matcher structure
342  *
343  *\param        src Matcher structure to copy
344  *
345  *\return       MatcherProp * Pointer to newly allocated matcher structure
346  */
347 MatcherProp *matcherprop_copy(const MatcherProp *src)
348 {
349         MatcherProp *prop = g_new0(MatcherProp, 1);
350         
351         prop->criteria = src->criteria;
352         prop->header = src->header ? g_strdup(src->header) : NULL;
353         prop->expr = src->expr ? g_strdup(src->expr) : NULL;
354         prop->matchtype = src->matchtype;
355         
356         prop->preg = NULL; /* will be re-evaluated */
357         prop->value = src->value;
358         prop->error = src->error;       
359         return prop;            
360 }
361
362 /* ************** match ******************************/
363
364 static gboolean match_with_addresses_in_addressbook
365         (MatcherProp *prop, GSList *address_list, gint type,
366          gchar* folderpath, gint match)
367 {
368         GSList *walk = NULL;
369         gboolean found = FALSE;
370         gchar *path = NULL;
371
372         cm_return_val_if_fail(address_list != NULL, FALSE);
373
374         debug_print("match_with_addresses_in_addressbook(%d, %s)\n",
375                                 g_slist_length(address_list), folderpath?folderpath:"(null)");
376
377         if (folderpath == NULL ||
378                 strcasecmp(folderpath, "Any") == 0 ||
379                 *folderpath == '\0')
380                 path = NULL;
381         else
382                 path = folderpath;
383         
384         start_address_completion(path);
385
386         for (walk = address_list; walk != NULL; walk = walk->next) {
387                 /* exact matching of email address */
388                 guint num_addr = complete_address(walk->data);
389                 found = FALSE;
390                 if (num_addr > 1) {
391                         /* skip first item (this is the search string itself) */
392                         int i = 1;
393                         for (; i < num_addr && !found; i++) {
394                                 gchar *addr = get_complete_address(i);
395                                 extract_address(addr);
396                                 if (strcasecmp(addr, walk->data) == 0) {
397                                         found = TRUE;
398
399                                         /* debug output */
400                                         if (debug_filtering_session
401                                                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
402                                                 log_print(LOG_DEBUG_FILTERING,
403                                                                 "address [ %s ] matches\n",
404                                                                 (gchar *)walk->data);
405                                         }
406                                 }
407                                 g_free(addr);
408                         }
409                 }
410                 /* debug output */
411                 if (debug_filtering_session
412                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH
413                                 && !found) {
414                         log_print(LOG_DEBUG_FILTERING,
415                                         "address [ %s ] does NOT match\n",
416                                         (gchar *)walk->data);
417                 }
418                 g_free(walk->data);
419
420                 if (match == MATCH_ALL) {
421                         /* if matching all addresses, stop if one doesn't match */
422                         if (!found) {
423                                 /* debug output */
424                                 if (debug_filtering_session
425                                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
426                                         log_print(LOG_DEBUG_FILTERING,
427                                                         "not all address match (matching all)\n");
428                                 }
429                                 break;
430                         }
431                 } else if (match == MATCH_ANY) {
432                         /* if matching any address, stop if one does match */
433                         if (found) {
434                                 /* debug output */
435                                 if (debug_filtering_session
436                                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
437                                         log_print(LOG_DEBUG_FILTERING,
438                                                         "at least one address matches (matching any)\n");
439                                 }
440                                 break;
441                         }
442                 }
443                 /* MATCH_ONE: there should be only one loop iteration */
444         }
445
446         end_address_completion();
447         
448         return found;
449 }
450
451 /*!
452  *\brief        Find out if a string matches a condition
453  *
454  *\param        prop Matcher structure
455  *\param        str String to check 
456  *
457  *\return       gboolean TRUE if str matches the condition in the 
458  *              matcher structure
459  */
460 static gboolean matcherprop_string_match(MatcherProp *prop, const gchar *str,
461                                          const gchar *debug_context)
462 {
463         gchar *str1;
464         gchar *down_expr;
465         gboolean ret = FALSE;
466         gboolean should_free = FALSE;
467         if (str == NULL)
468                 return FALSE;
469
470         if (prop->matchtype == MATCHTYPE_REGEXPCASE ||
471             prop->matchtype == MATCHTYPE_MATCHCASE) {
472                 str1 = g_utf8_casefold(str, -1);
473                 down_expr = g_utf8_casefold(prop->expr, -1);
474                 should_free = TRUE;
475         } else {
476                 str1 = (gchar *)str;
477                 down_expr = (gchar *)prop->expr;
478                 should_free = FALSE;
479         }
480
481         switch (prop->matchtype) {
482         case MATCHTYPE_REGEXPCASE:
483         case MATCHTYPE_REGEXP:
484 #ifndef G_OS_WIN32
485                 if (!prop->preg && (prop->error == 0)) {
486                         prop->preg = g_new0(regex_t, 1);
487                         /* if regexp then don't use the escaped string */
488                         if (regcomp(prop->preg, down_expr,
489                                     REG_NOSUB | REG_EXTENDED
490                                     | ((prop->matchtype == MATCHTYPE_REGEXPCASE)
491                                     ? REG_ICASE : 0)) != 0) {
492                                 prop->error = 1;
493                                 g_free(prop->preg);
494                                 prop->preg = NULL;
495                         }
496                 }
497                 if (prop->preg == NULL) {
498                         ret = FALSE;
499                         goto free_strs;
500                 }
501                 
502                 if (regexec(prop->preg, str1, 0, NULL, 0) == 0)
503                         ret = TRUE;
504                 else
505                         ret = FALSE;
506
507                 /* debug output */
508                 if (debug_filtering_session
509                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
510                         gchar *stripped = g_strdup(str);
511
512                         strretchomp(stripped);
513                         if (ret) {
514                                 log_print(LOG_DEBUG_FILTERING,
515                                                 "%s value [ %s ] matches regular expression [ %s ] (%s)\n",
516                                                 debug_context, stripped, prop->expr,
517                                                 prop->matchtype == MATCHTYPE_REGEXP ? _("Case sensitive"):_("Case insensitive"));
518                         } else {
519                                 log_print(LOG_DEBUG_FILTERING,
520                                                 "%s value [ %s ] does NOT match regular expression [ %s ] (%s)\n",
521                                                 debug_context, stripped, prop->expr,
522                                                 prop->matchtype == MATCHTYPE_REGEXP ? _("Case sensitive"):_("Case insensitive"));
523                         }
524                         g_free(stripped);
525                 }
526                 break;
527 #endif                  
528         case MATCHTYPE_MATCHCASE:
529         case MATCHTYPE_MATCH:
530                 ret = (strstr(str1, down_expr) != NULL);
531
532                 /* debug output */
533                 if (debug_filtering_session
534                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
535                         gchar *stripped = g_strdup(str);
536
537                         strretchomp(stripped);
538                         if (ret) {
539                                 log_print(LOG_DEBUG_FILTERING,
540                                                 "%s value [ %s ] contains [ %s ] (%s)\n",
541                                                 debug_context, stripped, prop->expr,
542                                                 prop->matchtype == MATCHTYPE_MATCH ? _("Case sensitive"):_("Case insensitive"));
543                         } else {
544                                 log_print(LOG_DEBUG_FILTERING,
545                                                 "%s value [ %s ] does NOT contain [ %s ] (%s)\n",
546                                                 debug_context, stripped, prop->expr,
547                                                 prop->matchtype == MATCHTYPE_MATCH ? _("Case sensitive"):_("Case insensitive"));
548                         }
549                         g_free(stripped);
550                 }
551                 break;
552
553         default:
554                 break;
555         }
556         
557 free_strs:
558         if (should_free) {
559                 g_free(str1);
560                 g_free(down_expr);
561         }
562         return ret;
563 }
564
565 /*!
566  *\brief        Find out if a tag matches a condition
567  *
568  *\param        prop Matcher structure
569  *\param        msginfo message to check
570  *
571  *\return       gboolean TRUE if msginfo matches the condition in the 
572  *              matcher structure
573  */
574 static gboolean matcherprop_tag_match(MatcherProp *prop, MsgInfo *msginfo,
575                                          const gchar *debug_context)
576 {
577         gboolean ret = FALSE;
578         GSList *cur;
579
580         if (msginfo == NULL || msginfo->tags == NULL)
581                 return FALSE;
582
583         for (cur = msginfo->tags; cur; cur = cur->next) {
584                 const gchar *str = tags_get_tag(GPOINTER_TO_INT(cur->data));
585                 if (!str)
586                         continue;
587                 if (matcherprop_string_match(prop, str, debug_context)) {
588                         ret = TRUE;
589                         break;
590                 }
591         }
592         return ret;
593 }
594
595 /*!
596  *\brief        Find out if the string-ed list matches a condition
597  *
598  *\param        prop Matcher structure
599  *\param        list GSList of strings to check
600  *
601  *\return       gboolean TRUE if str matches the condition in the 
602  *              matcher structure
603  */
604 static gboolean matcherprop_list_match(MatcherProp *prop, const GSList *list,
605 const gchar *debug_context)
606 {
607         const GSList *cur;
608
609         for(cur = list; cur != NULL; cur = cur->next) {
610                 if (matcherprop_string_match(prop, (gchar *)cur->data, debug_context))
611                         return TRUE;
612         }
613         return FALSE;
614 }
615
616 static gboolean matcherprop_header_line_match(MatcherProp *prop, const gchar *hdr,
617                                               const gchar *str, const gchar *debug_context)
618 {
619         gchar *line = NULL;
620         gboolean res = FALSE;
621
622         if (hdr == NULL || str == NULL)
623                 return FALSE;
624
625         line = g_strdup_printf("%s %s", hdr, str);
626         res = matcherprop_string_match(prop, line, debug_context);
627         g_free(line);
628        
629         return res;
630 }
631
632 #ifdef USE_PTHREAD
633 typedef struct _thread_data {
634         const gchar *cmd;
635         gboolean done;
636 } thread_data;
637 #endif
638
639 #ifdef USE_PTHREAD
640 static void *matcher_test_thread(void *data)
641 {
642         thread_data *td = (thread_data *)data;
643         int result = -1;
644
645         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
646         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
647
648         result = system(td->cmd);
649         td->done = TRUE; /* let the caller thread join() */
650         return GINT_TO_POINTER(result);
651 }
652 #endif
653
654 /*!
655  *\brief        Execute a command defined in the matcher structure
656  *
657  *\param        prop Pointer to matcher structure
658  *\param        info Pointer to message info structure
659  *
660  *\return       gboolean TRUE if command was executed succesfully
661  */
662 static gboolean matcherprop_match_test(const MatcherProp *prop, 
663                                           MsgInfo *info)
664 {
665         gchar *file;
666         gchar *cmd;
667         gint retval;
668 #ifdef USE_PTHREAD
669         pthread_t pt;
670         pthread_attr_t pta;
671         thread_data *td = g_new0(thread_data, 1);
672         void *res = NULL;
673         time_t start_time = time(NULL);
674 #endif
675
676         file = procmsg_get_message_file(info);
677         if (file == NULL) {
678 #ifdef USE_PTHREAD
679                 g_free(td);
680 #endif
681                 return FALSE;
682         }
683         g_free(file);           
684
685         cmd = matching_build_command(prop->expr, info);
686         if (cmd == NULL) {
687 #ifdef USE_PTHREAD
688                 g_free(td);
689 #endif  
690                 return FALSE;
691 }
692
693 #ifdef USE_PTHREAD
694         /* debug output */
695         if (debug_filtering_session
696                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
697                 log_print(LOG_DEBUG_FILTERING,
698                                 "starting threaded command [ %s ]\n",
699                                 cmd);
700         }
701
702         td->cmd = cmd;
703         td->done = FALSE;
704         if (pthread_attr_init(&pta) != 0 ||
705             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
706             pthread_create(&pt, &pta, matcher_test_thread, td) != 0)
707                 retval = system(cmd);
708         else {
709                 debug_print("waiting for test thread\n");
710                 while(!td->done) {
711                         /* don't let the interface freeze while waiting */
712                         claws_do_idle();
713                         if (time(NULL) - start_time > 30) {
714                                 pthread_cancel(pt);
715                                 td->done = TRUE;
716                                 retval = -1;
717                         }
718                 }
719                 pthread_join(pt, &res);
720                 retval = GPOINTER_TO_INT(res);
721                 debug_print(" test thread returned %d\n", retval);
722         }
723         g_free(td);
724 #else
725         /* debug output */
726         if (debug_filtering_session
727                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
728                 log_print(LOG_DEBUG_FILTERING,
729                                 "starting synchronous command [ %s ]\n",
730                                 cmd);
731         }
732
733         retval = system(cmd);
734 #endif
735         debug_print("Command exit code: %d\n", retval);
736
737         /* debug output */
738         if (debug_filtering_session
739                         && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
740                 log_print(LOG_DEBUG_FILTERING,
741                                 "command returned [ %d ]\n",
742                                 retval);
743         }
744
745         g_free(cmd);
746         return (retval == 0);
747 }
748
749 /*!
750  *\brief        Check if a message matches the condition in a matcher
751  *              structure.
752  *
753  *\param        prop Pointer to matcher structure
754  *\param        info Pointer to message info
755  *
756  *\return       gboolean TRUE if a match
757  */
758 static gboolean matcherprop_match(MatcherProp *prop, 
759                                   MsgInfo *info)
760 {
761         time_t t;
762         gint age_mult_hours = 1;
763
764         switch(prop->criteria) {
765         case MATCHCRITERIA_ALL:
766                 return TRUE;
767         case MATCHCRITERIA_UNREAD:
768                 return MSG_IS_UNREAD(info->flags);
769         case MATCHCRITERIA_NOT_UNREAD:
770                 return !MSG_IS_UNREAD(info->flags);
771         case MATCHCRITERIA_NEW:
772                 return MSG_IS_NEW(info->flags);
773         case MATCHCRITERIA_NOT_NEW:
774                 return !MSG_IS_NEW(info->flags);
775         case MATCHCRITERIA_MARKED:
776                 return MSG_IS_MARKED(info->flags);
777         case MATCHCRITERIA_NOT_MARKED:
778                 return !MSG_IS_MARKED(info->flags);
779         case MATCHCRITERIA_DELETED:
780                 return MSG_IS_DELETED(info->flags);
781         case MATCHCRITERIA_NOT_DELETED:
782                 return !MSG_IS_DELETED(info->flags);
783         case MATCHCRITERIA_REPLIED:
784                 return MSG_IS_REPLIED(info->flags);
785         case MATCHCRITERIA_NOT_REPLIED:
786                 return !MSG_IS_REPLIED(info->flags);
787         case MATCHCRITERIA_FORWARDED:
788                 return MSG_IS_FORWARDED(info->flags);
789         case MATCHCRITERIA_NOT_FORWARDED:
790                 return !MSG_IS_FORWARDED(info->flags);
791         case MATCHCRITERIA_LOCKED:
792                 return MSG_IS_LOCKED(info->flags);
793         case MATCHCRITERIA_NOT_LOCKED:
794                 return !MSG_IS_LOCKED(info->flags);
795         case MATCHCRITERIA_SPAM:
796                 return MSG_IS_SPAM(info->flags);
797         case MATCHCRITERIA_NOT_SPAM:
798                 return !MSG_IS_SPAM(info->flags);
799         case MATCHCRITERIA_HAS_ATTACHMENT:
800                 return MSG_IS_WITH_ATTACHMENT(info->flags);
801         case MATCHCRITERIA_HAS_NO_ATTACHMENT:
802                 return !MSG_IS_WITH_ATTACHMENT(info->flags);
803         case MATCHCRITERIA_SIGNED:
804                 return MSG_IS_SIGNED(info->flags);
805         case MATCHCRITERIA_NOT_SIGNED:
806                 return !MSG_IS_SIGNED(info->flags);
807         case MATCHCRITERIA_COLORLABEL:
808         {
809                 gint color = MSG_GET_COLORLABEL_VALUE(info->flags);
810                 gboolean ret = (color == prop->value);
811
812                 /* debug output */
813                 if (debug_filtering_session
814                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
815                         if (ret) {
816                                 log_print(LOG_DEBUG_FILTERING,
817                                                 "message color value [ %d ] matches color value [ %d ]\n",
818                                                 color, prop->value);
819                         } else {
820                                 log_print(LOG_DEBUG_FILTERING,
821                                                 "message color value [ %d ] does NOT match color value [ %d ]\n",
822                                                 color, prop->value);
823                         }
824                 }
825                 return ret;
826         }
827         case MATCHCRITERIA_NOT_COLORLABEL:
828         {
829                 gint color = MSG_GET_COLORLABEL_VALUE(info->flags);
830                 gboolean ret = (color != prop->value);
831
832                 /* debug output */
833                 if (debug_filtering_session
834                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
835                         if (ret) {
836                                 log_print(LOG_DEBUG_FILTERING,
837                                                 "message color value [ %d ] matches color value [ %d ]\n",
838                                                 color, prop->value);
839                         } else {
840                                 log_print(LOG_DEBUG_FILTERING,
841                                                 "message color value [ %d ] does NOT match color value [ %d ]\n",
842                                                 color, prop->value);
843                         }
844                 }
845                 return ret;
846         }
847         case MATCHCRITERIA_IGNORE_THREAD:
848                 return MSG_IS_IGNORE_THREAD(info->flags);
849         case MATCHCRITERIA_NOT_IGNORE_THREAD:
850                 return !MSG_IS_IGNORE_THREAD(info->flags);
851         case MATCHCRITERIA_WATCH_THREAD:
852                 return MSG_IS_WATCH_THREAD(info->flags);
853         case MATCHCRITERIA_NOT_WATCH_THREAD:
854                 return !MSG_IS_WATCH_THREAD(info->flags);
855         case MATCHCRITERIA_SUBJECT:
856                 return matcherprop_string_match(prop, info->subject, context_str[CONTEXT_SUBJECT]);
857         case MATCHCRITERIA_NOT_SUBJECT:
858                 return !matcherprop_string_match(prop, info->subject, context_str[CONTEXT_SUBJECT]);
859         case MATCHCRITERIA_FROM:
860                 return matcherprop_string_match(prop, info->from, context_str[CONTEXT_FROM]);
861         case MATCHCRITERIA_NOT_FROM:
862                 return !matcherprop_string_match(prop, info->from, context_str[CONTEXT_FROM]);
863         case MATCHCRITERIA_TO:
864                 return matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO]);
865         case MATCHCRITERIA_NOT_TO:
866                 return !matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO]);
867         case MATCHCRITERIA_CC:
868                 return matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
869         case MATCHCRITERIA_NOT_CC:
870                 return !matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
871         case MATCHCRITERIA_TO_OR_CC:
872                 return matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO])
873                      || matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
874         case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
875                 return !matcherprop_string_match(prop, info->to, context_str[CONTEXT_TO])
876                      && !matcherprop_string_match(prop, info->cc, context_str[CONTEXT_CC]);
877         case MATCHCRITERIA_TAG:
878                 return matcherprop_tag_match(prop, info, context_str[CONTEXT_TAG]);
879         case MATCHCRITERIA_NOT_TAG:
880                 return !matcherprop_tag_match(prop, info, context_str[CONTEXT_TAG]);
881         case MATCHCRITERIA_TAGGED:
882                 return info->tags != NULL;
883         case MATCHCRITERIA_NOT_TAGGED:
884                 return info->tags == NULL;
885         case MATCHCRITERIA_AGE_GREATER:
886                 age_mult_hours = 24;
887                 /* Fallthrough intended */
888         case MATCHCRITERIA_AGE_GREATER_HOURS:
889         {
890                 gboolean ret;
891                 gint age;
892
893                 t = time(NULL);
894                 age = ((t - info->date_t) / (60 * 60 * age_mult_hours));
895                 ret = (age >= prop->value);
896
897                 /* debug output */
898                 if (debug_filtering_session
899                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
900                         if (ret) {
901                                 log_print(LOG_DEBUG_FILTERING,
902                                                 "message age [ %d ] is greater than [ %d ]\n",
903                                                 age, prop->value);
904                         } else {
905                                 log_print(LOG_DEBUG_FILTERING,
906                                                 "message age [ %d ] is not greater than [ %d ]\n",
907                                                 age, prop->value);
908                         }
909                 }
910                 return ret;
911         }
912         case MATCHCRITERIA_AGE_LOWER:
913                 age_mult_hours = 24;
914                 /* Fallthrough intended */
915         case MATCHCRITERIA_AGE_LOWER_HOURS:
916         {
917                 gboolean ret;
918                 gint age;
919
920                 t = time(NULL);
921                 age = ((t - info->date_t) / (60 * 60 * age_mult_hours));
922                 ret = (age < prop->value);
923
924                 /* debug output */
925                 if (debug_filtering_session
926                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
927                         if (ret) {
928                                 log_print(LOG_DEBUG_FILTERING,
929                                                 "message age [ %d ] is lower than [ %d ]\n",
930                                                 age, prop->value);
931                         } else {
932                                 log_print(LOG_DEBUG_FILTERING,
933                                                 "message age [ %d ] is not lower than [ %d ]\n",
934                                                 age, prop->value);
935                         }
936                 }
937                 return ret;
938         }
939         case MATCHCRITERIA_SCORE_GREATER:
940         {
941                 gboolean ret = (info->score > prop->value);
942
943                 /* debug output */
944                 if (debug_filtering_session
945                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
946                         if (ret) {
947                                 log_print(LOG_DEBUG_FILTERING,
948                                                 "message score [ %d ] is greater than [ %d ]\n",
949                                                 info->score, prop->value);
950                         } else {
951                                 log_print(LOG_DEBUG_FILTERING,
952                                                 "message score [ %d ] is not greater than [ %d ]\n",
953                                                 info->score, prop->value);
954                         }
955                 }
956                 return ret;
957         }
958         case MATCHCRITERIA_SCORE_LOWER:
959         {
960                 gboolean ret = (info->score < prop->value);
961
962                 /* debug output */
963                 if (debug_filtering_session
964                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
965                         if (ret) {
966                                 log_print(LOG_DEBUG_FILTERING,
967                                                 "message score [ %d ] is lower than [ %d ]\n",
968                                                 info->score, prop->value);
969                         } else {
970                                 log_print(LOG_DEBUG_FILTERING,
971                                                 "message score [ %d ] is not lower than [ %d ]\n",
972                                                 info->score, prop->value);
973                         }
974                 }
975                 return ret;
976         }
977         case MATCHCRITERIA_SCORE_EQUAL:
978         {
979                 gboolean ret = (info->score == prop->value);
980
981                 /* debug output */
982                 if (debug_filtering_session
983                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
984                         if (ret) {
985                                 log_print(LOG_DEBUG_FILTERING,
986                                                 "message score [ %d ] is equal to [ %d ]\n",
987                                                 info->score, prop->value);
988                         } else {
989                                 log_print(LOG_DEBUG_FILTERING,
990                                                 "message score [ %d ] is not equal to [ %d ]\n",
991                                                 info->score, prop->value);
992                         }
993                 }
994                 return ret;
995         }
996         case MATCHCRITERIA_SIZE_GREATER:
997         {
998                 /* FIXME: info->size is a goffset */
999                 gboolean ret = (info->size > (goffset) prop->value);
1000
1001                 /* debug output */
1002                 if (debug_filtering_session
1003                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1004                         if (ret) {
1005                                 log_print(LOG_DEBUG_FILTERING,
1006                                                 "message size is greater than [ %d ]\n",
1007                                                 prop->value);
1008                         } else {
1009                                 log_print(LOG_DEBUG_FILTERING,
1010                                                 "message size is not greater than [ %d ]\n",
1011                                                 prop->value);
1012                         }
1013                 }
1014                 return ret;
1015         }
1016         case MATCHCRITERIA_SIZE_SMALLER:
1017         {
1018                 /* FIXME: info->size is a goffset */
1019                 gboolean ret = (info->size < (goffset) prop->value);
1020
1021                 /* debug output */
1022                 if (debug_filtering_session
1023                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1024                         if (ret) {
1025                                 log_print(LOG_DEBUG_FILTERING,
1026                                                 "message size is smaller than [ %d ]\n",
1027                                                 prop->value);
1028                         } else {
1029                                 log_print(LOG_DEBUG_FILTERING,
1030                                                 "message size is not smaller than [ %d ]\n",
1031                                                 prop->value);
1032                         }
1033                 }
1034                 return ret;
1035         }
1036         case MATCHCRITERIA_SIZE_EQUAL:
1037         {
1038                 /* FIXME: info->size is a goffset */
1039                 gboolean ret = (info->size == (goffset) prop->value);
1040
1041                 /* debug output */
1042                 if (debug_filtering_session
1043                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1044                         if (ret) {
1045                                 log_print(LOG_DEBUG_FILTERING,
1046                                                 "message size is equal to [ %d ]\n",
1047                                                 prop->value);
1048                         } else {
1049                                 log_print(LOG_DEBUG_FILTERING,
1050                                                 "message size is not equal to [ %d ]\n",
1051                                                 prop->value);
1052                         }
1053                 }
1054                 return ret;
1055         }
1056         case MATCHCRITERIA_PARTIAL:
1057         {
1058                 /* FIXME: info->size is a goffset */
1059                 gboolean ret = (info->total_size != 0 && info->size != (goffset)info->total_size);
1060
1061                 /* debug output */
1062                 if (debug_filtering_session
1063                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1064                         if (ret) {
1065                                 log_print(LOG_DEBUG_FILTERING,
1066                                                 "message is partially downloaded, size is less than total size [ %d ])\n",
1067                                                 info->total_size);
1068                         } else {
1069                                 log_print(LOG_DEBUG_FILTERING,
1070                                                 "message is not partially downloaded\n");
1071                         }
1072                 }
1073                 return ret;
1074         }
1075         case MATCHCRITERIA_NOT_PARTIAL:
1076         {
1077                 /* FIXME: info->size is a goffset */
1078                 gboolean ret = (info->total_size == 0 || info->size == (goffset)info->total_size);
1079
1080                 /* debug output */
1081                 if (debug_filtering_session
1082                                 && prefs_common.filtering_debug_level >= FILTERING_DEBUG_LEVEL_HIGH) {
1083                         if (ret) {
1084                                 log_print(LOG_DEBUG_FILTERING,
1085                                                 "message is not partially downloaded\n");
1086                         } else {
1087                                 log_print(LOG_DEBUG_FILTERING,
1088                                                 "message is partially downloaded, size is less than total size [ %d ])\n",
1089                                                 info->total_size);
1090                         }
1091                 }
1092                 return ret;
1093         }
1094         case MATCHCRITERIA_NEWSGROUPS:
1095                 return matcherprop_string_match(prop, info->newsgroups, context_str[CONTEXT_NEWSGROUPS]);
1096         case MATCHCRITERIA_NOT_NEWSGROUPS:
1097                 return !matcherprop_string_match(prop, info->newsgroups, context_str[CONTEXT_NEWSGROUPS]);
1098         case MATCHCRITERIA_INREPLYTO:
1099                 return matcherprop_string_match(prop, info->inreplyto, context_str[CONTEXT_IN_REPLY_TO]);
1100         case MATCHCRITERIA_NOT_INREPLYTO:
1101                 return !matcherprop_string_match(prop, info->inreplyto, context_str[CONTEXT_IN_REPLY_TO]);
1102         case MATCHCRITERIA_REFERENCES:
1103                 return matcherprop_list_match(prop, info->references, context_str[CONTEXT_REFERENCES]);
1104         case MATCHCRITERIA_NOT_REFERENCES:
1105                 return !matcherprop_list_match(prop, info->references, context_str[CONTEXT_REFERENCES]);
1106         case MATCHCRITERIA_TEST:
1107                 return matcherprop_match_test(prop, info);
1108         case MATCHCRITERIA_NOT_TEST:
1109                 return !matcherprop_match_test(prop, info);
1110         default:
1111                 return FALSE;
1112         }
1113 }
1114
1115 /* ********************* MatcherList *************************** */
1116
1117 /*!
1118  *\brief        Create a new list of matchers 
1119  *
1120  *\param        matchers List of matcher structures
1121  *\param        bool_and Operator
1122  *
1123  *\return       MatcherList * New list
1124  */
1125 MatcherList *matcherlist_new(GSList *matchers, gboolean bool_and)
1126 {
1127         MatcherList *cond;
1128
1129         cond = g_new0(MatcherList, 1);
1130
1131         cond->matchers = matchers;
1132         cond->bool_and = bool_and;
1133
1134         return cond;
1135 }
1136
1137 #ifdef G_OS_UNIX
1138 /*!
1139  *\brief        Builds a single regular expresion from an array of srings.
1140  *
1141  *\param        strings The lines containing the different sub-regexp.
1142  *
1143  *\return       The newly allocated regexp string.
1144  */
1145 static gchar *build_complete_regexp(gchar **strings)
1146 {
1147         int i = 0;
1148         gchar *expr = NULL;
1149         while (strings && strings[i] && *strings[i]) {
1150                 int old_len = expr ? strlen(expr):0;
1151                 int new_len = 0;
1152                 gchar *tmpstr = NULL;
1153
1154                 if (g_utf8_validate(strings[i], -1, NULL))
1155                         tmpstr = g_strdup(strings[i]);
1156                 else
1157                         tmpstr = conv_codeset_strdup(strings[i], 
1158                                         conv_get_locale_charset_str_no_utf8(),
1159                                         CS_INTERNAL);
1160
1161                 if (strstr(tmpstr, "\n"))
1162                         *(strstr(tmpstr, "\n")) = '\0';
1163
1164                 new_len = strlen(tmpstr);
1165
1166                 expr = g_realloc(expr, 
1167                         expr ? (old_len + strlen("|()") + new_len + 1)
1168                              : (strlen("()") + new_len + 1));
1169                 
1170                 if (old_len) {
1171                         strcpy(expr + old_len, "|(");
1172                         strcpy(expr + old_len + 2, tmpstr);
1173                         strcpy(expr + old_len + 2 + new_len, ")");
1174                 } else {
1175                         strcpy(expr+old_len, "(");
1176                         strcpy(expr+old_len + 1, tmpstr);
1177                         strcpy(expr+old_len + 1 + new_len, ")");
1178                 }
1179                 g_free(tmpstr);
1180                 i++;
1181         }
1182         return expr;
1183 }
1184 #endif
1185
1186 /*!
1187  *\brief        Create a new list of matchers from a multi-line string
1188  *
1189  *\param        lines String with "\n"-separated expressions
1190  *\param        bool_and Operator
1191  *
1192  *\return       MatcherList * New matcher list
1193  */
1194 MatcherList *matcherlist_new_from_lines(gchar *lines, gboolean bool_and)
1195 {
1196         MatcherProp *m = NULL;
1197         GSList *matchers = NULL;
1198         gchar **strings = g_strsplit(lines, "\n", -1);
1199
1200 #ifdef G_OS_UNIX
1201         gchar *expr = NULL;
1202         expr = build_complete_regexp(strings);
1203         debug_print("building matcherprop for expr '%s'\n", expr?expr:"NULL");
1204         
1205         m = matcherprop_new(MATCHCRITERIA_SUBJECT, NULL, MATCHTYPE_REGEXP, 
1206                             expr, 0);
1207         if (m == NULL) {
1208                 /* print error message */
1209                 debug_print("failed to allocate memory for matcherprop\n");
1210         } else {
1211                 matchers = g_slist_append(matchers, m);
1212         }
1213
1214         g_free(expr);
1215 #else
1216         int i = 0;
1217         while (strings && strings[i] && *strings[i]) {
1218                 m = matcherprop_new(MATCHCRITERIA_SUBJECT, NULL, MATCHTYPE_MATCHCASE, 
1219                             strings[i], 0);
1220                 if (m == NULL) {
1221                         /* print error message */
1222                         debug_print("failed to allocate memory for matcherprop\n");
1223                 } else {
1224                         matchers = g_slist_append(matchers, m);
1225                 }
1226                 i++;
1227         }
1228 #endif
1229         g_strfreev(strings);
1230
1231         return matcherlist_new(matchers, bool_and);
1232 }
1233
1234 /*!
1235  *\brief        Frees a list of matchers
1236  *
1237  *\param        cond List of matchers
1238  */
1239 void matcherlist_free(MatcherList *cond)
1240 {
1241         GSList *l;
1242
1243         cm_return_if_fail(cond);
1244         for (l = cond->matchers ; l != NULL ; l = g_slist_next(l)) {
1245                 matcherprop_free((MatcherProp *) l->data);
1246         }
1247         g_slist_free(cond->matchers);
1248         g_free(cond);
1249 }
1250
1251 /*!
1252  *\brief        Skip all headers in a message file
1253  *
1254  *\param        fp Message file
1255  */
1256 static void matcherlist_skip_headers(FILE *fp)
1257 {
1258         gchar buf[BUFFSIZE];
1259
1260         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1)
1261                 ;
1262 }
1263
1264 /*!
1265  *\brief        Check if a header matches a matcher condition
1266  *
1267  *\param        matcher Matcher structure to check header for
1268  *\param        buf Header name
1269  *
1270  *\return       boolean TRUE if matching header
1271  */
1272 static gboolean matcherprop_match_one_header(MatcherProp *matcher,
1273                                              gchar *buf)
1274 {
1275         gboolean result = FALSE;
1276         Header *header = NULL;
1277
1278         switch (matcher->criteria) {
1279         case MATCHCRITERIA_HEADER:
1280         case MATCHCRITERIA_NOT_HEADER:
1281                 header = procheader_parse_header(buf);
1282                 if (!header)
1283                         return FALSE;
1284                 if (procheader_headername_equal(header->name,
1285                                                 matcher->header)) {
1286                         if (matcher->criteria == MATCHCRITERIA_HEADER)
1287                                 result = matcherprop_string_match(matcher, header->body, context_str[CONTEXT_HEADER]);
1288                         else
1289                                 result = !matcherprop_string_match(matcher, header->body, context_str[CONTEXT_HEADER]);
1290                         procheader_header_free(header);
1291                         return result;
1292                 }
1293                 else {
1294                         procheader_header_free(header);
1295                 }
1296                 break;
1297         case MATCHCRITERIA_HEADERS_PART:
1298         case MATCHCRITERIA_MESSAGE:
1299                 header = procheader_parse_header(buf);
1300                 if (!header)
1301                         return FALSE;
1302                 result = matcherprop_header_line_match(matcher, 
1303                                header->name, header->body, context_str[CONTEXT_HEADER_LINE]);
1304                 procheader_header_free(header);
1305                 return result;
1306         case MATCHCRITERIA_NOT_HEADERS_PART:
1307         case MATCHCRITERIA_NOT_MESSAGE:
1308                 header = procheader_parse_header(buf);
1309                 if (!header)
1310                         return FALSE;
1311                 result = !matcherprop_header_line_match(matcher, 
1312                                header->name, header->body, context_str[CONTEXT_HEADER_LINE]);
1313                 procheader_header_free(header);
1314                 return result;
1315         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1316         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1317                 {
1318                         GSList *address_list = NULL;
1319                         gint match = MATCH_ONE;
1320                         gboolean found = FALSE;
1321
1322                         /* how many address headers are me trying to mach? */
1323                         if (strcasecmp(matcher->header, "Any") == 0)
1324                                 match = MATCH_ANY;
1325                         else if (strcasecmp(matcher->header, "All") == 0)
1326                                         match = MATCH_ALL;
1327
1328                         if (match == MATCH_ONE) {
1329                                 /* matching one address header exactly, is that the right one? */
1330                                 header = procheader_parse_header(buf);
1331                                 if (!header ||
1332                                                 !procheader_headername_equal(header->name, matcher->header))
1333                                         return FALSE;
1334                                 address_list = address_list_append(address_list, header->body);
1335                                 if (address_list == NULL)
1336                                         return FALSE;
1337
1338                         } else {
1339                                 header = procheader_parse_header(buf);
1340                                 if (!header)
1341                                         return FALSE;
1342                                 /* address header is one of the headers we have to match when checking
1343                                    for any address header or all address headers? */
1344                                 if (procheader_headername_equal(header->name, "From") ||
1345                                          procheader_headername_equal(header->name, "To") ||
1346                                          procheader_headername_equal(header->name, "Cc") ||
1347                                          procheader_headername_equal(header->name, "Reply-To") ||
1348                                          procheader_headername_equal(header->name, "Sender"))
1349                                         address_list = address_list_append(address_list, header->body);
1350                                 if (address_list == NULL)
1351                                         return FALSE;
1352                         }
1353
1354                         found = match_with_addresses_in_addressbook
1355                                                         (matcher, address_list, matcher->criteria,
1356                                                          matcher->expr, match);
1357                         g_slist_free(address_list);
1358
1359                         if (matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK)
1360                                 return !found;
1361                         else
1362                                 return found;
1363         }
1364         }
1365
1366         return FALSE;
1367 }
1368
1369 /*!
1370  *\brief        Check if the matcher structure wants headers to
1371  *              be matched
1372  *
1373  *\param        matcher Matcher structure
1374  *
1375  *\return       gboolean TRUE if the matcher structure describes
1376  *              a header match condition
1377  */
1378 static gboolean matcherprop_criteria_headers(const MatcherProp *matcher)
1379 {
1380         switch (matcher->criteria) {
1381         case MATCHCRITERIA_HEADER:
1382         case MATCHCRITERIA_NOT_HEADER:
1383         case MATCHCRITERIA_HEADERS_PART:
1384         case MATCHCRITERIA_NOT_HEADERS_PART:
1385         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
1386         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
1387                 return TRUE;
1388         default:
1389                 return FALSE;
1390         }
1391 }
1392
1393 /*!
1394  *\brief        Check if the matcher structure wants the message
1395  *              to be matched (just perform an action on any
1396  *              message)
1397  *
1398  *\param        matcher Matcher structure
1399  *
1400  *\return       gboolean TRUE if matcher condition should match
1401  *              a message
1402  */
1403 static gboolean matcherprop_criteria_message(MatcherProp *matcher)
1404 {
1405         switch (matcher->criteria) {
1406         case MATCHCRITERIA_MESSAGE:
1407         case MATCHCRITERIA_NOT_MESSAGE:
1408                 return TRUE;
1409         default:
1410                 return FALSE;
1411         }
1412 }
1413
1414 /*!
1415  *\brief        Check if a list of conditions matches one header in
1416  *              a message file.
1417  *
1418  *\param        matchers List of conditions
1419  *\param        fp Message file
1420  *
1421  *\return       gboolean TRUE if one of the headers is matched by
1422  *              the list of conditions. 
1423  */
1424 static gboolean matcherlist_match_headers(MatcherList *matchers, FILE *fp)
1425 {
1426         GSList *l;
1427         gchar buf[BUFFSIZE];
1428
1429         while (procheader_get_one_field(buf, sizeof(buf), fp, NULL) != -1) {
1430                 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1431                         MatcherProp *matcher = (MatcherProp *) l->data;
1432                         gint match = MATCH_ANY;
1433
1434                         if (matcher->done)
1435                                 continue;
1436
1437                         /* determine the match range (all, any are our concern here) */
1438                         if (matcher->criteria == MATCHCRITERIA_NOT_HEADERS_PART ||
1439                             matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1440                                 match = MATCH_ALL;
1441
1442                         } else if (matcher->criteria == MATCHCRITERIA_FOUND_IN_ADDRESSBOOK ||
1443                                            matcher->criteria == MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK) {
1444                                 Header *header = NULL;
1445
1446                                 /* address header is one of the headers we have to match when checking
1447                                    for any address header or all address headers? */
1448                                 header = procheader_parse_header(buf);
1449                                 if (header &&
1450                                         (procheader_headername_equal(header->name, "From") ||
1451                                          procheader_headername_equal(header->name, "To") ||
1452                                          procheader_headername_equal(header->name, "Cc") ||
1453                                          procheader_headername_equal(header->name, "Reply-To") ||
1454                                          procheader_headername_equal(header->name, "Sender"))) {
1455
1456                                         if (strcasecmp(matcher->header, "Any") == 0)
1457                                                 match = MATCH_ANY;
1458                                         else if (strcasecmp(matcher->header, "All") == 0)
1459                                                 match = MATCH_ALL;
1460                                         else
1461                                                 match = MATCH_ONE;
1462                                 } else {
1463                                         /* further call to matcherprop_match_one_header() can't match
1464                                            and it irrelevant, so: don't alter the match result */
1465                                         continue;
1466                                 }
1467                         }
1468
1469                         /* ZERO line must NOT match for the rule to match.
1470                          */
1471                         if (match == MATCH_ALL) {
1472                                 if (matcherprop_match_one_header(matcher, buf)) {
1473                                         matcher->result = TRUE;
1474                                 } else {
1475                                         matcher->result = FALSE;
1476                                         matcher->done = TRUE;
1477                                 }
1478                         /* else, just one line matching is enough for the rule to match
1479                          */
1480                         } else if (matcherprop_criteria_headers(matcher) ||
1481                                    matcherprop_criteria_message(matcher)) {
1482                                 if (matcherprop_match_one_header(matcher, buf)) {
1483                                         matcher->result = TRUE;
1484                                         matcher->done = TRUE;
1485                                 }
1486                         }
1487                         
1488                         /* if the rule matched and the matchers are OR, no need to
1489                          * check the others */
1490                         if (matcher->result && matcher->done) {
1491                                 if (!matchers->bool_and)
1492                                         return TRUE;
1493                         }
1494                 }
1495         }
1496
1497         return FALSE;
1498 }
1499
1500 /*!
1501  *\brief        Check if a matcher wants to check the message body
1502  *
1503  *\param        matcher Matcher structure
1504  *
1505  *\return       gboolean TRUE if body must be matched.
1506  */
1507 static gboolean matcherprop_criteria_body(const MatcherProp *matcher)
1508 {
1509         switch (matcher->criteria) {
1510         case MATCHCRITERIA_BODY_PART:
1511         case MATCHCRITERIA_NOT_BODY_PART:
1512                 return TRUE;
1513         default:
1514                 return FALSE;
1515         }
1516 }
1517         
1518 static gboolean matcherlist_match_binary_content(MatcherList *matchers, MimeInfo *partinfo)
1519 {
1520         FILE *outfp;
1521         gchar buf[BUFFSIZE];
1522         GSList *l;
1523
1524         if (partinfo->type == MIMETYPE_TEXT)
1525                 return FALSE;
1526         else
1527                 outfp = procmime_get_binary_content(partinfo);
1528
1529         if (!outfp)
1530                 return FALSE;
1531
1532         while (fgets(buf, sizeof(buf), outfp) != NULL) {
1533                 strretchomp(buf);
1534
1535                 for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1536                         MatcherProp *matcher = (MatcherProp *) l->data;
1537
1538                         if (matcher->done) 
1539                                 continue;
1540
1541                         /* Don't scan non-text parts when looking in body, only
1542                          * when looking in whole message
1543                          */
1544                         if (partinfo && partinfo->type != MIMETYPE_TEXT &&
1545                         (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1546                         matcher->criteria == MATCHCRITERIA_BODY_PART))
1547                                 continue;
1548
1549                         /* if the criteria is ~body_part or ~message, ZERO lines
1550                          * must match for the rule to match.
1551                          */
1552                         if (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1553                             matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1554                                 if (matcherprop_string_match(matcher, buf, 
1555                                                         context_str[CONTEXT_BODY_LINE])) {
1556                                         matcher->result = FALSE;
1557                                         matcher->done = TRUE;
1558                                 } else
1559                                         matcher->result = TRUE;
1560                         /* else, just one line has to match */
1561                         } else if (matcherprop_criteria_body(matcher) ||
1562                                    matcherprop_criteria_message(matcher)) {
1563                                 if (matcherprop_string_match(matcher, buf,
1564                                                         context_str[CONTEXT_BODY_LINE])) {
1565                                         matcher->result = TRUE;
1566                                         matcher->done = TRUE;
1567                                 }
1568                         }
1569
1570                         /* if the matchers are OR'ed and the rule matched,
1571                          * no need to check the others. */
1572                         if (matcher->result && matcher->done) {
1573                                 if (!matchers->bool_and) {
1574                                         fclose(outfp);
1575                                         return TRUE;
1576                                 }
1577                         }
1578                 }
1579         }
1580
1581         fclose(outfp);
1582         return FALSE;
1583 }
1584
1585 static gboolean match_content_cb(const gchar *buf, gpointer data)
1586 {
1587         MatcherList *matchers = (MatcherList *)data;
1588         gboolean all_done = TRUE;
1589         GSList *l;
1590
1591         for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1592                 MatcherProp *matcher = (MatcherProp *) l->data;
1593
1594                 if (matcher->done) 
1595                         continue;
1596
1597                 /* if the criteria is ~body_part or ~message, ZERO lines
1598                  * must match for the rule to match.
1599                  */
1600                 if (matcher->criteria == MATCHCRITERIA_NOT_BODY_PART ||
1601                     matcher->criteria == MATCHCRITERIA_NOT_MESSAGE) {
1602                         if (matcherprop_string_match(matcher, buf, 
1603                                                 context_str[CONTEXT_BODY_LINE])) {
1604                                 matcher->result = FALSE;
1605                                 matcher->done = TRUE;
1606                         } else
1607                                 matcher->result = TRUE;
1608                 /* else, just one line has to match */
1609                 } else if (matcherprop_criteria_body(matcher) ||
1610                            matcherprop_criteria_message(matcher)) {
1611                         if (matcherprop_string_match(matcher, buf,
1612                                                 context_str[CONTEXT_BODY_LINE])) {
1613                                 matcher->result = TRUE;
1614                                 matcher->done = TRUE;
1615                         }
1616                 }
1617
1618                 /* if the matchers are OR'ed and the rule matched,
1619                  * no need to check the others. */
1620                 if (matcher->result && matcher->done) {
1621                         if (!matchers->bool_and) {
1622                                 return TRUE;
1623                         }
1624                 }
1625
1626                 if (!matcher->done)
1627                         all_done = FALSE;
1628         }
1629         return all_done;
1630 }
1631
1632 static gboolean matcherlist_match_text_content(MatcherList *matchers, MimeInfo *partinfo)
1633 {
1634         if (partinfo->type != MIMETYPE_TEXT)
1635                 return FALSE;
1636
1637         return procmime_scan_text_content(partinfo, match_content_cb, matchers);
1638 }
1639
1640 /*!
1641  *\brief        Check if a line in a message file's body matches
1642  *              the criteria
1643  *
1644  *\param        matchers List of conditions
1645  *\param        fp Message file
1646  *
1647  *\return       gboolean TRUE if succesful match
1648  */
1649 static gboolean matcherlist_match_body(MatcherList *matchers, gboolean body_only, MsgInfo *info)
1650 {
1651         MimeInfo *mimeinfo = NULL;
1652         MimeInfo *partinfo = NULL;
1653         gboolean first_text_found = FALSE;
1654
1655         cm_return_val_if_fail(info != NULL, FALSE);
1656
1657         mimeinfo = procmime_scan_message(info);
1658
1659         /* Skip headers */
1660         partinfo = procmime_mimeinfo_next(mimeinfo);
1661
1662         for (; partinfo != NULL; partinfo = procmime_mimeinfo_next(partinfo)) {
1663
1664                 if (partinfo->type != MIMETYPE_TEXT && body_only)
1665                         continue;
1666
1667                 if (partinfo->type == MIMETYPE_TEXT) {
1668                         first_text_found = TRUE;
1669                         if (matcherlist_match_text_content(matchers, partinfo)) {
1670                                 procmime_mimeinfo_free_all(mimeinfo);
1671                                 return TRUE;
1672                         }
1673                 } else if (matcherlist_match_binary_content(matchers, partinfo)) {
1674                         procmime_mimeinfo_free_all(mimeinfo);
1675                         return TRUE;
1676                 }
1677
1678                 if (body_only && first_text_found)
1679                         break;
1680         }
1681         procmime_mimeinfo_free_all(mimeinfo);
1682
1683         return FALSE;
1684 }
1685
1686 /*!
1687  *\brief        Check if a message file matches criteria
1688  *
1689  *\param        matchers Criteria
1690  *\param        info Message info
1691  *\param        result Default result
1692  *
1693  *\return       gboolean TRUE if matched
1694  */
1695 static gboolean matcherlist_match_file(MatcherList *matchers, MsgInfo *info,
1696                                 gboolean result)
1697 {
1698         gboolean read_headers;
1699         gboolean read_body;
1700         gboolean body_only;
1701         GSList *l;
1702         FILE *fp;
1703         gchar *file;
1704
1705         /* file need to be read ? */
1706
1707         read_headers = FALSE;
1708         read_body = FALSE;
1709         body_only = TRUE;
1710         for (l = matchers->matchers ; l != NULL ; l = g_slist_next(l)) {
1711                 MatcherProp *matcher = (MatcherProp *) l->data;
1712
1713                 if (matcherprop_criteria_headers(matcher))
1714                         read_headers = TRUE;
1715                 if (matcherprop_criteria_body(matcher))
1716                         read_body = TRUE;
1717                 if (matcherprop_criteria_message(matcher)) {
1718                         read_headers = TRUE;
1719                         read_body = TRUE;
1720                         body_only = FALSE;
1721                 }
1722                 matcher->result = FALSE;
1723                 matcher->done = FALSE;
1724         }
1725
1726         if (!read_headers && !read_body)
1727                 return result;
1728
1729         file = procmsg_get_message_file_full(info, read_headers, read_body);
1730         if (file == NULL)
1731                 return FALSE;
1732
1733         if ((fp = g_fopen(file, "rb")) == NULL) {
1734                 FILE_OP_ERROR(file, "fopen");
1735                 g_free(file);
1736                 return result;
1737         }
1738
1739         /* read the headers */
1740
1741         if (read_headers) {
1742                 if (matcherlist_match_headers(matchers, fp))
1743                         read_body = FALSE;
1744         } else {
1745                 matcherlist_skip_headers(fp);
1746         }
1747
1748         /* read the body */
1749         if (read_body) {
1750                 matcherlist_match_body(matchers, body_only, info);
1751         }
1752         
1753         for (l = matchers->matchers; l != NULL; l = g_slist_next(l)) {
1754                 MatcherProp *matcher = (MatcherProp *) l->data;
1755
1756                 if (matcherprop_criteria_headers(matcher) ||
1757                     matcherprop_criteria_body(matcher)    ||
1758                     matcherprop_criteria_message(matcher)) {
1759                         if (matcher->result) {
1760                                 if (!matchers->bool_and) {
1761                                         result = TRUE;
1762                                         break;
1763                                 }
1764                         }
1765                         else {
1766                                 if (matchers->bool_and) {
1767                                         result = FALSE;
1768                                         break;
1769                                 }
1770                         }
1771                 }                       
1772         }
1773
1774         g_free(file);
1775
1776         fclose(fp);
1777         
1778         return result;
1779 }
1780
1781 /*!
1782  *\brief        Test list of conditions on a message.
1783  *
1784  *\param        matchers List of conditions
1785  *\param        info Message info
1786  *
1787  *\return       gboolean TRUE if matched
1788  */
1789 gboolean matcherlist_match(MatcherList *matchers, MsgInfo *info)
1790 {
1791         GSList *l;
1792         gboolean result;
1793
1794         if (!matchers)
1795                 return FALSE;
1796
1797         if (matchers->bool_and)
1798                 result = TRUE;
1799         else
1800                 result = FALSE;
1801
1802         /* test the cached elements */
1803
1804         for (l = matchers->matchers; l != NULL ;l = g_slist_next(l)) {
1805                 MatcherProp *matcher = (MatcherProp *) l->data;
1806
1807                 if (debug_filtering_session) {
1808                         gchar *buf = matcherprop_to_string(matcher);
1809                         log_print(LOG_DEBUG_FILTERING, _("checking if message matches [ %s ]\n"), buf);
1810                         g_free(buf);
1811                 }
1812
1813                 switch(matcher->criteria) {
1814                 case MATCHCRITERIA_ALL:
1815                 case MATCHCRITERIA_UNREAD:
1816                 case MATCHCRITERIA_NOT_UNREAD:
1817                 case MATCHCRITERIA_NEW:
1818                 case MATCHCRITERIA_NOT_NEW:
1819                 case MATCHCRITERIA_MARKED:
1820                 case MATCHCRITERIA_NOT_MARKED:
1821                 case MATCHCRITERIA_DELETED:
1822                 case MATCHCRITERIA_NOT_DELETED:
1823                 case MATCHCRITERIA_REPLIED:
1824                 case MATCHCRITERIA_NOT_REPLIED:
1825                 case MATCHCRITERIA_FORWARDED:
1826                 case MATCHCRITERIA_NOT_FORWARDED:
1827                 case MATCHCRITERIA_LOCKED:
1828                 case MATCHCRITERIA_NOT_LOCKED:
1829                 case MATCHCRITERIA_SPAM:
1830                 case MATCHCRITERIA_NOT_SPAM:
1831                 case MATCHCRITERIA_HAS_ATTACHMENT:
1832                 case MATCHCRITERIA_HAS_NO_ATTACHMENT:
1833                 case MATCHCRITERIA_SIGNED:
1834                 case MATCHCRITERIA_NOT_SIGNED:
1835                 case MATCHCRITERIA_COLORLABEL:
1836                 case MATCHCRITERIA_NOT_COLORLABEL:
1837                 case MATCHCRITERIA_IGNORE_THREAD:
1838                 case MATCHCRITERIA_NOT_IGNORE_THREAD:
1839                 case MATCHCRITERIA_WATCH_THREAD:
1840                 case MATCHCRITERIA_NOT_WATCH_THREAD:
1841                 case MATCHCRITERIA_SUBJECT:
1842                 case MATCHCRITERIA_NOT_SUBJECT:
1843                 case MATCHCRITERIA_FROM:
1844                 case MATCHCRITERIA_NOT_FROM:
1845                 case MATCHCRITERIA_TO:
1846                 case MATCHCRITERIA_NOT_TO:
1847                 case MATCHCRITERIA_CC:
1848                 case MATCHCRITERIA_NOT_CC:
1849                 case MATCHCRITERIA_TO_OR_CC:
1850                 case MATCHCRITERIA_NOT_TO_AND_NOT_CC:
1851                 case MATCHCRITERIA_TAG:
1852                 case MATCHCRITERIA_NOT_TAG:
1853                 case MATCHCRITERIA_TAGGED:
1854                 case MATCHCRITERIA_NOT_TAGGED:
1855                 case MATCHCRITERIA_AGE_GREATER:
1856                 case MATCHCRITERIA_AGE_LOWER:
1857                 case MATCHCRITERIA_AGE_GREATER_HOURS:
1858                 case MATCHCRITERIA_AGE_LOWER_HOURS:
1859                 case MATCHCRITERIA_NEWSGROUPS:
1860                 case MATCHCRITERIA_NOT_NEWSGROUPS:
1861                 case MATCHCRITERIA_INREPLYTO:
1862                 case MATCHCRITERIA_NOT_INREPLYTO:
1863                 case MATCHCRITERIA_REFERENCES:
1864                 case MATCHCRITERIA_NOT_REFERENCES:
1865                 case MATCHCRITERIA_SCORE_GREATER:
1866                 case MATCHCRITERIA_SCORE_LOWER:
1867                 case MATCHCRITERIA_SCORE_EQUAL:
1868                 case MATCHCRITERIA_SIZE_GREATER:
1869                 case MATCHCRITERIA_SIZE_SMALLER:
1870                 case MATCHCRITERIA_SIZE_EQUAL:
1871                 case MATCHCRITERIA_TEST:
1872                 case MATCHCRITERIA_NOT_TEST:
1873                 case MATCHCRITERIA_PARTIAL:
1874                 case MATCHCRITERIA_NOT_PARTIAL:
1875                         if (matcherprop_match(matcher, info)) {
1876                                 if (!matchers->bool_and) {
1877                                         if (debug_filtering_session)
1878                                                 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1879                                         return TRUE;
1880                                 }
1881                         }
1882                         else {
1883                                 if (matchers->bool_and) {
1884                                         if (debug_filtering_session)
1885                                                 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1886                                         return FALSE;
1887                                 }
1888                         }
1889                 }
1890         }
1891
1892         /* test the condition on the file */
1893
1894         if (matcherlist_match_file(matchers, info, result)) {
1895                 if (!matchers->bool_and) {
1896                         if (debug_filtering_session)
1897                                 log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1898                         return TRUE;
1899                 }
1900         } else {
1901                 if (matchers->bool_and) {
1902                         if (debug_filtering_session)
1903                                 log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1904                         return FALSE;
1905                 }
1906         }
1907
1908         if (debug_filtering_session) {
1909                 if (result)
1910                         log_status_ok(LOG_DEBUG_FILTERING, _("message matches\n"));
1911                 else
1912                         log_status_nok(LOG_DEBUG_FILTERING, _("message does not match\n"));
1913         }
1914         return result;
1915 }
1916
1917
1918 static gint quote_filter_str(gchar * result, guint size,
1919                              const gchar * path)
1920 {
1921         const gchar * p;
1922         gchar * result_p;
1923         guint remaining;
1924
1925         result_p = result;
1926         remaining = size;
1927
1928         for(p = path ; * p != '\0' ; p ++) {
1929
1930                 if ((* p != '\"') && (* p != '\\')) {
1931                         if (remaining > 0) {
1932                                 * result_p = * p;
1933                                 result_p ++; 
1934                                 remaining --;
1935                         }
1936                         else {
1937                                 result[size - 1] = '\0';
1938                                 return -1;
1939                         }
1940                 }
1941                 else { 
1942                         if (remaining >= 2) {
1943                                 * result_p = '\\';
1944                                 result_p ++; 
1945                                 * result_p = * p;
1946                                 result_p ++; 
1947                                 remaining -= 2;
1948                         }
1949                         else {
1950                                 result[size - 1] = '\0';
1951                                 return -1;
1952                         }
1953                 }
1954         }
1955         if (remaining > 0) {
1956                 * result_p = '\0';
1957         }
1958         else {
1959                 result[size - 1] = '\0';
1960                 return -1;
1961         }
1962   
1963         return 0;
1964 }
1965
1966
1967 gchar * matcher_quote_str(const gchar * src)
1968 {
1969         gchar * res;
1970         gint len;
1971         
1972         len = strlen(src) * 2 + 1;
1973         res = g_malloc(len);
1974         quote_filter_str(res, len, src);
1975         
1976         return res;
1977 }
1978
1979 /*!
1980  *\brief        Convert a matcher structure to a string
1981  *
1982  *\param        matcher Matcher structure
1983  *
1984  *\return       gchar * Newly allocated string
1985  */
1986 gchar *matcherprop_to_string(MatcherProp *matcher)
1987 {
1988         gchar *matcher_str = NULL;
1989         const gchar *criteria_str;
1990         const gchar *matchtype_str;
1991         int i;
1992         gchar * quoted_expr;
1993         gchar * quoted_header;
1994         
1995         criteria_str = NULL;
1996         for (i = 0; i < (int) (sizeof(matchparser_tab) / sizeof(MatchParser)); i++) {
1997                 if (matchparser_tab[i].id == matcher->criteria)
1998                         criteria_str = matchparser_tab[i].str;
1999         }
2000         if (criteria_str == NULL)
2001                 return NULL;
2002
2003         switch (matcher->criteria) {
2004         case MATCHCRITERIA_AGE_GREATER:
2005         case MATCHCRITERIA_AGE_LOWER:
2006         case MATCHCRITERIA_AGE_GREATER_HOURS:
2007         case MATCHCRITERIA_AGE_LOWER_HOURS:
2008         case MATCHCRITERIA_SCORE_GREATER:
2009         case MATCHCRITERIA_SCORE_LOWER:
2010         case MATCHCRITERIA_SCORE_EQUAL:
2011         case MATCHCRITERIA_SIZE_GREATER:
2012         case MATCHCRITERIA_SIZE_SMALLER:
2013         case MATCHCRITERIA_SIZE_EQUAL:
2014         case MATCHCRITERIA_COLORLABEL:
2015         case MATCHCRITERIA_NOT_COLORLABEL:
2016                 return g_strdup_printf("%s %i", criteria_str, matcher->value);
2017         case MATCHCRITERIA_ALL:
2018         case MATCHCRITERIA_UNREAD:
2019         case MATCHCRITERIA_NOT_UNREAD:
2020         case MATCHCRITERIA_NEW:
2021         case MATCHCRITERIA_NOT_NEW:
2022         case MATCHCRITERIA_MARKED:
2023         case MATCHCRITERIA_NOT_MARKED:
2024         case MATCHCRITERIA_DELETED:
2025         case MATCHCRITERIA_NOT_DELETED:
2026         case MATCHCRITERIA_REPLIED:
2027         case MATCHCRITERIA_NOT_REPLIED:
2028         case MATCHCRITERIA_FORWARDED:
2029         case MATCHCRITERIA_NOT_FORWARDED:
2030         case MATCHCRITERIA_LOCKED:
2031         case MATCHCRITERIA_NOT_LOCKED:
2032         case MATCHCRITERIA_SPAM:
2033         case MATCHCRITERIA_NOT_SPAM:
2034         case MATCHCRITERIA_HAS_ATTACHMENT:
2035         case MATCHCRITERIA_HAS_NO_ATTACHMENT:
2036         case MATCHCRITERIA_SIGNED:
2037         case MATCHCRITERIA_NOT_SIGNED:
2038         case MATCHCRITERIA_PARTIAL:
2039         case MATCHCRITERIA_NOT_PARTIAL:
2040         case MATCHCRITERIA_IGNORE_THREAD:
2041         case MATCHCRITERIA_NOT_IGNORE_THREAD:
2042         case MATCHCRITERIA_WATCH_THREAD:
2043         case MATCHCRITERIA_NOT_WATCH_THREAD:
2044         case MATCHCRITERIA_TAGGED:
2045         case MATCHCRITERIA_NOT_TAGGED:
2046                 return g_strdup(criteria_str);
2047         case MATCHCRITERIA_TEST:
2048         case MATCHCRITERIA_NOT_TEST:
2049                 quoted_expr = matcher_quote_str(matcher->expr);
2050                 matcher_str = g_strdup_printf("%s \"%s\"",
2051                                               criteria_str, quoted_expr);
2052                 g_free(quoted_expr);
2053                 return matcher_str;
2054         case MATCHCRITERIA_FOUND_IN_ADDRESSBOOK:
2055         case MATCHCRITERIA_NOT_FOUND_IN_ADDRESSBOOK:
2056                 quoted_header = matcher_quote_str(matcher->header);
2057                 quoted_expr = matcher_quote_str(matcher->expr);
2058                 matcher_str = g_strdup_printf("%s \"%s\" in \"%s\"",
2059                                               criteria_str, quoted_header, quoted_expr);
2060                 g_free(quoted_header);
2061                 g_free(quoted_expr);
2062                 return matcher_str;
2063         }
2064
2065         matchtype_str = NULL;
2066         for (i = 0; i < sizeof matchparser_tab / sizeof matchparser_tab[0]; i++) {
2067                 if (matchparser_tab[i].id == matcher->matchtype)
2068                         matchtype_str = matchparser_tab[i].str;
2069         }
2070
2071         if (matchtype_str == NULL)
2072                 return NULL;
2073
2074         switch (matcher->matchtype) {
2075         case MATCHTYPE_MATCH:
2076         case MATCHTYPE_MATCHCASE:
2077         case MATCHTYPE_REGEXP:
2078         case MATCHTYPE_REGEXPCASE:
2079                 quoted_expr = matcher_quote_str(matcher->expr);
2080                 if (matcher->header) {
2081                         quoted_header = matcher_quote_str(matcher->header);
2082                         matcher_str = g_strdup_printf
2083                                         ("%s \"%s\" %s \"%s\"",
2084                                          criteria_str, quoted_header,
2085                                          matchtype_str, quoted_expr);
2086                         g_free(quoted_header);
2087                 }
2088                 else
2089                         matcher_str = g_strdup_printf
2090                                         ("%s %s \"%s\"", criteria_str,
2091                                          matchtype_str, quoted_expr);
2092                 g_free(quoted_expr);
2093                 break;
2094         }
2095
2096         return matcher_str;
2097 }
2098
2099 /*!
2100  *\brief        Convert a list of conditions to a string
2101  *
2102  *\param        matchers List of conditions
2103  *
2104  *\return       gchar * Newly allocated string
2105  */
2106 gchar *matcherlist_to_string(const MatcherList *matchers)
2107 {
2108         gint count;
2109         gchar **vstr;
2110         GSList *l;
2111         gchar **cur_str;
2112         gchar *result = NULL;
2113
2114         count = g_slist_length(matchers->matchers);
2115         vstr = g_new(gchar *, count + 1);
2116
2117         for (l = matchers->matchers, cur_str = vstr; l != NULL;
2118              l = g_slist_next(l), cur_str ++) {
2119                 *cur_str = matcherprop_to_string((MatcherProp *) l->data);
2120                 if (*cur_str == NULL)
2121                         break;
2122         }
2123         *cur_str = NULL;
2124         
2125         if (matchers->bool_and)
2126                 result = g_strjoinv(" & ", vstr);
2127         else
2128                 result = g_strjoinv(" | ", vstr);
2129
2130         for (cur_str = vstr ; *cur_str != NULL ; cur_str ++)
2131                 g_free(*cur_str);
2132         g_free(vstr);
2133
2134         return result;
2135 }
2136
2137
2138 #define STRLEN_ZERO(s) ((s) ? strlen(s) : 0)
2139 #define STRLEN_DEFAULT(s,d) ((s) ? strlen(s) : STRLEN_ZERO(d))
2140
2141 static void add_str_default(gchar ** dest,
2142                             const gchar * s, const gchar * d)
2143 {
2144         gchar quoted_str[4096];
2145         const gchar * str;
2146         
2147         if (s != NULL)
2148                 str = s;
2149         else
2150                 str = d;
2151         
2152         quote_cmd_argument(quoted_str, sizeof(quoted_str), str);
2153         strcpy(* dest, quoted_str);
2154         
2155         (* dest) += strlen(* dest);
2156 }
2157
2158 /* matching_build_command() - preferably cmd should be unescaped */
2159 /*!
2160  *\brief        Build the command-line to execute
2161  *
2162  *\param        cmd String with command-line specifiers
2163  *\param        info Message info to use for command
2164  *
2165  *\return       gchar * Newly allocated string
2166  */
2167 gchar *matching_build_command(const gchar *cmd, MsgInfo *info)
2168 {
2169         const gchar *s = cmd;
2170         gchar *filename = NULL;
2171         gchar *processed_cmd;
2172         gchar *p;
2173         gint size;
2174
2175         const gchar *const no_subject    = _("(none)") ;
2176         const gchar *const no_from       = _("(none)") ;
2177         const gchar *const no_to         = _("(none)") ;
2178         const gchar *const no_cc         = _("(none)") ;
2179         const gchar *const no_date       = _("(none)") ;
2180         const gchar *const no_msgid      = _("(none)") ;
2181         const gchar *const no_newsgroups = _("(none)") ;
2182         const gchar *const no_references = _("(none)") ;
2183
2184         size = STRLEN_ZERO(cmd) + 1;
2185         while (*s != '\0') {
2186                 if (*s == '%') {
2187                         s++;
2188                         switch (*s) {
2189                         case '%':
2190                                 size -= 1;
2191                                 break;
2192                         case 's': /* subject */
2193                                 size += STRLEN_DEFAULT(info->subject, no_subject) - 2;
2194                                 break;
2195                         case 'f': /* from */
2196                                 size += STRLEN_DEFAULT(info->from, no_from) - 2;
2197                                 break;
2198                         case 't': /* to */
2199                                 size += STRLEN_DEFAULT(info->to, no_to) - 2;
2200                                 break;
2201                         case 'c': /* cc */
2202                                 size += STRLEN_DEFAULT(info->cc, no_cc) - 2;
2203                                 break;
2204                         case 'd': /* date */
2205                                 size += STRLEN_DEFAULT(info->date, no_date) - 2;
2206                                 break;
2207                         case 'i': /* message-id */
2208                                 size += STRLEN_DEFAULT(info->msgid, no_msgid) - 2;
2209                                 break;
2210                         case 'n': /* newsgroups */
2211                                 size += STRLEN_DEFAULT(info->newsgroups, no_newsgroups) - 2;
2212                                 break;
2213                         case 'r': /* references */
2214                                 /* FIXME: using the inreplyto header for reference */
2215                                 size += STRLEN_DEFAULT(info->inreplyto, no_references) - 2;
2216                                 break;
2217                         case 'F': /* file */
2218                                 if (filename == NULL)
2219                                         filename = folder_item_fetch_msg(info->folder, info->msgnum);
2220                                 
2221                                 if (filename == NULL) {
2222                                         g_warning("filename is not set");
2223                                         return NULL;
2224                                 }
2225                                 else {
2226                                         size += strlen(filename) - 2;
2227                                 }
2228                                 break;
2229                         }
2230                         s++;
2231                 }
2232                 else s++;
2233         }
2234         
2235         /* as the string can be quoted, we double the result */
2236         size *= 2;
2237
2238         processed_cmd = g_new0(gchar, size);
2239         s = cmd;
2240         p = processed_cmd;
2241
2242         while (*s != '\0') {
2243                 if (*s == '%') {
2244                         s++;
2245                         switch (*s) {
2246                         case '%':
2247                                 *p = '%';
2248                                 p++;
2249                                 break;
2250                         case 's': /* subject */
2251                                 add_str_default(&p, info->subject,
2252                                                 no_subject);
2253                                 break;
2254                         case 'f': /* from */
2255                                 add_str_default(&p, info->from,
2256                                                 no_from);
2257                                 break;
2258                         case 't': /* to */
2259                                 add_str_default(&p, info->to,
2260                                                 no_to);
2261                                 break;
2262                         case 'c': /* cc */
2263                                 add_str_default(&p, info->cc,
2264                                                 no_cc);
2265                                 break;
2266                         case 'd': /* date */
2267                                 add_str_default(&p, info->date,
2268                                                 no_date);
2269                                 break;
2270                         case 'i': /* message-id */
2271                                 add_str_default(&p, info->msgid,
2272                                                 no_msgid);
2273                                 break;
2274                         case 'n': /* newsgroups */
2275                                 add_str_default(&p, info->newsgroups,
2276                                                 no_newsgroups);
2277                                 break;
2278                         case 'r': /* references */
2279                                 /* FIXME: using the inreplyto header for references */
2280                                 add_str_default(&p, info->inreplyto, no_references);
2281                                 break;
2282                         case 'F': /* file */
2283                                 if (filename != NULL)
2284                                         add_str_default(&p, filename, NULL);
2285                                 break;
2286                         default:
2287                                 *p = '%';
2288                                 p++;
2289                                 *p = *s;
2290                                 p++;
2291                                 break;
2292                         }
2293                         s++;
2294                 }
2295                 else {
2296                         *p = *s;
2297                         p++;
2298                         s++;
2299                 }
2300         }
2301         g_free(filename);
2302         
2303         return processed_cmd;
2304 }
2305 #undef STRLEN_DEFAULT
2306 #undef STRLEN_ZERO
2307
2308 /* ************************************************************ */
2309
2310
2311 /*!
2312  *\brief        Write filtering list to file
2313  *
2314  *\param        fp File
2315  *\param        prefs_filtering List of filtering conditions
2316  */
2317 static int prefs_filtering_write(FILE *fp, GSList *prefs_filtering)
2318 {
2319         GSList *cur = NULL;
2320
2321         for (cur = prefs_filtering; cur != NULL; cur = cur->next) {
2322                 gchar *filtering_str = NULL;
2323                 gchar *tmp_name = NULL;
2324                 FilteringProp *prop = NULL;
2325
2326                 if (NULL == (prop = (FilteringProp *) cur->data))
2327                         continue;
2328                 
2329                 if (NULL == (filtering_str = filteringprop_to_string(prop)))
2330                         continue;
2331
2332                 if (prop->enabled) {
2333                         if (fputs("enabled ", fp) == EOF) {
2334                                 FILE_OP_ERROR("filtering config", "fputs");
2335                                 return -1;
2336                         }
2337                 } else {
2338                         if (fputs("disabled ", fp) == EOF) {
2339                                 FILE_OP_ERROR("filtering config", "fputs");
2340                                 return -1;
2341                         }
2342                 }
2343
2344                 if (fputs("rulename \"", fp) == EOF) {
2345                         FILE_OP_ERROR("filtering config", "fputs");
2346                         g_free(filtering_str);
2347                         return -1;
2348                 }
2349                 tmp_name = prop->name;
2350                 while (tmp_name && *tmp_name != '\0') {
2351                         if (*tmp_name != '"') {
2352                                 if (fputc(*tmp_name, fp) == EOF) {
2353                                         FILE_OP_ERROR("filtering config", "fputs || fputc");
2354                                         g_free(filtering_str);
2355                                         return -1;
2356                                 }
2357                         } else if (*tmp_name == '"') {
2358                                 if (fputc('\\', fp) == EOF ||
2359                                     fputc('"', fp) == EOF) {
2360                                         FILE_OP_ERROR("filtering config", "fputs || fputc");
2361                                         g_free(filtering_str);
2362                                         return -1;
2363                                 }
2364                         }
2365                         tmp_name ++;
2366                 }
2367                 if (fputs("\" ", fp) == EOF) {
2368                         FILE_OP_ERROR("filtering config", "fputs");
2369                         g_free(filtering_str);
2370                         return -1;
2371                 }
2372
2373                 if (prop->account_id != 0) {
2374                         gchar *tmp = NULL;
2375
2376                         tmp = g_strdup_printf("account %d ", prop->account_id);
2377                         if (fputs(tmp, fp) == EOF) {
2378                                 FILE_OP_ERROR("filtering config", "fputs");
2379                                 g_free(tmp);
2380                                 return -1;
2381                         }
2382                         g_free(tmp);
2383                 }
2384
2385                 if(fputs(filtering_str, fp) == EOF ||
2386                     fputc('\n', fp) == EOF) {
2387                         FILE_OP_ERROR("filtering config", "fputs || fputc");
2388                         g_free(filtering_str);
2389                         return -1;
2390                 }
2391                 g_free(filtering_str);
2392         }
2393         
2394         return 0;
2395 }
2396
2397 typedef struct _NodeLoopData {
2398         FILE *fp;
2399         gboolean error;
2400 } NodeLoopData;
2401
2402 /*!
2403  *\brief        Write matchers from a folder item
2404  *
2405  *\param        node Node with folder info
2406  *\param        data File pointer
2407  *
2408  *\return       gboolean FALSE
2409  */
2410 static gboolean prefs_matcher_write_func(GNode *node, gpointer d)
2411 {
2412         FolderItem *item;
2413         NodeLoopData *data = (NodeLoopData *)d;
2414         gchar *id;
2415         GSList *prefs_filtering;
2416
2417         item = node->data;
2418         /* prevent warning */
2419         if (item->path == NULL)
2420                 return FALSE;
2421         id = folder_item_get_identifier(item);
2422         if (id == NULL)
2423                 return FALSE;
2424         prefs_filtering = item->prefs->processing;
2425
2426         if (prefs_filtering != NULL) {
2427                 if (fprintf(data->fp, "[%s]\n", id) < 0) {
2428                         data->error = TRUE;
2429                         goto fail;
2430                 }
2431                 if (prefs_filtering_write(data->fp, prefs_filtering) < 0) {
2432                         data->error = TRUE;
2433                         goto fail;
2434                 }
2435                 if (fputc('\n', data->fp) == EOF) {
2436                         data->error = TRUE;
2437                         goto fail;
2438                 }
2439         }
2440 fail:
2441         g_free(id);
2442
2443         return FALSE;
2444 }
2445
2446 /*!
2447  *\brief        Save matchers from folder items
2448  *
2449  *\param        fp File
2450  */
2451 static int prefs_matcher_save(FILE *fp)
2452 {
2453         GList *cur;
2454         NodeLoopData data;
2455         
2456         data.fp = fp;
2457         data.error = FALSE;
2458
2459         for (cur = folder_get_list() ; cur != NULL ; cur = g_list_next(cur)) {
2460                 Folder *folder;
2461
2462                 folder = (Folder *) cur->data;
2463                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
2464                                 prefs_matcher_write_func, &data);
2465         }
2466         
2467         if (data.error == TRUE)
2468                 return -1;
2469
2470         /* pre global rules */
2471         if (fprintf(fp, "[preglobal]\n") < 0 ||
2472             prefs_filtering_write(fp, pre_global_processing) < 0 ||
2473             fputc('\n', fp) == EOF)
2474                 return -1;
2475
2476         /* post global rules */
2477         if (fprintf(fp, "[postglobal]\n") < 0 ||
2478             prefs_filtering_write(fp, post_global_processing) < 0 ||
2479             fputc('\n', fp) == EOF)
2480                 return -1;
2481         
2482         /* filtering rules */
2483         if (fprintf(fp, "[filtering]\n") < 0 ||
2484             prefs_filtering_write(fp, filtering_rules) < 0 ||
2485             fputc('\n', fp) == EOF)
2486                 return -1;
2487
2488         return 0;
2489 }
2490
2491 /*!
2492  *\brief        Write filtering / matcher configuration file
2493  */
2494 void prefs_matcher_write_config(void)
2495 {
2496         gchar *rcpath;
2497         PrefFile *pfile;
2498
2499         debug_print("Writing matcher configuration...\n");
2500
2501         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2502                              MATCHER_RC, NULL);
2503
2504         if ((pfile = prefs_write_open(rcpath)) == NULL) {
2505                 g_warning("failed to write configuration to file\n");
2506                 g_free(rcpath);
2507                 return;
2508         }
2509
2510         g_free(rcpath);
2511
2512         if (prefs_matcher_save(pfile->fp) < 0) {
2513                 g_warning("failed to write configuration to file\n");
2514                 prefs_file_close_revert(pfile);
2515         } else if (prefs_file_close(pfile) < 0) {
2516                 g_warning("failed to save configuration to file\n");
2517         }
2518 }
2519
2520 /* ******************************************************************* */
2521
2522 static void matcher_add_rulenames(const gchar *rcpath)
2523 {
2524         gchar *newpath = g_strconcat(rcpath, ".new", NULL);
2525         FILE *src = g_fopen(rcpath, "rb");
2526         FILE *dst = g_fopen(newpath, "wb");
2527         gchar buf[BUFFSIZE];
2528         int r;
2529
2530         if (src == NULL) {
2531                 perror("fopen");
2532                 if (dst)
2533                         fclose(dst);
2534                 g_free(newpath);
2535                 return;
2536         }
2537         if (dst == NULL) {
2538                 perror("fopen");
2539                 if (src)
2540                         fclose(src);
2541                 g_free(newpath);
2542                 return;
2543         }
2544
2545         while (fgets (buf, sizeof(buf), src) != NULL) {
2546                 if (strlen(buf) > 2 && buf[0] != '['
2547                 && strncmp(buf, "rulename \"", 10)
2548                 && strncmp(buf, "enabled rulename \"", 18)
2549                 && strncmp(buf, "disabled rulename \"", 18)) {
2550                         r = fwrite("enabled rulename \"\" ",
2551                                 strlen("enabled rulename \"\" "), 1, dst);
2552                         if (r != 1) {
2553                                 g_message("cannot fwrite rulename\n");
2554                         }
2555                 }
2556                 r = fwrite(buf, strlen(buf), 1, dst);
2557                 if (r != 1) {
2558                         g_message("cannot fwrite rule\n");
2559                 }
2560         }
2561         fclose(dst);
2562         fclose(src);
2563         move_file(newpath, rcpath, TRUE);
2564         g_free(newpath);
2565 }
2566
2567 /*!
2568  *\brief        Read matcher configuration
2569  */
2570 void prefs_matcher_read_config(void)
2571 {
2572         gchar *rcpath;
2573         gchar *rc_old_format;
2574         FILE *f;
2575
2576         create_matchparser_hashtab();
2577         prefs_filtering_clear();
2578
2579         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, NULL);
2580         rc_old_format = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MATCHER_RC, 
2581                                 ".pre_names", NULL);
2582         
2583         if (!is_file_exist(rc_old_format) && is_file_exist(rcpath)) {
2584                 /* backup file with no rules names, in case 
2585                  * anything goes wrong */
2586                 copy_file(rcpath, rc_old_format, FALSE);
2587                 /* now hack the file in order to have it to the new format */
2588                 matcher_add_rulenames(rcpath);
2589         }
2590         
2591         g_free(rc_old_format);
2592
2593         f = g_fopen(rcpath, "rb");
2594         g_free(rcpath);
2595
2596         if (f != NULL) {
2597                 matcher_parser_start_parsing(f);
2598                 fclose(matcher_parserin);
2599         }
2600         else {
2601                 /* previous version compatibility */
2602
2603                 /* g_print("reading filtering\n"); */
2604                 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2605                                      FILTERING_RC, NULL);
2606                 f = g_fopen(rcpath, "rb");
2607                 g_free(rcpath);
2608                 
2609                 if (f != NULL) {
2610                         matcher_parser_start_parsing(f);
2611                         fclose(matcher_parserin);
2612                 }
2613                 
2614                 /* g_print("reading scoring\n"); */
2615                 rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2616                                      SCORING_RC, NULL);
2617                 f = g_fopen(rcpath, "rb");
2618                 g_free(rcpath);
2619                 
2620                 if (f != NULL) {
2621                         matcher_parser_start_parsing(f);
2622                         fclose(matcher_parserin);
2623                 }
2624         }
2625 }