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