fix actions: escaping, forwarding, execute
[claws.git] / src / filtering.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto & The Sylpheed Claws Team
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 /* 
21  * initital     Hoa             initial
22  * 07/16/01     Alfons          fix bugs
23  * 07/18/01     Alfons          rewrite things
24  */
25
26 /* 07/18/01 (alfons) 
27  * 
28  * filter_message() is no longer the entry point for filtering. it's
29  * replaced with filter_incoming_message() which does not trust
30  * on MsgInfo's from a folder. instead it directly works with
31  * the temporary file.  
32  * updating the mark file is a lot easier now, because we can do that
33  * right after a call to folder_item_add_msg(). 
34  */ 
35
36 #include <ctype.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <errno.h>
40 #include <gtk/gtk.h>
41 #include <stdio.h>
42 #include "intl.h"
43 #include "utils.h"
44 #include "defs.h"
45 #include "procheader.h"
46 #include "matcher.h"
47 #include "filtering.h"
48 #include "prefs.h"
49 #include "compose.h"
50
51 #define PREFSBUFSIZE            1024
52
53 GSList * prefs_filtering = NULL;
54
55 FilteringAction * filteringaction_new(int type, int account_id,
56                                       gchar * destination)
57 {
58         FilteringAction * action;
59
60         action = g_new0(FilteringAction, 1);
61
62         action->type = type;
63         action->account_id = account_id;
64         if (destination)
65                 action->destination = g_strdup(destination);
66
67         return action;
68 }
69
70 void filteringaction_free(FilteringAction * action)
71 {
72         if (action->destination)
73                 g_free(action->destination);
74         g_free(action);
75 }
76
77 FilteringAction * filteringaction_parse(gchar ** str)
78 {
79         FilteringAction * action;
80         gchar * tmp;
81         gchar * destination = NULL;
82         gint account_id = 0;
83         gint key;
84
85         tmp = * str;
86
87         key = matcher_parse_keyword(&tmp);
88
89         switch (key) {
90         case MATCHING_ACTION_MOVE:
91         case MATCHING_ACTION_COPY:
92         case MATCHING_EXECUTE:
93                 destination = matcher_parse_str(&tmp);
94                 if (tmp == NULL) {
95                         * str = NULL;
96                         return NULL;
97                 }
98                 break;
99         case MATCHING_ACTION_DELETE:
100                 break;
101         case MATCHING_ACTION_MARK:
102                 break;
103         case MATCHING_ACTION_MARK_AS_READ:
104                 break;
105         case MATCHING_ACTION_UNMARK:
106                 break;
107         case MATCHING_ACTION_MARK_AS_UNREAD:
108                 break;
109         case MATCHING_ACTION_FORWARD:
110         case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
111                 account_id = matcher_parse_number(&tmp);
112                 if (tmp == NULL) {
113                         * str = NULL;
114                         return NULL;
115                 }
116
117                 destination = matcher_parse_str(&tmp);
118                 if (tmp == NULL) {
119                         * str = NULL;
120                         return NULL;
121                 }
122
123                 break;
124         default:
125                 * str = NULL;
126                 return NULL;
127         }
128
129         * str = tmp;
130
131         action = filteringaction_new(key, account_id, destination);
132
133         return action;
134 }
135
136 FilteringProp * filteringprop_parse(gchar ** str)
137 {
138         gchar * tmp;
139         gint key;
140         FilteringProp * filtering;
141         MatcherList * matchers;
142         FilteringAction * action;
143         
144         tmp = * str;
145
146         matchers = matcherlist_parse(&tmp);
147         if (tmp == NULL) {
148                 * str = NULL;
149                 return NULL;
150         }
151
152         if (tmp == NULL) {
153                 matcherlist_free(matchers);
154                 * str = NULL;
155                 return NULL;
156         }
157
158         action = filteringaction_parse(&tmp);
159         if (tmp == NULL) {
160                 matcherlist_free(matchers);
161                 * str = NULL;
162                 return NULL;
163         }
164
165         filtering = filteringprop_new(matchers, action);
166
167         * str = tmp;
168         return filtering;
169 }
170
171
172 FilteringProp * filteringprop_new(MatcherList * matchers,
173                                   FilteringAction * action)
174 {
175         FilteringProp * filtering;
176
177         filtering = g_new0(FilteringProp, 1);
178         filtering->matchers = matchers;
179         filtering->action = action;
180
181         return filtering;
182 }
183
184 void filteringprop_free(FilteringProp * prop)
185 {
186         matcherlist_free(prop->matchers);
187         filteringaction_free(prop->action);
188         g_free(prop);
189 }
190
191 /* filteringaction_update_mark() - updates a mark for a message. note that
192  * the message should not have been moved or copied. remember that the
193  * procmsg_open_mark_file(PATH, TRUE) actually _appends_ a new record.
194  */
195 static gboolean filteringaction_update_mark(MsgInfo * info)
196 {
197         gchar * dest_path;
198         FILE * fp;
199
200         if (info->folder->folder->type == F_MH) {
201                 dest_path = folder_item_get_path(info->folder);
202                 if (!is_dir_exist(dest_path))
203                         make_dir_hier(dest_path);
204                 
205                 if (dest_path == NULL) {
206                         g_warning(_("Can't open mark file.\n"));
207                         return FALSE;
208                 }
209                 
210                 if ((fp = procmsg_open_mark_file(dest_path, TRUE))
211                     == NULL) {
212                         g_warning(_("Can't open mark file.\n"));
213                         return FALSE;
214                 }
215                 
216                 procmsg_write_flags(info, fp);
217                 fclose(fp);
218                 return TRUE;
219         }
220         return FALSE;
221 }
222
223 static inline gint strlen_with_check(const gchar *expr, gint fline, const gchar *str)
224 {
225         if (str) 
226                 return strlen(str);
227         else {
228                 debug_print("%s(%d) - invalid string %s\n", __FILE__, fline, expr);
229                 return 0;
230         }
231 }
232
233 #define STRLEN_WITH_CHECK(expr) \
234         strlen_with_check(#expr, __LINE__, expr)
235         
236 static gchar * filteringaction_execute_command(gchar * cmd, MsgInfo * info)
237 {
238         gchar * s = cmd;
239         gchar * filename = NULL;
240         gchar * processed_cmd;
241         gchar * p;
242         gint size;
243
244         matcher_unescape_str(cmd);
245
246         size = strlen(cmd) + 1;
247         while (*s != '\0') {
248                 if (*s == '%') {
249                         s++;
250                         switch (*s) {
251                         case '%':
252                                 size -= 1;
253                                 break;
254                         case 's': /* subject */
255                                 size += STRLEN_WITH_CHECK(info->subject) - 2;
256                                 break;
257                         case 'f': /* from */
258                                 size += STRLEN_WITH_CHECK(info->from) - 2;
259                                 break;
260                         case 't': /* to */
261                                 size += STRLEN_WITH_CHECK(info->to) - 2;
262                                 break;
263                         case 'c': /* cc */
264                                 size += STRLEN_WITH_CHECK(info->cc) - 2;
265                                 break;
266                         case 'd': /* date */
267                                 size += STRLEN_WITH_CHECK(info->date) - 2;
268                                 break;
269                         case 'i': /* message-id */
270                                 size += STRLEN_WITH_CHECK(info->msgid) - 2;
271                                 break;
272                         case 'n': /* newsgroups */
273                                 size += STRLEN_WITH_CHECK(info->newsgroups) - 2;
274                                 break;
275                         case 'r': /* references */
276                                 size += STRLEN_WITH_CHECK(info->references) - 2;
277                                 break;
278                         case 'F': /* file */
279                                 if (MSG_IS_FILTERING(info->flags))
280                                         filename = g_strdup(info->folder);
281                                 else
282                                         filename = folder_item_fetch_msg(info->folder, info->msgnum);
283                                 
284                                 if (filename == NULL) {
285                                         g_warning(_("filename is not set"));
286                                         return NULL;
287                                 }
288                                 else
289                                         size += strlen(filename) - 2;
290                                 break;
291                         }
292                         s++;
293                 }
294                 else s++;
295         }
296
297
298         processed_cmd = g_new0(gchar, size);
299         s = cmd;
300         p = processed_cmd;
301
302         while (*s != '\0') {
303                 if (*s == '%') {
304                         s++;
305                         switch (*s) {
306                         case '%':
307                                 *p = '%';
308                                 p++;
309                                 break;
310                         case 's': /* subject */
311                                 if (info->subject != NULL)
312                                         strcpy(p, info->subject);
313                                 else
314                                         strcpy(p, "(none)");
315                                 p += strlen(p);
316                                 break;
317                         case 'f': /* from */
318                                 if (info->from != NULL)
319                                         strcpy(p, info->from);
320                                 else
321                                         strcpy(p, "(none)");
322                                 p += strlen(p);
323                                 break;
324                         case 't': /* to */
325                                 if (info->to != NULL)
326                                         strcpy(p, info->to);
327                                 else
328                                         strcpy(p, "(none)");
329                                 p += strlen(p);
330                                 break;
331                         case 'c': /* cc */
332                                 if (info->cc != NULL)
333                                         strcpy(p, info->cc);
334                                 else
335                                         strcpy(p, "(none)");
336                                 p += strlen(p);
337                                 break;
338                         case 'd': /* date */
339                                 if (info->date != NULL)
340                                         strcpy(p, info->date);
341                                 else
342                                         strcpy(p, "(none)");
343                                 p += strlen(p);
344                                 break;
345                         case 'i': /* message-id */
346                                 if (info->msgid != NULL)
347                                         strcpy(p, info->msgid);
348                                 else
349                                         strcpy(p, "(none)");
350                                 p += strlen(p);
351                                 break;
352                         case 'n': /* newsgroups */
353                                 if (info->newsgroups != NULL)
354                                         strcpy(p, info->newsgroups);
355                                 else
356                                         strcpy(p, "(none)");
357                                 p += strlen(p);
358                                 break;
359                         case 'r': /* references */
360                                 if (info->references != NULL)
361                                         strcpy(p, info->references);
362                                 else
363                                         strcpy(p, "(none)");
364                                 p += strlen(p);
365                                 break;
366                         case 'F': /* file */
367                                 strcpy(p, filename);
368                                 p += strlen(p);
369                                 break;
370                         default:
371                                 *p = '%';
372                                 p++;
373                                 *p = *s;
374                                 p++;
375                                 break;
376                         }
377                         s++;
378                 }
379                 else {
380                         *p = *s;
381                         p++;
382                         s++;
383                 }
384         }
385
386         g_free(filename);
387         return processed_cmd;
388 }
389
390 /*
391   fitleringaction_apply
392   runs the action on one MsgInfo
393   return value : return TRUE if the action could be applied
394 */
395
396 #define CHANGE_FLAGS(msginfo) \
397 { \
398 if (msginfo->folder->folder->change_flags != NULL) \
399 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
400                                       msginfo->folder, \
401                                       msginfo); \
402 }
403
404 static gboolean filteringaction_apply(FilteringAction * action, MsgInfo * info,
405                                       GHashTable *folder_table)
406 {
407         FolderItem * dest_folder;
408         gint val;
409         Compose * compose;
410         PrefsAccount * account;
411         gchar * cmd;
412
413         switch(action->type) {
414         case MATCHING_ACTION_MOVE:
415                 dest_folder =
416                         folder_find_item_from_identifier(action->destination);
417                 if (!dest_folder)
418                         return FALSE;
419
420                 if (folder_item_move_msg(dest_folder, info) == -1)
421                         return FALSE;
422
423                 /* WRONG: can not update the mark, because the message has 
424                  * been moved. info pertains to original location. 
425                  * folder_item_move_msg() already updated the mark for the
426                  * destination folder.
427                 info->flags = 0;
428                 filteringaction_update_mark(info);
429                  */
430                 if (folder_table) {
431                         val = GPOINTER_TO_INT(g_hash_table_lookup
432                                               (folder_table, dest_folder));
433                         if (val == 0) {
434                                 folder_item_scan(dest_folder);
435                                 g_hash_table_insert(folder_table, dest_folder,
436                                                     GINT_TO_POINTER(1));
437                         }
438                         val = GPOINTER_TO_INT(g_hash_table_lookup
439                                               (folder_table, info->folder));
440                         if (val == 0) {
441                                 folder_item_scan(info->folder);
442                                 g_hash_table_insert(folder_table, info->folder,
443                                                     GINT_TO_POINTER(1));
444                         }
445                 }
446                 return TRUE;
447
448         case MATCHING_ACTION_COPY:
449                 dest_folder =
450                         folder_find_item_from_identifier(action->destination);
451
452                 if (!dest_folder)
453                         return FALSE;
454
455                 /* NOTE: the following call *will* update the mark file for
456                  * the destination folder. but the original message will
457                  * still be there in the inbox. */
458
459                 if (folder_item_copy_msg(dest_folder, info) == -1)
460                         return FALSE;
461
462                 if (folder_table) {
463                         val = GPOINTER_TO_INT(g_hash_table_lookup
464                                               (folder_table, dest_folder));
465                         if (val == 0) {
466                                 folder_item_scan(dest_folder);
467                                 g_hash_table_insert(folder_table, dest_folder,
468                                                     GINT_TO_POINTER(1));
469                         }
470                 }
471                         
472                 return TRUE;
473
474         case MATCHING_ACTION_DELETE:
475                 if (folder_item_remove_msg(info->folder, info->msgnum) == -1)
476                         return FALSE;
477
478                 /* WRONG: can not update the mark. this would actually add
479                  * a bogus record to the mark file for the message's original 
480                  * folder. 
481                 info->flags = 0;
482                 filteringaction_update_mark(info);
483                  */
484
485                 return TRUE;
486
487         case MATCHING_ACTION_MARK:
488                 MSG_SET_PERM_FLAGS(info->flags, MSG_MARKED);
489                 debug_print("*** MARKING message %d, in folder %s, \"%s\"\n",
490                             info->msgnum, info->folder->name,
491                             info->subject ? info->subject : "<none>");
492                 filteringaction_update_mark(info);
493
494                 CHANGE_FLAGS(info);
495
496                 return TRUE;
497
498         case MATCHING_ACTION_UNMARK:
499                 MSG_UNSET_PERM_FLAGS(info->flags, MSG_MARKED);
500                 filteringaction_update_mark(info);
501
502                 CHANGE_FLAGS(info);
503
504                 return TRUE;
505                 
506         case MATCHING_ACTION_MARK_AS_READ:
507                 MSG_UNSET_PERM_FLAGS(info->flags, MSG_UNREAD | MSG_NEW);
508                 filteringaction_update_mark(info);
509
510                 CHANGE_FLAGS(info);
511
512                 return TRUE;
513
514         case MATCHING_ACTION_MARK_AS_UNREAD:
515                 MSG_SET_PERM_FLAGS(info->flags, MSG_UNREAD | MSG_NEW);
516                 filteringaction_update_mark(info);
517
518                 CHANGE_FLAGS(info);
519                 
520                 return TRUE;
521
522         case MATCHING_ACTION_FORWARD:
523
524                 account = account_find_from_id(action->account_id);
525                 compose = compose_forward(account, info, FALSE);
526                 if (compose->account->protocol == A_NNTP)
527                         compose_entry_append(compose, action->destination,
528                                              COMPOSE_NEWSGROUPS);
529                 else
530                         compose_entry_append(compose, action->destination,
531                                              COMPOSE_TO);
532
533                 val = compose_send(compose);
534                 if (val == 0) {
535                         gtk_widget_destroy(compose->window);
536                         return TRUE;
537                 }
538
539                 gtk_widget_destroy(compose->window);
540                 return FALSE;
541
542         case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
543
544                 account = account_find_from_id(action->account_id);
545                 compose = compose_forward(account, info, TRUE);
546                 if (compose->account->protocol == A_NNTP)
547                         compose_entry_append(compose, action->destination,
548                                              COMPOSE_NEWSGROUPS);
549                 else
550                         compose_entry_append(compose, action->destination,
551                                              COMPOSE_TO);
552
553                 val = compose_send(compose);
554                 if (val == 0) {
555                         gtk_widget_destroy(compose->window);
556                         return TRUE;
557                 }
558
559                 gtk_widget_destroy(compose->window);
560                 return FALSE;
561
562         case MATCHING_EXECUTE:
563
564                 cmd = matching_build_command(action->destination, info);
565                 if (cmd == NULL)
566                         return TRUE;
567                 else {
568                         system(cmd);
569                         g_free(cmd);
570                 }
571
572                 return TRUE;
573
574         default:
575                 return FALSE;
576         }
577 }
578
579 /* filteringprop_apply() - runs the action on one MsgInfo if it matches the 
580  * criterium. certain actions can be followed by other actions. in this
581  * case the function returns FALSE. if an action can not be followed
582  * by others, the function returns TRUE.
583  *
584  * remember that this is because of the fact that msg flags are always
585  * _appended_ to mark files. currently sylpheed does not insert messages 
586  * at a certain index. 
587  * now, after having performed a certain action, the MsgInfo is still
588  * valid for the message. in *this* case the function returns FALSE.
589  */
590 static gboolean filteringprop_apply(FilteringProp * filtering, MsgInfo * info,
591                                     GHashTable *folder_table)
592 {
593         if (matcherlist_match(filtering->matchers, info)) {
594                 gint result;
595                 gchar * action_str;
596
597                 result = TRUE;
598
599                 result = filteringaction_apply(filtering->action, info,
600                                                folder_table);
601                 action_str =
602                         filteringaction_to_string(filtering->action);
603                 if (!result) {
604                         g_warning(_("action %s could not be applied"),
605                                   action_str);
606                 }
607                 else {
608                         debug_print(_("message %i %s..."),
609                                       info->msgnum, action_str);
610                 }
611
612                 g_free(action_str);
613
614                 switch(filtering->action->type) {
615                 case MATCHING_ACTION_MOVE:
616                 case MATCHING_ACTION_DELETE:
617                         return TRUE; /* MsgInfo invalid for message */
618                 case MATCHING_EXECUTE:
619                 case MATCHING_ACTION_COPY:
620                 case MATCHING_ACTION_MARK:
621                 case MATCHING_ACTION_MARK_AS_READ:
622                 case MATCHING_ACTION_UNMARK:
623                 case MATCHING_ACTION_MARK_AS_UNREAD:
624                 case MATCHING_ACTION_FORWARD:
625                 case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
626                         return FALSE; /* MsgInfo still valid for message */
627                 default:
628                         return FALSE;
629                 }
630         }
631         else
632                 return FALSE;
633 }
634
635 void filter_msginfo(GSList * filtering_list, MsgInfo * info,
636                     GHashTable *folder_table)
637 {
638         GSList * l;
639
640         if (info == NULL) {
641                 g_warning(_("msginfo is not set"));
642                 return;
643         }
644         
645         for(l = filtering_list ; l != NULL ; l = g_slist_next(l)) {
646                 FilteringProp * filtering = (FilteringProp *) l->data;
647                 
648                 if (filteringprop_apply(filtering, info, folder_table))
649                         break;
650         }
651 }
652
653 void filter_msginfo_move_or_delete(GSList * filtering_list, MsgInfo * info,
654                                    GHashTable *folder_table)
655 {
656         GSList * l;
657
658         if (info == NULL) {
659                 g_warning(_("msginfo is not set"));
660                 return;
661         }
662         
663         for(l = filtering_list ; l != NULL ; l = g_slist_next(l)) {
664                 FilteringProp * filtering = (FilteringProp *) l->data;
665
666                 switch (filtering->action->type) {
667                 case MATCHING_ACTION_MOVE:
668                 case MATCHING_ACTION_DELETE:
669                         if (filteringprop_apply(filtering, info, folder_table))
670                                 return;
671                 }
672         }
673 }
674
675 void filter_message(GSList * filtering_list, FolderItem * item,
676                     gint msgnum, GHashTable *folder_table)
677 {
678         MsgInfo * msginfo;
679         gchar * filename;
680         MsgFlags  msgflags = { 0, 0 };
681
682         if (item == NULL) {
683                 g_warning(_("folderitem not set"));
684                 return;
685         }
686
687         filename = folder_item_fetch_msg(item, msgnum);
688
689         if (filename == NULL) {
690                 g_warning(_("filename is not set"));
691                 return;
692         }
693
694         msginfo = procheader_parse(filename, msgflags, TRUE);
695         
696         g_free(filename);
697
698         if (msginfo == NULL) {
699                 g_warning(_("could not get info for %s"), filename);
700                 return;
701         }
702
703         msginfo->folder = item;
704         msginfo->msgnum = msgnum;
705
706         filter_msginfo(filtering_list, msginfo, folder_table);
707 }
708
709
710 /******************************************************************************/
711
712 /* revised filtering system.  
713  * 
714  * 07/18/01     alfons          initial revisement
715  */
716
717 /* (alfons)
718  * 
719  * the revised filtering system does not rely on a message being "registered"
720  * in one of sylpheed's folders. it now uses the file sylpheed created on
721  * incorporation of mail. 
722  * i do use MsgInfo data; that's needed by the matcher, but for the rest
723  * the MsgInfo is not really used. */
724  
725
726 /* add_mark() - adds a mark for a file */
727 static void add_mark(FolderItem *folder, gint msgnum, MsgPermFlags flags)
728 {
729         gchar * dest_path;
730         FILE * fp;
731
732         if (folder->folder->type == F_MH) {
733                 dest_path = folder_item_get_path(folder);
734                 if (!is_dir_exist(dest_path))
735                         make_dir_hier(dest_path);
736                 
737                 if (dest_path == NULL) {
738                         g_warning(_("Can't open mark file.\n"));
739                         return;
740                 }
741                 
742                 if ((fp = procmsg_open_mark_file(dest_path, TRUE))
743                     == NULL) {
744                         g_warning(_("Can't open mark file.\n"));
745                         return;
746                 }
747
748                 /* TODO: straight from procmsg.c:procmsg_write_flags()
749                  * should update this when mark file version changes */
750 #if MARK_VERSION == 2            
751                 WRITE_CACHE_DATA_INT(msgnum, fp);
752                 WRITE_CACHE_DATA_INT(flags, fp);
753 #else
754 #error should rewrite the above for new  mark version   
755                 /* paste the source code of procmsg.c:procmsg_write_flags() */
756 #endif
757                 fclose(fp);
758                 return;
759         }
760         return;
761 }
762
763 /* prepare_destination() - prepares destination folder by registering it 
764  * in the global folder table (if not already there). it returns TRUE if
765  * successful. it also returns the FolderItem for the destination */
766 static gboolean prepare_destination(const gchar *destination, FolderItem **item, 
767                                     GHashTable *folder_table)
768 {
769         gint val;
770         FolderItem *result;
771
772         result = folder_find_item_from_identifier(destination);
773         if (!result)
774                 return FALSE;
775         if (folder_table) {
776                 *item = result;
777                 val = GPOINTER_TO_INT(g_hash_table_lookup(folder_table, *item));
778                 if (val == 0) {
779                         folder_item_scan(*item);
780                         g_hash_table_insert(folder_table, *item, GINT_TO_POINTER(1));
781                 }
782         }
783         return TRUE;
784 }
785
786 /* filter_incoming_perform_actions() - performs actions on incoming
787  * message. this function handles updating marks a little bit smarter;
788  * remember that marks can only be appended. */
789 static gboolean filter_incoming_perform_actions(FolderItem *default_folder, 
790                                                 MsgInfo    *msginfo,
791                                                 GHashTable *folder_table)
792 {
793         /* matching actions for msginfo */
794         struct matching_action {
795                 FilteringAction         *action;
796                 struct matching_action  *next;
797         };
798
799         struct matching_action  ma_head = { NULL, NULL };
800         struct matching_action *ma_tail = &ma_head;
801
802         /* need this for the forwarding stuff */
803         PrefsAccount *account;
804         Compose      *compose;
805         MsgFlags      tmp;
806         gchar        *fwd_msg_name;
807         gint          val;
808         MsgInfo      *fwd_msg;
809
810         MsgFlags     markflags = { 0, 0 };
811
812         /* use the global prefs_filtering list */
813         GSList *     list = prefs_filtering;
814
815         /* things we get after having added a message to a folder */
816         FolderItem  *dest_folder;
817         gint         msgnum;
818         
819         /* after performing certain action, we may have to copy 
820          * the message to inbox too */
821         gboolean     copy_to_inbox_too = TRUE;
822         
823         /* filename is only put in msginfo->folder if MSG_FILTERING is set. */
824         const gchar *filename = (gchar *) msginfo->folder;
825         
826         MsgPermFlags flags;
827         gboolean     stop;
828         gchar        *cmd;
829
830         /* build list of matching actions */
831         for (; list != NULL; list = g_slist_next(list)) {
832                 FilteringProp *prop = (FilteringProp *) list->data;
833                 
834                 if (!matcherlist_match(prop->matchers, msginfo))
835                         continue;
836
837                 if (NULL == (ma_tail->next = alloca(sizeof(struct matching_action)))) {
838                         debug_print(_("action allocation error\n"));
839                         break;
840                 }
841
842                 debug_print("*** action %d\n", prop->action->type);
843
844                 ma_tail->action = prop->action;
845                 ma_tail->next->action = NULL;
846                 ma_tail->next->next = NULL;
847                 ma_tail = ma_tail->next;
848         }
849
850         debug_print("*** collecting marks\n");          
851         
852         /* collect all marks */
853         for (ma_tail = &ma_head, stop = FALSE; ma_tail->action && !stop; ma_tail = ma_tail->next) {
854                 switch (ma_tail->action->type) {
855                 
856                 case MATCHING_ACTION_MARK:
857                         MSG_SET_PERM_FLAGS(markflags, MSG_MARKED);
858                         break;
859                         
860                 case MATCHING_ACTION_UNMARK:
861                         MSG_UNSET_PERM_FLAGS(markflags, MSG_MARKED);
862                         break;
863                 
864                 case MATCHING_ACTION_MARK_AS_READ:
865                         MSG_UNSET_PERM_FLAGS(markflags, MSG_UNREAD);
866                         break;
867
868                 case MATCHING_ACTION_MARK_AS_UNREAD:                    
869                         MSG_SET_PERM_FLAGS(markflags, MSG_UNREAD);
870                         break;
871
872                 /* UNCONTINUABLE */
873                 case MATCHING_ACTION_FORWARD:
874                 case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
875                 case MATCHING_ACTION_MOVE:
876                 case MATCHING_ACTION_DELETE:
877                         stop = TRUE;
878                         break;
879                 
880                 default:
881                         break;
882                 }
883         }
884
885
886         /* msgnum & dest_folder should have valid values after a succesful
887          * drop; in this case there is a MsgInfo available */
888         msgnum      = -1;
889         dest_folder = NULL;
890
891         debug_print("*** performing actions\n"); 
892         
893         for (ma_tail = &ma_head ; ma_tail->action; ma_tail = ma_tail->next) {
894
895                 /* there are variables you have to use when defining new actions:
896                  *
897                  * copy_to_inbox_too - if the original message should be copied to the inbox 
898                  *                     (default_folder) too.
899                  * 
900                  * also note that after dropping it to a folder (folder_item_add_msg()) you have
901                  * to mark the message, just to make sure any defined mark actions are applied. */
902                  
903 #define ACTION  (ma_tail->action->type) 
904
905                 /* C O N T I N U A B L E */
906
907                 if (MATCHING_ACTION_COPY == ACTION) {
908                         debug_print("*** performing copy\n");
909                         copy_to_inbox_too = TRUE;
910                         if (!prepare_destination(ma_tail->action->destination, &dest_folder, folder_table)) {
911                                 debug_print("Rule failed: unknown destination %s\n", ma_tail->action->destination);
912                                 continue; /* try next action */
913                         }
914                         if (0 > (msgnum = folder_item_add_msg(dest_folder, filename, FALSE))) {
915                                 debug_print(_("Rule failed: could not copy to folder %s\n"),
916                                             ma_tail->action->destination);
917                                 continue; /* try next action */     
918                         }   
919                         flags = msginfo->flags.perm_flags | markflags.perm_flags;
920                         add_mark(dest_folder, msgnum, flags);
921                 }               
922                 else if (MATCHING_EXECUTE == ACTION) {
923                         debug_print("*** performing exec\n");
924                         copy_to_inbox_too = TRUE;
925                         
926                         /* matching_build_command() knows about filtering */
927                         cmd = matching_build_command(ma_tail->action->destination, msginfo);
928                         if (cmd) { 
929                                 system(cmd);
930                                 g_free(cmd);
931                         }
932                         else
933                                 debug_print(_("Rule failed: no command line\n"));
934                 } 
935
936                 /* U N C O N T I N U A B L E */
937                 
938                 else if (MATCHING_ACTION_FORWARD == ACTION
939                 ||       MATCHING_ACTION_FORWARD_AS_ATTACHMENT == ACTION) {
940                         debug_print("*** performing forward\n");
941
942                         /* forwarding messages is complicated because there's currently no 
943                          * way to forward a message using "filenames"; you can only forward
944                          * a message if you have its MsgInfo. this means we have to drop
945                          * the message first */ 
946                         if (0 > (msgnum = folder_item_add_msg(default_folder, filename, FALSE))) {
947                                 debug_print(_("Rule failed: could not forward\n"));
948                                 copy_to_inbox_too = TRUE;
949                                 continue;
950                         }
951                                 
952                         flags = msginfo->flags.perm_flags | markflags.perm_flags;
953                         flags |= MSG_FORWARDED;
954                         add_mark(default_folder, msgnum, flags);
955
956                         /* grab the dropped message */
957                         fwd_msg_name = folder_item_fetch_msg(default_folder, msgnum);
958
959                         tmp.perm_flags = tmp.tmp_flags = 0;
960                         fwd_msg = procheader_parse(fwd_msg_name, tmp, TRUE);
961
962                         fwd_msg->folder = default_folder;
963                         fwd_msg->msgnum = msgnum;
964
965                         /* do the compose_XXX stuff */
966                         account = account_find_from_id(ma_tail->action->account_id);
967                         compose = compose_forward(account, fwd_msg, ACTION == MATCHING_ACTION_FORWARD ? FALSE : TRUE);
968                         if (compose->account->protocol == A_NNTP)
969                                 compose_entry_append(compose, ma_tail->action->destination,
970                                                      COMPOSE_NEWSGROUPS);
971                         else
972                                 compose_entry_append(compose, ma_tail->action->destination,
973                                                      COMPOSE_TO);
974
975                         compose_send(compose);
976
977                         procmsg_msginfo_free(fwd_msg);
978                         
979                         gtk_widget_destroy(compose->window);
980                         break;
981                 }                       
982                 else if (MATCHING_ACTION_DELETE == ACTION) {
983                         debug_print("*** performing delete\n");
984                         copy_to_inbox_too = FALSE;
985                         if (unlink(filename) < 0)
986                                 debug_print(_("Rule failed: could not delete message\n"));
987                         break;                          
988                 }
989                 else if (MATCHING_ACTION_MOVE == ACTION) {
990                         debug_print("*** performing move\n");
991                         copy_to_inbox_too = FALSE;
992                         
993                         if (!prepare_destination(ma_tail->action->destination, &dest_folder, folder_table)) {
994                                 copy_to_inbox_too = TRUE;
995                                 break;
996                         }
997                                 
998                         msgnum = folder_item_add_msg(dest_folder, filename, FALSE);
999                         if (msgnum < 0) {
1000                                 debug_print(_("Rule failed: could not move to folder %s\n"),
1001                                             ma_tail->action->destination);
1002                                 copy_to_inbox_too = TRUE;                                          
1003                                 break;
1004                         }   
1005                         
1006                         flags = msginfo->flags.perm_flags | markflags.perm_flags;
1007                         add_mark(dest_folder, msgnum, flags);
1008                         break;
1009                 }
1010         }
1011
1012         /* may need to copy it to inbox too */
1013         if (copy_to_inbox_too) {
1014                 debug_print("*** performing inbox copy\n");
1015                 msgnum = folder_item_add_msg(default_folder, filename, TRUE);
1016                 if (msgnum < 0) {
1017                         debug_print(_("error copying incoming file %s to inbox\n"), 
1018                                     filename);
1019                         return FALSE;                               
1020                 }
1021                 flags = msginfo->flags.perm_flags | markflags.perm_flags;
1022                 add_mark(default_folder, msgnum, flags);
1023         }
1024         else {
1025                 debug_print("*** unlinking\n");
1026                 if (unlink(filename) < 0) 
1027                         debug_print(_("error deleting incoming message file\n"));
1028         }
1029
1030 #undef ACTION
1031
1032         return TRUE;
1033 }
1034
1035 static void filter_incoming_msginfo(FolderItem *default_folder, MsgInfo *msginfo, 
1036                                     GHashTable *folder_table)
1037 {
1038         filter_incoming_perform_actions(default_folder, msginfo, folder_table); 
1039 }
1040
1041 /* filter_incoming_message() - tries to apply a filter on one incoming message.
1042  * it also handles the case when there's no filter match */
1043 void filter_incoming_message(FolderItem *default_folder, const gchar *file_name, 
1044                              GHashTable *folder_table)
1045 {
1046         MsgInfo *msginfo;
1047         MsgFlags msgflags = { 0, 0 };
1048         
1049         /* make an "uncomplete" msginfo. it's incomplete because it doesn't
1050          * have a message number / folder yet. */
1051         if (NULL == (msginfo = procheader_parse(file_name, msgflags, TRUE))) {
1052                 g_warning(_("error filtering incoming message %s\n"), 
1053                           file_name);
1054                 return;         
1055         }
1056
1057         /* let matcher know that this is a message that has no
1058          * valid body data yet. */
1059         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_FILTERING);
1060         msginfo->folder = g_strdup(file_name);
1061         msginfo->msgnum = 0;
1062
1063         filter_incoming_msginfo(default_folder, msginfo, folder_table);
1064
1065         g_free(msginfo->folder);
1066         procmsg_msginfo_free(msginfo);
1067 }
1068
1069 /******************************************************************************/
1070
1071 void prefs_filtering_read_config(void)
1072 {
1073         gchar *rcpath;
1074         FILE *fp;
1075         gchar buf[PREFSBUFSIZE];
1076
1077         debug_print(_("Reading filtering configuration...\n"));
1078
1079         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1080                              FILTERING_RC, NULL);
1081         if ((fp = fopen(rcpath, "r")) == NULL) {
1082                 if (ENOENT != errno) FILE_OP_ERROR(rcpath, "fopen");
1083                 g_free(rcpath);
1084                 prefs_filtering = NULL;
1085                 return;
1086         }
1087         g_free(rcpath);
1088
1089         /* remove all filtering */
1090         while (prefs_filtering != NULL) {
1091                 FilteringProp * filtering =
1092                         (FilteringProp *) prefs_filtering->data;
1093                 filteringprop_free(filtering);
1094                 prefs_filtering = g_slist_remove(prefs_filtering, filtering);
1095         }
1096
1097         while (fgets(buf, sizeof(buf), fp) != NULL) {
1098                 FilteringProp * filtering;
1099                 gchar * tmp;
1100
1101                 g_strchomp(buf);
1102
1103                 if ((*buf != '#') && (*buf != '\0')) {
1104                         tmp = buf;
1105                         filtering = filteringprop_parse(&tmp);
1106                         if (tmp != NULL) {
1107                                 prefs_filtering =
1108                                         g_slist_append(prefs_filtering,
1109                                                        filtering);
1110                         }
1111                         else {
1112                                 /* debug */
1113                                 g_warning(_("syntax error : %s\n"), buf);
1114                         }
1115                 }
1116         }
1117
1118         fclose(fp);
1119 }
1120
1121 gchar * filteringaction_to_string(FilteringAction * action)
1122 {
1123         gchar * command_str;
1124         gint i;
1125         gchar * account_id_str;
1126
1127         command_str = NULL;
1128         command_str = get_matchparser_tab_str(action->type);
1129
1130         if (command_str == NULL)
1131                 return NULL;
1132
1133         switch(action->type) {
1134         case MATCHING_ACTION_MOVE:
1135         case MATCHING_ACTION_COPY:
1136         case MATCHING_EXECUTE:
1137                 return g_strconcat(command_str, " \"", action->destination,
1138                                    "\"", NULL);
1139
1140         case MATCHING_ACTION_DELETE:
1141         case MATCHING_ACTION_MARK:
1142         case MATCHING_ACTION_UNMARK:
1143         case MATCHING_ACTION_MARK_AS_READ:
1144         case MATCHING_ACTION_MARK_AS_UNREAD:
1145                 return g_strdup(command_str);
1146                 break;
1147
1148         case MATCHING_ACTION_FORWARD:
1149         case MATCHING_ACTION_FORWARD_AS_ATTACHMENT:
1150                 account_id_str = itos(action->account_id);
1151                 return g_strconcat(command_str, " ", account_id_str,
1152                                    " \"", action->destination, "\"", NULL);
1153
1154         default:
1155                 return NULL;
1156         }
1157 }
1158
1159 gchar * filteringprop_to_string(FilteringProp * prop)
1160 {
1161         gchar * list_str;
1162         gchar * action_str;
1163         gchar * filtering_str;
1164
1165         action_str = filteringaction_to_string(prop->action);
1166
1167         if (action_str == NULL)
1168                 return NULL;
1169
1170         list_str = matcherlist_to_string(prop->matchers);
1171
1172         if (list_str == NULL) {
1173                 g_free(action_str);
1174                 return NULL;
1175         }
1176
1177         filtering_str = g_strconcat(list_str, " ", action_str, NULL);
1178         g_free(list_str);
1179         g_free(action_str);
1180
1181         return filtering_str;
1182 }
1183
1184 void prefs_filtering_write_config(void)
1185 {
1186         gchar *rcpath;
1187         PrefFile *pfile;
1188         GSList *cur;
1189         FilteringProp * prop;
1190
1191         debug_print(_("Writing filtering configuration...\n"));
1192
1193         rcpath = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, FILTERING_RC, NULL);
1194
1195         if ((pfile = prefs_write_open(rcpath)) == NULL) {
1196                 g_warning(_("failed to write configuration to file\n"));
1197                 g_free(rcpath);
1198                 return;
1199         }
1200
1201         for (cur = prefs_filtering; cur != NULL; cur = cur->next) {
1202                 gchar *filtering_str;
1203
1204                 prop = (FilteringProp *) cur->data;
1205                 filtering_str = filteringprop_to_string(prop);
1206                 if (fputs(filtering_str, pfile->fp) == EOF ||
1207                     fputc('\n', pfile->fp) == EOF) {
1208                         FILE_OP_ERROR(rcpath, "fputs || fputc");
1209                         prefs_write_close_revert(pfile);
1210                         g_free(rcpath);
1211                         g_free(filtering_str);
1212                         return;
1213                 }
1214                 g_free(filtering_str);
1215         }
1216
1217         g_free(rcpath);
1218
1219         if (prefs_write_close(pfile) < 0) {
1220                 g_warning(_("failed to write configuration to file\n"));
1221                 return;
1222         }
1223 }