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