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