2006-09-04 [colin] 2.4.0cvs143
[claws.git] / src / filtering.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #include "defs.h"
21 #include <glib.h>
22 #include <glib/gi18n.h>
23 #include <ctype.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <gtk/gtk.h>
28 #include <stdio.h>
29
30 #include "utils.h"
31 #include "procheader.h"
32 #include "matcher.h"
33 #include "filtering.h"
34 #include "prefs_gtk.h"
35 #include "compose.h"
36 #include "prefs_common.h"
37
38 #define PREFSBUFSIZE            1024
39
40 GSList * pre_global_processing = NULL;
41 GSList * post_global_processing = NULL;
42 GSList * filtering_rules = NULL;
43
44 static gboolean filtering_is_final_action(FilteringAction *filtering_action);
45
46 #define STRLEN_WITH_CHECK(expr) \
47         strlen_with_check(#expr, __LINE__, expr)
48                 
49 static inline gint strlen_with_check(const gchar *expr, gint fline, const gchar *str)
50 {
51         if (str) 
52                 return strlen(str);
53         else {
54                 debug_print("%s(%d) - invalid string %s\n", __FILE__, fline, expr);
55                 return 0;
56         }
57 }
58
59 FilteringAction * filteringaction_new(int type, int account_id,
60                                       gchar * destination,
61                                       gint labelcolor, gint score)
62 {
63         FilteringAction * action;
64
65         action = g_new0(FilteringAction, 1);
66
67         action->type = type;
68         action->account_id = account_id;
69         if (destination) {
70                 action->destination       = g_strdup(destination);
71         } else {
72                 action->destination       = NULL;
73         }
74         action->labelcolor = labelcolor;        
75         action->score = score;
76         return action;
77 }
78
79 void filteringaction_free(FilteringAction * action)
80 {
81         g_return_if_fail(action);
82         g_free(action->destination);
83         g_free(action);
84 }
85
86 FilteringProp * filteringprop_new(gboolean enabled,
87                                   const gchar *name,
88                                   gint account_id,
89                                   MatcherList * matchers,
90                                   GSList * action_list)
91 {
92         FilteringProp * filtering;
93
94         filtering = g_new0(FilteringProp, 1);
95         filtering->enabled = enabled;
96         filtering->name = name ? g_strdup(name): NULL;
97         filtering->account_id = account_id;
98         filtering->matchers = matchers;
99         filtering->action_list = action_list;
100
101         return filtering;
102 }
103
104 static FilteringAction * filteringaction_copy(FilteringAction * src)
105 {
106         FilteringAction * new;
107         
108         new = g_new0(FilteringAction, 1);
109         
110         new->type = src->type;
111         new->account_id = src->account_id;
112         if (src->destination)
113                 new->destination = g_strdup(src->destination);
114         else 
115                 new->destination = NULL;
116         new->labelcolor = src->labelcolor;
117         new->score = src->score;
118
119         return new;
120 }
121
122 FilteringProp * filteringprop_copy(FilteringProp *src)
123 {
124         FilteringProp * new;
125         GSList *tmp;
126         
127         new = g_new0(FilteringProp, 1);
128         new->matchers = g_new0(MatcherList, 1);
129
130         for (tmp = src->matchers->matchers; tmp != NULL && tmp->data != NULL;) {
131                 MatcherProp *matcher = (MatcherProp *)tmp->data;
132                 
133                 new->matchers->matchers = g_slist_append(new->matchers->matchers,
134                                                    matcherprop_copy(matcher));
135                 tmp = tmp->next;
136         }
137
138         new->matchers->bool_and = src->matchers->bool_and;
139
140         new->action_list = NULL;
141
142         for (tmp = src->action_list ; tmp != NULL ; tmp = tmp->next) {
143                 FilteringAction *filtering_action;
144                 
145                 filtering_action = tmp->data;
146                 
147                 new->action_list = g_slist_append(new->action_list,
148                     filteringaction_copy(filtering_action));
149         }
150
151         new->enabled = src->enabled;
152         new->name = g_strdup(src->name);
153
154         return new;
155 }
156
157 void filteringprop_free(FilteringProp * prop)
158 {
159         GSList * tmp;
160
161         g_return_if_fail(prop);
162         matcherlist_free(prop->matchers);
163         
164         for (tmp = prop->action_list ; tmp != NULL ; tmp = tmp->next) {
165                 filteringaction_free(tmp->data);
166         }
167         g_free(prop->name);
168         g_free(prop);
169 }
170
171 void filtering_move_and_copy_msg(MsgInfo *msginfo)
172 {
173         GSList *list = g_slist_append(NULL, msginfo);
174         filtering_move_and_copy_msgs(list);
175         g_slist_free(list);
176 }
177
178 /* move and copy messages by batches to be faster on IMAP */
179 void filtering_move_and_copy_msgs(GSList *msgs)
180 {
181         GSList *messages = g_slist_copy(msgs);
182         FolderItem *last_item = NULL;
183         gboolean is_copy = FALSE, is_move = FALSE;
184         
185         while (messages) {
186                 GSList *batch = NULL, *cur;
187                 gint found = 0;
188                 for (cur = messages; cur; cur = cur->next) {
189                         MsgInfo *info = (MsgInfo *)cur->data;
190                         if (last_item == NULL) {
191                                 last_item = info->to_filter_folder;
192                         }
193                         if (last_item == NULL)
194                                 continue;
195                         if (!is_copy && !is_move) {
196                                 if (info->is_copy)
197                                         is_copy = TRUE;
198                                 else if (info->is_move)
199                                         is_move = TRUE;
200                         }
201                         found++;
202                         if (info->to_filter_folder == last_item 
203                         &&  info->is_copy == is_copy
204                         &&  info->is_move == is_move) {
205                                 batch = g_slist_prepend(batch, info);
206                         }
207                 }
208                 if (found == 0) {
209                         debug_print("no more messages to move/copy\n");
210                         break;
211                 }
212                 for (cur = batch; cur; cur = cur->next) {
213                         MsgInfo *info = (MsgInfo *)cur->data;
214                         messages = g_slist_remove(messages, info);
215                 }
216                 batch = g_slist_reverse(batch);
217                 if (g_slist_length(batch)) {
218                         MsgInfo *info = (MsgInfo *)batch->data;
219                         if (is_copy && last_item != info->folder) {
220                                 folder_item_copy_msgs(last_item, batch);
221                         } else if (is_move && last_item != info->folder) {
222                                 if (folder_item_move_msgs(last_item, batch) < 0)
223                                         folder_item_move_msgs(
224                                                 folder_get_default_inbox(), 
225                                                 batch);
226                         }
227                         /* we don't reference the msginfos, because caller will do */
228                         g_slist_free(batch);
229                         batch = NULL;
230                 }
231                 last_item = NULL;
232                 is_copy = FALSE;
233                 is_move = FALSE;
234         }
235         /* we don't reference the msginfos, because caller will do */
236         g_slist_free(messages);
237 }
238
239 /*
240   fitleringaction_apply
241   runs the action on one MsgInfo
242   return value : return TRUE if the action could be applied
243 */
244
245 static gboolean filteringaction_apply(FilteringAction * action, MsgInfo * info)
246 {
247         FolderItem * dest_folder;
248         gint val;
249         Compose * compose;
250         PrefsAccount * account;
251         gchar * cmd;
252
253         switch(action->type) {
254         case MATCHACTION_MOVE:
255                 dest_folder =
256                         folder_find_item_from_identifier(action->destination);
257                 if (!dest_folder) {
258                         debug_print("*** folder not found '%s'\n",
259                                 action->destination ?action->destination :"");
260                         return FALSE;
261                 }
262                 
263                 /* check if mail is set to copy already, 
264                  * in which case we have to do it */
265                 if (info->is_copy && info->to_filter_folder) {
266                         debug_print("should cp and mv !\n");
267                         folder_item_copy_msg(info->to_filter_folder, info);
268                         info->is_copy = FALSE;
269                 }
270                 /* mark message to be moved */          
271                 info->is_move = TRUE;
272                 info->to_filter_folder = dest_folder;
273                 return TRUE;
274
275         case MATCHACTION_COPY:
276                 dest_folder =
277                         folder_find_item_from_identifier(action->destination);
278
279                 if (!dest_folder) {
280                         debug_print("*** folder not found '%s'\n",
281                                 action->destination ?action->destination :"");
282                         return FALSE;
283                 }
284
285                 /* check if mail is set to copy already, 
286                  * in which case we have to do it */
287                 if (info->is_copy && info->to_filter_folder) {
288                         debug_print("should cp and mv !\n");
289                         folder_item_copy_msg(info->to_filter_folder, info);
290                         info->is_copy = FALSE;
291                 }
292                 /* mark message to be copied */         
293                 info->is_copy = TRUE;
294                 info->to_filter_folder = dest_folder;
295                 return TRUE;
296
297         case MATCHACTION_DELETE:
298                 if (folder_item_remove_msg(info->folder, info->msgnum) == -1)
299                         return FALSE;
300                 return TRUE;
301
302         case MATCHACTION_MARK:
303                 procmsg_msginfo_set_flags(info, MSG_MARKED, 0);
304                 return TRUE;
305
306         case MATCHACTION_UNMARK:
307                 procmsg_msginfo_unset_flags(info, MSG_MARKED, 0);
308                 return TRUE;
309
310         case MATCHACTION_LOCK:
311                 procmsg_msginfo_set_flags(info, MSG_LOCKED, 0);
312                 return TRUE;
313
314         case MATCHACTION_UNLOCK:
315                 procmsg_msginfo_unset_flags(info, MSG_LOCKED, 0);       
316                 return TRUE;
317                 
318         case MATCHACTION_MARK_AS_READ:
319                 procmsg_msginfo_unset_flags(info, MSG_UNREAD | MSG_NEW, 0);
320                 return TRUE;
321
322         case MATCHACTION_MARK_AS_UNREAD:
323                 procmsg_msginfo_set_flags(info, MSG_UNREAD | MSG_NEW, 0);
324                 return TRUE;
325         
326         case MATCHACTION_COLOR:
327                 procmsg_msginfo_unset_flags(info, MSG_CLABEL_FLAG_MASK, 0); 
328                 procmsg_msginfo_set_flags(info, MSG_COLORLABEL_TO_FLAGS(action->labelcolor), 0);
329                 return TRUE;
330
331         case MATCHACTION_FORWARD:
332         case MATCHACTION_FORWARD_AS_ATTACHMENT:
333                 account = account_find_from_id(action->account_id);
334                 compose = compose_forward(account, info,
335                         action->type == MATCHACTION_FORWARD ? FALSE : TRUE,
336                         NULL, TRUE, TRUE);
337                 compose_entry_append(compose, action->destination,
338                                      compose->account->protocol == A_NNTP
339                                             ? COMPOSE_NEWSGROUPS
340                                             : COMPOSE_TO);
341
342                 val = compose_send(compose);
343
344                 return val == 0 ? TRUE : FALSE;
345
346         case MATCHACTION_REDIRECT:
347                 account = account_find_from_id(action->account_id);
348                 compose = compose_redirect(account, info, TRUE);
349                 if (compose->account->protocol == A_NNTP)
350                         break;
351                 else
352                         compose_entry_append(compose, action->destination,
353                                              COMPOSE_TO);
354
355                 val = compose_send(compose);
356                 
357                 return val == 0 ? TRUE : FALSE;
358
359         case MATCHACTION_EXECUTE:
360                 cmd = matching_build_command(action->destination, info);
361                 if (cmd == NULL)
362                         return FALSE;
363                 else {
364                         system(cmd);
365                         g_free(cmd);
366                 }
367                 return TRUE;
368
369         case MATCHACTION_SET_SCORE:
370                 info->score = action->score;
371                 return TRUE;
372
373         case MATCHACTION_CHANGE_SCORE:
374                 info->score += action->score;
375                 return TRUE;
376
377         case MATCHACTION_STOP:
378                 return FALSE;
379
380         case MATCHACTION_HIDE:
381                 info->hidden = TRUE;
382                 return TRUE;
383
384         case MATCHACTION_IGNORE:
385                 procmsg_msginfo_set_flags(info, MSG_IGNORE_THREAD, 0);
386                 return TRUE;
387
388         default:
389                 break;
390         }
391         return FALSE;
392 }
393
394 gboolean filteringaction_apply_action_list(GSList *action_list, MsgInfo *info)
395 {
396         GSList *p;
397         g_return_val_if_fail(action_list, FALSE);
398         g_return_val_if_fail(info, FALSE);
399         for (p = action_list; p && p->data; p = g_slist_next(p)) {
400                 FilteringAction *a = (FilteringAction *) p->data;
401                 if (filteringaction_apply(a, info)) {
402                         if (filtering_is_final_action(a))
403                                 break;
404                 } else
405                         return FALSE;
406                 
407         }
408         return TRUE;
409 }
410
411 static gboolean filtering_match_condition(FilteringProp *filtering, MsgInfo *info,
412                                                         PrefsAccount *ac_prefs)
413 {
414         gboolean matches = FALSE;
415
416         if (ac_prefs != NULL) {
417                 matches = ((filtering->account_id == 0)
418                                         || (filtering->account_id == ac_prefs->account_id));
419         } else {
420                 switch (prefs_common.apply_per_account_filtering_rules) {
421                 case FILTERING_ACCOUNT_RULES_FORCE:
422                         /* apply filtering rules regardless to the account info */
423                         matches = TRUE;
424                         break;
425                 case FILTERING_ACCOUNT_RULES_SKIP:
426                         /* don't apply filtering rules that belong to an account */
427                         matches = (filtering->account_id == 0);
428                         break;
429                 case FILTERING_ACCOUNT_RULES_USE_CURRENT:
430                         matches = ((filtering->account_id == 0)
431                                         || (filtering->account_id == cur_account->account_id));
432                         break;
433                 }
434         }
435
436         return matches && matcherlist_match(filtering->matchers, info);
437 }
438
439 /*!
440  *\brief        Apply a rule on message.
441  *
442  *\param        filtering List of filtering rules.
443  *\param        info Message to apply rules on.
444  *\param        final Variable returning TRUE or FALSE if one of the
445  *              encountered actions was final. 
446  *              See also \ref filtering_is_final_action.
447  *
448  *\return       gboolean TRUE to continue applying rules.
449  */
450 static gboolean filtering_apply_rule(FilteringProp *filtering, MsgInfo *info,
451     gboolean * final)
452 {
453         gboolean result = TRUE;
454         gchar    buf[50];
455         GSList * tmp;
456         
457         * final = FALSE;
458         for (tmp = filtering->action_list ; tmp != NULL ; tmp = tmp->next) {
459                 FilteringAction * action;
460                 
461                 action = tmp->data;
462                 
463                 if (FALSE == (result = filteringaction_apply(action, info))) {
464                         g_warning("No further processing after rule %s\n",
465                             filteringaction_to_string(buf, sizeof buf, action));
466                 }
467                 
468                 if (filtering_is_final_action(action)) {
469                         * final = TRUE;
470                         break;
471                 }
472         }
473         return result;
474 }
475
476 /*!
477  *\brief        Check if an action is "final", i.e. should break further
478  *              processing.
479  *
480  *\param        filtering_action Action to check.
481  *
482  *\return       gboolean TRUE if \a filtering_action is final.  
483  */
484 static gboolean filtering_is_final_action(FilteringAction *filtering_action)
485 {
486         switch(filtering_action->type) {
487         case MATCHACTION_MOVE:
488         case MATCHACTION_DELETE:
489         case MATCHACTION_STOP:
490                 return TRUE; /* MsgInfo invalid for message */
491         default:
492                 return FALSE;
493         }
494 }
495
496 static gboolean filter_msginfo(GSList * filtering_list, MsgInfo * info, PrefsAccount* ac_prefs)
497 {
498         GSList  *l;
499         gboolean final;
500         gboolean apply_next;
501         
502         g_return_val_if_fail(info != NULL, TRUE);
503         
504         for (l = filtering_list, final = FALSE, apply_next = FALSE; l != NULL; l = g_slist_next(l)) {
505                 FilteringProp * filtering = (FilteringProp *) l->data;
506
507                 if (filtering->enabled && filtering_match_condition(filtering, info, ac_prefs)) {
508                         apply_next = filtering_apply_rule(filtering, info, &final);
509                         if (final)
510                                 break;
511                 }               
512         }
513
514         /* put in inbox if a final rule could not be applied, or
515          * the last rule was not a final one. */
516         if ((final && !apply_next) || !final) {
517                 return FALSE;
518         }
519
520         return TRUE;
521 }
522
523 /*!
524  *\brief        Filter a message against a list of rules.
525  *
526  *\param        flist List of filter rules.
527  *\param        info Message.
528  *
529  *\return       gboolean TRUE if filter rules handled the message.
530  *
531  *\note         Returning FALSE means the message was not handled,
532  *              and that the calling code should do the default
533  *              processing. E.g. \ref inc.c::inc_start moves the 
534  *              message to the inbox.   
535  */
536 gboolean filter_message_by_msginfo(GSList *flist, MsgInfo *info, PrefsAccount* ac_prefs)
537 {
538         return filter_msginfo(flist, info, ac_prefs);
539 }
540
541 gchar *filteringaction_to_string(gchar *dest, gint destlen, FilteringAction *action)
542 {
543         const gchar *command_str;
544         gchar * quoted_dest;
545         
546         command_str = get_matchparser_tab_str(action->type);
547
548         if (command_str == NULL)
549                 return NULL;
550
551         switch(action->type) {
552         case MATCHACTION_MOVE:
553         case MATCHACTION_COPY:
554         case MATCHACTION_EXECUTE:
555                 quoted_dest = matcher_quote_str(action->destination);
556                 g_snprintf(dest, destlen, "%s \"%s\"", command_str, quoted_dest);
557                 g_free(quoted_dest);
558                 return dest;
559
560         case MATCHACTION_DELETE:
561         case MATCHACTION_MARK:
562         case MATCHACTION_UNMARK:
563         case MATCHACTION_LOCK:
564         case MATCHACTION_UNLOCK:
565         case MATCHACTION_MARK_AS_READ:
566         case MATCHACTION_MARK_AS_UNREAD:
567         case MATCHACTION_STOP:
568         case MATCHACTION_HIDE:
569         case MATCHACTION_IGNORE:
570                 g_snprintf(dest, destlen, "%s", command_str);
571                 return dest;
572
573         case MATCHACTION_REDIRECT:
574         case MATCHACTION_FORWARD:
575         case MATCHACTION_FORWARD_AS_ATTACHMENT:
576                 quoted_dest = matcher_quote_str(action->destination);
577                 g_snprintf(dest, destlen, "%s %d \"%s\"", command_str, action->account_id, quoted_dest);
578                 g_free(quoted_dest);
579                 return dest; 
580
581         case MATCHACTION_COLOR:
582                 g_snprintf(dest, destlen, "%s %d", command_str, action->labelcolor);
583                 return dest;  
584
585         case MATCHACTION_CHANGE_SCORE:
586         case MATCHACTION_SET_SCORE:
587                 g_snprintf(dest, destlen, "%s %d", command_str, action->score);
588                 return dest;  
589
590         default:
591                 return NULL;
592         }
593 }
594
595 gchar * filteringaction_list_to_string(GSList * action_list)
596 {
597         gchar *action_list_str;
598         gchar  buf[256];
599         GSList * tmp;
600         gchar *list_str;
601
602         action_list_str = NULL;
603         for (tmp = action_list ; tmp != NULL ; tmp = tmp->next) {
604                 gchar *action_str;
605                 FilteringAction * action;
606                 
607                 action = tmp->data;
608                 
609                 action_str = filteringaction_to_string(buf,
610                     sizeof buf, action);
611                 
612                 if (action_list_str != NULL) {
613                         list_str = g_strconcat(action_list_str, " ", action_str, NULL);
614                         g_free(action_list_str);
615                 }
616                 else {
617                         list_str = g_strdup(action_str);
618                 }
619                 action_list_str = list_str;
620         }
621
622         return action_list_str;
623 }
624
625 gchar * filteringprop_to_string(FilteringProp * prop)
626 {
627         gchar *list_str;
628         gchar *action_list_str;
629         gchar *filtering_str;
630
631         action_list_str = filteringaction_list_to_string(prop->action_list);
632
633         if (action_list_str == NULL)
634                 return NULL;
635
636         list_str = matcherlist_to_string(prop->matchers);
637
638         if (list_str == NULL) {
639                 g_free(action_list_str);
640                 return NULL;
641         }
642
643         filtering_str = g_strconcat(list_str, " ", action_list_str, NULL);
644         g_free(action_list_str);
645         g_free(list_str);
646
647         return filtering_str;
648 }
649
650 void prefs_filtering_free(GSList * prefs_filtering)
651 {
652         while (prefs_filtering != NULL) {
653                 FilteringProp * filtering = (FilteringProp *)
654                         prefs_filtering->data;
655                 filteringprop_free(filtering);
656                 prefs_filtering = g_slist_remove(prefs_filtering, filtering);
657         }
658 }
659
660 static gboolean prefs_filtering_free_func(GNode *node, gpointer data)
661 {
662         FolderItem *item = node->data;
663
664         g_return_val_if_fail(item, FALSE);
665         g_return_val_if_fail(item->prefs, FALSE);
666
667         prefs_filtering_free(item->prefs->processing);
668         item->prefs->processing = NULL;
669
670         return FALSE;
671 }
672
673 void prefs_filtering_clear(void)
674 {
675         GList * cur;
676
677         for (cur = folder_get_list() ; cur != NULL ; cur = g_list_next(cur)) {
678                 Folder *folder;
679
680                 folder = (Folder *) cur->data;
681                 g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
682                                 prefs_filtering_free_func, NULL);
683         }
684
685         prefs_filtering_free(filtering_rules);
686         filtering_rules = NULL;
687         prefs_filtering_free(pre_global_processing);
688         pre_global_processing = NULL;
689         prefs_filtering_free(post_global_processing);
690         post_global_processing = NULL;
691 }
692
693 void prefs_filtering_clear_folder(Folder *folder)
694 {
695         g_return_if_fail(folder);
696         g_return_if_fail(folder->node);
697
698         g_node_traverse(folder->node, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
699                         prefs_filtering_free_func, NULL);
700         /* FIXME: Note folder settings were changed, where the updates? */
701 }
702
703 gboolean filtering_peek_per_account_rules(GSList *filtering_list)
704 /* return TRUE if there's at least one per-account filtering rule */
705 {
706         GSList *l;
707
708         for (l = filtering_list; l != NULL; l = g_slist_next(l)) {
709                 FilteringProp * filtering = (FilteringProp *) l->data;
710
711                 if (filtering->enabled && (filtering->account_id != 0)) {
712                         return TRUE;
713                 }               
714         }
715
716         return FALSE;
717 }