(spam-verify-bogofilter): new function
[gnus] / lisp / spam.el
1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: network
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; This module addresses a few aspects of spam control under Gnus.  Page
27 ;;; breaks are used for grouping declarations and documentation relating to
28 ;;; each particular aspect.
29
30 ;;; The integration with Gnus is not yet complete.  See various `FIXME'
31 ;;; comments, below, for supplementary explanations or discussions.
32
33 ;;; Several TODO items are marked as such
34
35 ;; TODO: cross-server splitting, remote processing, training through files
36
37 ;;; Code:
38
39 ;;{{{ compilation directives and autoloads/requires
40
41 (eval-when-compile (require 'cl))
42 (eval-when-compile (require 'spam-report))
43
44 (require 'gnus-sum)
45
46 (require 'gnus-uu)                      ; because of key prefix issues
47 ;;; for the definitions of group content classification and spam processors
48 (require 'gnus)
49 (require 'message)              ;for the message-fetch-field functions
50
51 ;; for nnimap-split-download-body-default
52 (eval-when-compile (require 'nnimap))
53
54 ;; autoload query-dig
55 (eval-and-compile
56   (autoload 'query-dig "dig"))
57
58 ;; autoload spam-report
59 (eval-and-compile
60   (autoload 'spam-report-gmane "spam-report")
61   (autoload 'spam-report-resend "spam-report"))
62
63 ;; autoload gnus-registry
64 (eval-and-compile
65   (autoload 'gnus-registry-group-count "gnus-registry")
66   (autoload 'gnus-registry-add-group "gnus-registry")
67   (autoload 'gnus-registry-store-extra-entry "gnus-registry")
68   (autoload 'gnus-registry-fetch-extra "gnus-registry"))
69
70 ;; autoload query-dns
71 (eval-and-compile
72   (autoload 'query-dns "dns"))
73
74 ;;}}}
75
76 ;;{{{ Main parameters.
77 (defvar spam-backends nil
78   "List of spam.el backends with all the pertinent data.
79 Populated by spam-install-backend-super.")
80
81 (defgroup spam nil
82   "Spam configuration.")
83
84 (defcustom spam-summary-exit-behavior 'default
85   "Exit behavior at the time of summary exit.
86 Note that setting the spam-use-move or spam-use-copy backends on
87 a group through group/topic parameters overrides this mechanism."
88   :type '(choice (const 'default :tag 
89                         "Move spam out of all groups.  Move ham out of spam groups.")
90                  (const 'move-all :tag 
91                         "Move spam out of all groups.  Move ham out of all groups.")
92                  (const 'move-none :tag 
93                         "Never move spam or ham out of any groups."))
94   :group 'spam)
95
96 (defcustom spam-directory (nnheader-concat gnus-directory "spam/")
97   "Directory for spam whitelists and blacklists."
98   :type 'directory
99   :group 'spam)
100
101 (defcustom spam-mark-new-messages-in-spam-group-as-spam t
102   "Whether new messages in a spam group should get the spam-mark."
103   :type 'boolean
104   :group 'spam)
105
106 (defcustom spam-log-to-registry nil
107   "Whether spam/ham processing should be logged in the registry."
108   :type 'boolean
109   :group 'spam)
110
111 (defcustom spam-split-symbolic-return nil
112   "Whether `spam-split' should work with symbols or group names."
113   :type 'boolean
114   :group 'spam)
115
116 (defcustom spam-split-symbolic-return-positive nil
117   "Whether `spam-split' should ALWAYS work with symbols or group names.
118 Do not set this if you use `spam-split' in a fancy split
119   method."
120   :type 'boolean
121   :group 'spam)
122
123 (defcustom spam-mark-only-unseen-as-spam t
124   "Whether only unseen articles should be marked as spam in spam groups.
125 When nil, all unread articles in a spam group are marked as
126 spam.  Set this if you want to leave an article unread in a spam group
127 without losing it to the automatic spam-marking process."
128   :type 'boolean
129   :group 'spam)
130
131 (defcustom spam-mark-ham-unread-before-move-from-spam-group nil
132   "Whether ham should be marked unread before it's moved.
133 The article is moved out of a spam group according to ham-process-destination.
134 This variable is an official entry in the international Longest Variable Name
135 Competition."
136   :type 'boolean
137   :group 'spam)
138
139 (defcustom spam-disable-spam-split-during-ham-respool nil
140   "Whether `spam-split' should be ignored while resplitting ham.
141 This is useful to prevent ham from ending up in the same spam
142 group after the resplit.  Don't set this to t if you have `spam-split' as the
143 last rule in your split configuration."
144   :type 'boolean
145   :group 'spam)
146
147 (defcustom spam-autodetect-recheck-messages nil
148   "Should spam.el recheck all meessages when autodetecting?
149 Normally this is nil, so only unseen messages will be checked."
150   :type 'boolean
151   :group 'spam)
152
153 (defcustom spam-whitelist (expand-file-name "whitelist" spam-directory)
154   "The location of the whitelist.
155 The file format is one regular expression per line.
156 The regular expression is matched against the address."
157   :type 'file
158   :group 'spam)
159
160 (defcustom spam-blacklist (expand-file-name "blacklist" spam-directory)
161   "The location of the blacklist.
162 The file format is one regular expression per line.
163 The regular expression is matched against the address."
164   :type 'file
165   :group 'spam)
166
167 (defcustom spam-use-dig t
168   "Whether `query-dig' should be used instead of `query-dns'."
169   :type 'boolean
170   :group 'spam)
171
172 (defcustom spam-use-gmane-xref nil
173   "Whether the Gmane spam xref should be used by `spam-split'."
174   :type 'boolean
175   :group 'spam)
176
177 (defcustom spam-use-blacklist nil
178   "Whether the blacklist should be used by `spam-split'."
179   :type 'boolean
180   :group 'spam)
181
182 (defcustom spam-blacklist-ignored-regexes nil
183   "Regular expressions that the blacklist should ignore."
184   :type '(repeat (regexp :tag "Regular expression to ignore when blacklisting"))
185   :group 'spam)
186
187 (defcustom spam-use-whitelist nil
188   "Whether the whitelist should be used by `spam-split'."
189   :type 'boolean
190   :group 'spam)
191
192 (defcustom spam-use-whitelist-exclusive nil
193   "Whether whitelist-exclusive should be used by `spam-split'.
194 Exclusive whitelisting means that all messages from senders not in the whitelist
195 are considered spam."
196   :type 'boolean
197   :group 'spam)
198
199 (defcustom spam-use-blackholes nil
200   "Whether blackholes should be used by `spam-split'."
201   :type 'boolean
202   :group 'spam)
203
204 (defcustom spam-use-hashcash nil
205   "Whether hashcash payments should be detected by `spam-split'."
206   :type 'boolean
207   :group 'spam)
208
209 (defcustom spam-use-regex-headers nil
210   "Whether a header regular expression match should be used by `spam-split'.
211 Also see the variables `spam-regex-headers-spam' and `spam-regex-headers-ham'."
212   :type 'boolean
213   :group 'spam)
214
215 (defcustom spam-use-regex-body nil
216   "Whether a body regular expression match should be used by `spam-split'.
217 Also see the variables `spam-regex-body-spam' and `spam-regex-body-ham'."
218   :type 'boolean
219   :group 'spam)
220
221 (defcustom spam-use-bogofilter-headers nil
222   "Whether bogofilter headers should be used by `spam-split'.
223 Enable this if you pre-process messages with Bogofilter BEFORE Gnus sees them."
224   :type 'boolean
225   :group 'spam)
226
227 (defcustom spam-use-bogofilter nil
228   "Whether bogofilter should be invoked by `spam-split'.
229 Enable this if you want Gnus to invoke Bogofilter on new messages."
230   :type 'boolean
231   :group 'spam)
232
233 (defcustom spam-use-bsfilter-headers nil
234   "Whether bsfilter headers should be used by `spam-split'.
235 Enable this if you pre-process messages with Bsfilter BEFORE Gnus sees them."
236   :type 'boolean
237   :group 'spam)
238
239 (defcustom spam-use-bsfilter nil
240   "Whether bsfilter should be invoked by `spam-split'.
241 Enable this if you want Gnus to invoke Bsfilter on new messages."
242   :type 'boolean
243   :group 'spam)
244
245 (defcustom spam-use-BBDB nil
246   "Whether BBDB should be used by `spam-split'."
247   :type 'boolean
248   :group 'spam)
249
250 (defcustom spam-use-BBDB-exclusive nil
251   "Whether BBDB-exclusive should be used by `spam-split'.
252 Exclusive BBDB means that all messages from senders not in the BBDB are
253 considered spam."
254   :type 'boolean
255   :group 'spam)
256
257 (defcustom spam-use-ifile nil
258   "Whether ifile should be used by `spam-split'."
259   :type 'boolean
260   :group 'spam)
261
262 (defcustom spam-use-stat nil
263   "Whether `spam-stat' should be used by `spam-split'."
264   :type 'boolean
265   :group 'spam)
266
267 (defcustom spam-use-spamoracle nil
268   "Whether spamoracle should be used by `spam-split'."
269   :type 'boolean
270   :group 'spam)
271
272 (defcustom spam-use-spamassassin nil
273   "Whether spamassassin should be invoked by `spam-split'.
274 Enable this if you want Gnus to invoke SpamAssassin on new messages."
275   :type 'boolean
276   :group 'spam)
277
278 (defcustom spam-use-spamassassin-headers nil
279   "Whether spamassassin headers should be checked by `spam-split'.
280 Enable this if you pre-process messages with SpamAssassin BEFORE Gnus sees
281 them."
282   :type 'boolean
283   :group 'spam)
284
285 (defcustom spam-use-crm114 nil
286   "Whether the CRM114 Mailfilter should be used by `spam-split'."
287   :type 'boolean
288   :group 'spam)
289
290 (defcustom spam-install-hooks (or
291                                spam-use-dig
292                                spam-use-gmane-xref
293                                spam-use-blacklist
294                                spam-use-whitelist
295                                spam-use-whitelist-exclusive
296                                spam-use-blackholes
297                                spam-use-hashcash
298                                spam-use-regex-headers
299                                spam-use-regex-body
300                                spam-use-bogofilter
301                                spam-use-bogofilter-headers
302                                spam-use-spamassassin
303                                spam-use-spamassassin-headers
304                                spam-use-bsfilter
305                                spam-use-bsfilter-headers
306                                spam-use-BBDB
307                                spam-use-BBDB-exclusive
308                                spam-use-ifile
309                                spam-use-stat
310                                spam-use-spamoracle
311                                spam-use-crm114)
312   "Whether the spam hooks should be installed.
313 Default to t if one of the spam-use-* variables is set."
314   :group 'spam
315   :type 'boolean)
316
317 (defcustom spam-split-group "spam"
318   "Group name where incoming spam should be put by `spam-split'."
319   :type 'string
320   :group 'spam)
321
322 ;;; TODO: deprecate this variable, it's confusing since it's a list of strings,
323 ;;; not regular expressions
324 (defcustom spam-junk-mailgroups (cons
325                                  spam-split-group
326                                  '("mail.junk" "poste.pourriel"))
327   "Mailgroups with spam contents.
328 All unmarked article in such group receive the spam mark on group entry."
329   :type '(repeat (string :tag "Group"))
330   :group 'spam)
331
332
333 (defcustom spam-gmane-xref-spam-group "gmane.spam.detected"
334   "The group where spam xrefs can be found on Gmane.
335 Only meaningful if you enable `spam-use-gmane-xref'."
336   :type 'string
337   :group 'spam)
338
339 (defcustom spam-blackhole-servers '("bl.spamcop.net" "relays.ordb.org"
340                                     "dev.null.dk" "relays.visi.com")
341   "List of blackhole servers.
342 Only meaningful if you enable `spam-use-blackholes'."
343   :type '(repeat (string :tag "Server"))
344   :group 'spam)
345
346 (defcustom spam-blackhole-good-server-regex nil
347   "String matching IP addresses that should not be checked in the blackholes.
348 Only meaningful if you enable `spam-use-blackholes'."
349   :type '(radio (const nil)
350                 (regexp :format "%t: %v\n" :size 0))
351   :group 'spam)
352
353 (defcustom spam-face 'gnus-splash-face
354   "Face for spam-marked articles."
355   :type 'face
356   :group 'spam)
357
358 (defcustom spam-regex-headers-spam '("^X-Spam-Flag: YES")
359   "Regular expression for positive header spam matches.
360 Only meaningful if you enable `spam-use-regex-headers'."
361   :type '(repeat (regexp :tag "Regular expression to match spam header"))
362   :group 'spam)
363
364 (defcustom spam-regex-headers-ham '("^X-Spam-Flag: NO")
365   "Regular expression for positive header ham matches.
366 Only meaningful if you enable `spam-use-regex-headers'."
367   :type '(repeat (regexp :tag "Regular expression to match ham header"))
368   :group 'spam)
369
370 (defcustom spam-regex-body-spam '()
371   "Regular expression for positive body spam matches.
372 Only meaningful if you enable `spam-use-regex-body'."
373   :type '(repeat (regexp :tag "Regular expression to match spam body"))
374   :group 'spam)
375
376 (defcustom spam-regex-body-ham '()
377   "Regular expression for positive body ham matches.
378 Only meaningful if you enable `spam-use-regex-body'."
379   :type '(repeat (regexp :tag "Regular expression to match ham body"))
380   :group 'spam)
381
382 (defgroup spam-ifile nil
383   "Spam ifile configuration."
384   :group 'spam)
385
386 (defcustom spam-ifile-path (executable-find "ifile")
387   "File path of the ifile executable program."
388   :type '(choice (file :tag "Location of ifile")
389                  (const :tag "ifile is not installed"))
390   :group 'spam-ifile)
391
392 (defcustom spam-ifile-database-path nil
393   "File path of the ifile database."
394   :type '(choice (file :tag "Location of the ifile database")
395                  (const :tag "Use the default"))
396   :group 'spam-ifile)
397
398 (defcustom spam-ifile-spam-category "spam"
399   "Name of the spam ifile category."
400   :type 'string
401   :group 'spam-ifile)
402
403 (defcustom spam-ifile-ham-category nil
404   "Name of the ham ifile category.
405 If nil, the current group name will be used."
406   :type '(choice (string :tag "Use a fixed category")
407                  (const :tag "Use the current group name"))
408   :group 'spam-ifile)
409
410 (defcustom spam-ifile-all-categories nil
411   "Whether the ifile check will return all categories, or just spam.
412 Set this to t if you want to use the `spam-split' invocation of ifile as
413 your main source of newsgroup names."
414   :type 'boolean
415   :group 'spam-ifile)
416
417 (defgroup spam-bogofilter nil
418   "Spam bogofilter configuration."
419   :group 'spam)
420
421 (defcustom spam-bogofilter-path (executable-find "bogofilter")
422   "File path of the Bogofilter executable program."
423   :type '(choice (file :tag "Location of bogofilter")
424                  (const :tag "Bogofilter is not installed"))
425   :group 'spam-bogofilter)
426
427 (defcustom spam-bogofilter-header "X-Bogosity"
428   "The header that Bogofilter inserts in messages."
429   :type 'string
430   :group 'spam-bogofilter)
431
432 (defcustom spam-bogofilter-spam-switch "-s"
433   "The switch that Bogofilter uses to register spam messages."
434   :type 'string
435   :group 'spam-bogofilter)
436
437 (defcustom spam-bogofilter-ham-switch "-n"
438   "The switch that Bogofilter uses to register ham messages."
439   :type 'string
440   :group 'spam-bogofilter)
441
442 (defcustom spam-bogofilter-spam-strong-switch "-S"
443   "The switch that Bogofilter uses to unregister ham messages."
444   :type 'string
445   :group 'spam-bogofilter)
446
447 (defcustom spam-bogofilter-ham-strong-switch "-N"
448   "The switch that Bogofilter uses to unregister spam messages."
449   :type 'string
450   :group 'spam-bogofilter)
451
452 (defcustom spam-bogofilter-bogosity-positive-spam-header "^\\(Yes\\|Spam\\)"
453   "The regex on `spam-bogofilter-header' for positive spam identification."
454   :type 'regexp
455   :group 'spam-bogofilter)
456
457 (defcustom spam-bogofilter-database-directory nil
458   "Directory path of the Bogofilter databases."
459   :type '(choice (directory
460                   :tag "Location of the Bogofilter database directory")
461                  (const :tag "Use the default"))
462   :group 'spam-bogofilter)
463
464 (defgroup spam-bsfilter nil
465   "Spam bsfilter configuration."
466   :group 'spam)
467
468 (defcustom spam-bsfilter-path (executable-find "bsfilter")
469   "File path of the Bsfilter executable program."
470   :type '(choice (file :tag "Location of bsfilter")
471                  (const :tag "Bsfilter is not installed"))
472   :group 'spam-bsfilter)
473
474 (defcustom spam-bsfilter-header "X-Spam-Flag"
475   "The header inserted by Bsfilter to flag spam."
476   :type 'string
477   :group 'spam-bsfilter)
478
479 (defcustom spam-bsfilter-probability-header "X-Spam-Probability"
480   "The header that Bsfilter inserts in messages."
481   :type 'string
482   :group 'spam-bsfilter)
483
484 (defcustom spam-bsfilter-spam-switch "--add-spam"
485   "The switch that Bsfilter uses to register spam messages."
486   :type 'string
487   :group 'spam-bsfilter)
488
489 (defcustom spam-bsfilter-ham-switch "--add-ham"
490   "The switch that Bsfilter uses to register ham messages."
491   :type 'string
492   :group 'spam-bsfilter)
493
494 (defcustom spam-bsfilter-spam-strong-switch "--sub-spam"
495   "The switch that Bsfilter uses to unregister ham messages."
496   :type 'string
497   :group 'spam-bsfilter)
498
499 (defcustom spam-bsfilter-ham-strong-switch "--sub-clean"
500   "The switch that Bsfilter uses to unregister spam messages."
501   :type 'string
502   :group 'spam-bsfilter)
503
504 (defcustom spam-bsfilter-database-directory nil
505   "Directory path of the Bsfilter databases."
506   :type '(choice (directory
507                   :tag "Location of the Bsfilter database directory")
508                  (const :tag "Use the default"))
509   :group 'spam-bsfilter)
510
511 (defgroup spam-spamoracle nil
512   "Spam spamoracle configuration."
513   :group 'spam)
514
515 (defcustom spam-spamoracle-database nil
516   "Location of spamoracle database file.
517 When nil, use the default spamoracle database."
518   :type '(choice (directory :tag "Location of spamoracle database file.")
519                  (const :tag "Use the default"))
520   :group 'spam-spamoracle)
521
522 (defcustom spam-spamoracle-binary (executable-find "spamoracle")
523   "Location of the spamoracle binary."
524   :type '(choice (directory :tag "Location of the spamoracle binary")
525                  (const :tag "Use the default"))
526   :group 'spam-spamoracle)
527
528 (defgroup spam-spamassassin nil
529   "Spam SpamAssassin configuration."
530   :group 'spam)
531
532 (defcustom spam-spamassassin-path (executable-find "spamassassin")
533   "File path of the spamassassin executable program.
534 Hint: set this to \"spamc\" if you have spamd running.  See the spamc and
535 spamd man pages for more information on these programs."
536   :type '(choice (file :tag "Location of spamc")
537                  (const :tag "spamassassin is not installed"))
538   :group 'spam-spamassassin)
539
540 (defcustom spam-spamassassin-arguments ()
541   "Arguments to pass to the spamassassin executable.
542 This must be a list.  For example, `(\"-C\" \"configfile\")'."
543   :type '(restricted-sexp :match-alternatives (listp))
544   :group 'spam-spamassassin)
545
546 (defcustom spam-spamassassin-spam-flag-header "X-Spam-Flag"
547   "The header inserted by SpamAssassin to flag spam."
548   :type 'string
549   :group 'spam-spamassassin)
550
551 (defcustom spam-spamassassin-positive-spam-flag-header "YES"
552   "The regex on `spam-spamassassin-spam-flag-header' for positive spam
553 identification"
554   :type 'string
555   :group 'spam-spamassassin)
556
557 (defcustom spam-spamassassin-spam-status-header "X-Spam-Status"
558   "The header inserted by SpamAssassin, giving extended scoring information"
559   :type 'string
560   :group 'spam-spamassassin)
561
562 (defcustom spam-sa-learn-path (executable-find "sa-learn")
563   "File path of the sa-learn executable program."
564   :type '(choice (file :tag "Location of spamassassin")
565                  (const :tag "spamassassin is not installed"))
566   :group 'spam-spamassassin)
567
568 (defcustom spam-sa-learn-rebuild t
569   "Whether sa-learn should rebuild the database every time it is called
570 Enable this if you want sa-learn to rebuild the database automatically.  Doing
571 this will slightly increase the running time of the spam registration process.
572 If you choose not to do this, you will have to run \"sa-learn --rebuild\" in
573 order for SpamAssassin to recognize the new registered spam."
574   :type 'boolean
575   :group 'spam-spamassassin)
576
577 (defcustom spam-sa-learn-spam-switch "--spam"
578   "The switch that sa-learn uses to register spam messages"
579   :type 'string
580   :group 'spam-spamassassin)
581
582 (defcustom spam-sa-learn-ham-switch "--ham"
583   "The switch that sa-learn uses to register ham messages"
584   :type 'string
585   :group 'spam-spamassassin)
586
587 (defcustom spam-sa-learn-unregister-switch "--forget"
588   "The switch that sa-learn uses to unregister messages messages"
589   :type 'string
590   :group 'spam-spamassassin)
591
592 (defgroup spam-crm114 nil
593   "Spam CRM114 Mailfilter configuration."
594   :group 'spam)
595
596 (defcustom spam-crm114-program (executable-find "mailfilter.crm")
597   "File path of the CRM114 Mailfilter executable program."
598   :type '(choice (file :tag "Location of CRM114 Mailfilter")
599          (const :tag "CRM114 Mailfilter is not installed"))
600   :group 'spam-crm114)
601
602 (defcustom spam-crm114-header "X-CRM114-Status"
603   "The header that CRM114 Mailfilter inserts in messages."
604   :type 'string
605   :group 'spam-crm114)
606
607 (defcustom spam-crm114-spam-switch "--learnspam"
608   "The switch that CRM114 Mailfilter uses to register spam messages."
609   :type 'string
610   :group 'spam-crm114)
611
612 (defcustom spam-crm114-ham-switch "--learnnonspam"
613   "The switch that CRM114 Mailfilter uses to register ham messages."
614   :type 'string
615   :group 'spam-crm114)
616
617 (defcustom spam-crm114-spam-strong-switch "--UNKNOWN"
618   "The switch that CRM114 Mailfilter uses to unregister ham messages."
619   :type 'string
620   :group 'spam-crm114)
621
622 (defcustom spam-crm114-ham-strong-switch "--UNKNOWN"
623   "The switch that CRM114 Mailfilter uses to unregister spam messages."
624   :type 'string
625   :group 'spam-crm114)
626
627 (defcustom spam-crm114-positive-spam-header "^SPAM"
628   "The regex on `spam-crm114-header' for positive spam identification."
629   :type 'regexp
630   :group 'spam-crm114)
631
632 (defcustom spam-crm114-database-directory nil
633   "Directory path of the CRM114 Mailfilter databases."
634   :type '(choice (directory
635           :tag "Location of the CRM114 Mailfilter database directory")
636          (const :tag "Use the default"))
637   :group 'spam-crm114)
638
639 ;;; Key bindings for spam control.
640
641 (gnus-define-keys gnus-summary-mode-map
642   "St" spam-generic-score
643   "Sx" gnus-summary-mark-as-spam
644   "Mst" spam-generic-score
645   "Msx" gnus-summary-mark-as-spam
646   "\M-d" gnus-summary-mark-as-spam)
647
648 (defvar spam-cache-lookups t
649   "Whether spam.el will try to cache lookups using `spam-caches'.")
650
651 (defvar spam-caches (make-hash-table
652                      :size 10
653                      :test 'equal)
654   "Cache of spam detection entries.")
655
656 (defvar spam-old-articles nil
657   "List of old ham and spam articles, generated when a group is entered.")
658
659 (defvar spam-split-disabled nil
660   "If non-nil, `spam-split' is disabled, and always returns nil.")
661
662 (defvar spam-split-last-successful-check nil
663   "Internal variable.
664 `spam-split' will set this to nil or a spam-use-XYZ check if it
665 finds ham or spam.")
666
667 ;; internal variables for backends
668 ;; TODO: find a way to create these on the fly in spam-install-backend-super
669 (defvar spam-use-copy nil)
670 (defvar spam-use-move nil)
671 (defvar spam-use-gmane nil)
672 (defvar spam-use-resend nil)
673
674 ;;}}}
675
676 ;;{{{ convenience functions
677
678 (defun spam-clear-cache (symbol)
679   "Clear the spam-caches entry for a check."
680   (remhash symbol spam-caches))
681
682 (defun spam-xor (a b)
683   "Logical A xor B."
684   (and (or a b) (not (and a b))))
685
686 (defun spam-set-difference (list1 list2)
687   "Return a set difference of LIST1 and LIST2.  
688 When either list is nil, the other is returned."
689   (if (and list1 list2)
690       ;; we have two non-nil lists
691       (progn
692         (dolist (item (append list1 list2))
693           (when (and (memq item list1) (memq item list2))
694             (setq list1 (delq item list1))
695             (setq list2 (delq item list2))))
696         (append list1 list2))
697     ;; if either of the lists was nil, return the other one
698     (if list1 list1 list2)))
699
700 (defun spam-group-ham-mark-p (group mark &optional spam)
701   "Checks if MARK is considered a ham mark in GROUP."
702   (when (stringp group)
703     (let* ((marks (spam-group-ham-marks group spam))
704            (marks (if (symbolp mark)
705                       marks
706                     (mapcar 'symbol-value marks))))
707       (memq mark marks))))
708
709 (defun spam-group-spam-mark-p (group mark)
710   "Checks if MARK is considered a spam mark in GROUP."
711   (spam-group-ham-mark-p group mark t))
712
713 (defun spam-group-ham-marks (group &optional spam)
714   "In GROUP, get all the ham marks."
715   (when (stringp group)
716     (let* ((marks (if spam
717                       (gnus-parameter-spam-marks group)
718                     (gnus-parameter-ham-marks group)))
719            (marks (car marks))
720            (marks (if (listp (car marks)) (car marks) marks)))
721       marks)))
722
723 (defun spam-group-spam-marks (group)
724   "In GROUP, get all the spam marks."
725   (spam-group-ham-marks group t))
726
727 (defun spam-group-spam-contents-p (group)
728   "Is GROUP a spam group?"
729   (if (and (stringp group) (< 0 (length group)))
730       (or (member group spam-junk-mailgroups)
731           (memq 'gnus-group-spam-classification-spam
732                 (gnus-parameter-spam-contents group)))
733     nil))
734
735 (defun spam-group-ham-contents-p (group)
736   "Is GROUP a ham group?"
737   (if (stringp group)
738       (memq 'gnus-group-spam-classification-ham
739             (gnus-parameter-spam-contents group))
740     nil))
741
742 (defun spam-classifications ()
743   "Return list of valid classifications"
744   '(spam ham))
745
746 (defun spam-classification-valid-p (classification)
747   "Is CLASSIFICATION a valid spam/ham classification?"
748   (memq classification (spam-classifications)))
749
750 (defun spam-backend-properties ()
751   "Return list of valid classifications."
752   '(statistical mover check hrf srf huf suf))
753
754 (defun spam-backend-property-valid-p (property)
755   "Is PROPERTY a valid backend property?"
756   (memq property (spam-backend-properties)))
757
758 (defun spam-backend-function-type-valid-p (type)
759   (or (eq type 'registration)
760       (eq type 'unregistration)))
761
762 (defun spam-process-type-valid-p (process-type)
763   (or (eq process-type 'incoming)
764       (eq process-type 'process)))
765
766 (defun spam-list-articles (articles classification)
767   (let ((mark-check (if (eq classification 'spam)
768                         'spam-group-spam-mark-p
769                       'spam-group-ham-mark-p))
770         alist mark-cache-yes mark-cache-no)
771     (dolist (article articles)
772       (let ((mark (gnus-summary-article-mark article)))
773         (unless (or (memq mark mark-cache-yes)
774                     (memq mark mark-cache-no))
775           (if (funcall mark-check
776                        gnus-newsgroup-name
777                        mark)
778               (push mark mark-cache-yes)
779             (push mark mark-cache-no)))
780         (when (memq mark mark-cache-yes)
781           (push article alist))))
782     alist))
783
784 ;;}}}
785
786 ;;{{{ backend installation functions and procedures
787
788 (defun spam-install-backend-super (backend &rest properties)
789   "Install BACKEND for spam.el.
790 Accepts incoming CHECK, ham registration function HRF, spam
791 registration function SRF, ham unregistration function HUF, spam
792 unregistration function SUF, and an indication whether the
793 backend is STATISTICAL."
794
795   (setq spam-backends (add-to-list 'spam-backends backend))
796   (while properties
797     (let ((property (pop properties))
798           (value (pop properties)))
799       (if (spam-backend-property-valid-p property)
800           (put backend property value)
801         (gnus-error 
802          5 
803          "spam-install-backend-super got an invalid property %s"
804          property)))))
805
806 (defun spam-backend-list (&optional type)
807   "Return a list of all the backend symbols, constrained by TYPE.
808 When TYPE is 'non-mover, only non-mover backends are returned.
809 When TYPE is 'mover, only mover backends are returned."
810   (let (list)
811     (dolist (backend spam-backends)
812       (when (or
813              (null type)                ;either no type was requested
814              ;; or the type is 'mover and the backend is a mover
815              (and
816               (eq type 'mover)
817               (spam-backend-mover-p backend))
818              ;; or the type is 'non-mover and the backend is not a mover
819              (and
820               (eq type 'non-mover)
821               (not (spam-backend-mover-p backend))))
822         (push backend list)))
823       list))
824
825 (defun spam-backend-check (backend)
826   "Get the check function for BACKEND.
827 Each individual check may return nil, t, or a mailgroup name.
828 The value nil means that the check does not yield a decision, and
829 so, that further checks are needed.  The value t means that the
830 message is definitely not spam, and that further spam checks
831 should be inhibited.  Otherwise, a mailgroup name or the symbol
832 'spam (depending on spam-split-symbolic-return) is returned where
833 the mail should go, and further checks are also inhibited.  The
834 usual mailgroup name is the value of `spam-split-group', meaning
835 that the message is definitely a spam."
836   (get backend 'check))
837
838 (defun spam-backend-valid-p (backend)
839   "Is BACKEND valid?"
840   (member backend (spam-backend-list)))
841
842 (defun spam-backend-info (backend)
843   "Return information about BACKEND."
844   (if (spam-backend-valid-p backend)
845       (let (info)
846         (setq info (format "Backend %s has the following properties:\n"
847                            backend))
848         (dolist (property (spam-backend-properties))
849           (setq info (format "%s%s=%s\n" 
850                              info
851                              property
852                              (get backend property))))
853         info)
854     (gnus-error 5 "spam-backend-info was asked about an invalid backend %s"
855                 backend)))
856
857 (defun spam-backend-function (backend classification type)
858   "Get the BACKEND function for CLASSIFICATION and TYPE.
859 TYPE is 'registration or 'unregistration.
860 CLASSIFICATION is 'ham or 'spam."
861   (if (and
862        (spam-classification-valid-p classification)
863        (spam-backend-function-type-valid-p type))
864       (let ((retrieval 
865              (intern 
866               (format "spam-backend-%s-%s-function"
867                       classification
868                       type))))
869         (funcall retrieval backend))
870     (gnus-error 
871      5
872      "%s was passed invalid backend %s, classification %s, or type %s"
873      "spam-backend-function"
874      backend
875      classification
876      type)))
877
878 (defun spam-backend-ham-registration-function (backend)
879   "Get the ham registration function for BACKEND."
880   (get backend 'hrf))
881
882 (defun spam-backend-spam-registration-function (backend)
883   "Get the spam registration function for BACKEND."
884   (get backend 'srf))
885
886 (defun spam-backend-ham-unregistration-function (backend)
887   "Get the ham unregistration function for BACKEND."
888   (get backend 'huf))
889
890 (defun spam-backend-spam-unregistration-function (backend)
891   "Get the spam unregistration function for BACKEND."
892   (get backend 'suf))
893
894 (defun spam-backend-statistical-p (backend)
895   "Is BACKEND statistical?"
896   (get backend 'statistical))
897
898 (defun spam-backend-mover-p (backend)
899   "Is BACKEND a mover?"
900   (get backend 'mover))
901
902 (defun spam-install-backend-alias (backend alias)
903   "Add ALIAS to an existing BACKEND.
904 The previous backend settings for ALIAS are erased."
905
906   ;; install alias with no properties at first
907   (spam-install-backend-super alias)
908   
909   (dolist (property (spam-backend-properties))
910     (put alias property (get backend property))))
911
912 (defun spam-install-checkonly-backend (backend check)
913   "Install a BACKEND than can only CHECK for spam."
914   (spam-install-backend-super backend 'check check))
915
916 (defun spam-install-mover-backend (backend hrf srf huf suf)
917   "Install a BACKEND than can move articles at summary exit.
918 Accepts ham registration function HRF, spam registration function
919 SRF, ham unregistration function HUF, spam unregistration
920 function SUF.  The backend has no incoming check and can't be
921 statistical."
922   (spam-install-backend-super 
923    backend 
924    'hrf hrf 'srf srf 'huf huf 'suf suf 'mover t))
925
926 (defun spam-install-nocheck-backend (backend hrf srf huf suf)
927   "Install a BACKEND than has no check.
928 Accepts ham registration function HRF, spam registration function
929 SRF, ham unregistration function HUF, spam unregistration
930 function SUF.  The backend has no incoming check and can't be
931 statistical (it could be, but in practice that doesn't happen)."
932   (spam-install-backend-super 
933    backend
934    'hrf hrf 'srf srf 'huf huf 'suf suf))
935
936 (defun spam-install-backend (backend check hrf srf huf suf)
937   "Install a BACKEND.
938 Accepts incoming CHECK, ham registration function HRF, spam
939 registration function SRF, ham unregistration function HUF, spam
940 unregistration function SUF.  The backend won't be
941 statistical (use spam-install-statistical-backend for that)."
942   (spam-install-backend-super 
943    backend
944    'check check 'hrf hrf 'srf srf 'huf huf 'suf suf))
945
946 (defun spam-install-statistical-backend (backend check hrf srf huf suf)
947   "Install a BACKEND.
948 Accepts incoming CHECK, ham registration function HRF, spam
949 registration function SRF, ham unregistration function HUF, spam
950 unregistration function SUF.  The backend will be
951 statistical (use spam-install-backend for non-statistical
952 backends)."
953   (spam-install-backend-super 
954    backend
955    'check check 'statistical t 'hrf hrf 'srf srf 'huf huf 'suf suf))
956
957 (defun spam-install-statistical-checkonly-backend (backend check)
958   "Install a statistical BACKEND than can only CHECK for spam."
959   (spam-install-backend-super 
960    backend
961    'check check 'statistical t))
962
963 ;;}}}
964
965 ;;{{{ backend installations
966 (spam-install-checkonly-backend 'spam-use-blackholes
967                                 'spam-check-blackholes)
968
969 (spam-install-checkonly-backend 'spam-use-hashcash
970                                 'spam-check-hashcash)
971
972 (spam-install-checkonly-backend 'spam-use-spamassassin-headers
973                                 'spam-check-spamassassin-headers)
974
975 (spam-install-checkonly-backend 'spam-use-bogofilter-headers
976                                 'spam-check-bogofilter-headers)
977
978 (spam-install-checkonly-backend 'spam-use-bsfilter-headers
979                                 'spam-check-bsfilter-headers)
980
981 (spam-install-checkonly-backend 'spam-use-gmane-xref
982                                 'spam-check-gmane-xref)
983
984 (spam-install-checkonly-backend 'spam-use-regex-headers
985                                 'spam-check-regex-headers)
986
987 (spam-install-statistical-checkonly-backend 'spam-use-regex-body
988                                             'spam-check-regex-body)
989
990 ;; TODO: NOTE: spam-use-ham-copy is now obsolete, use (ham spam-use-copy) instead
991 (spam-install-mover-backend 'spam-use-move
992                             'spam-move-ham-routine
993                             'spam-move-spam-routine
994                             nil
995                             nil)
996
997 (spam-install-nocheck-backend 'spam-use-copy
998                               'spam-copy-ham-routine
999                               'spam-copy-spam-routine
1000                               nil
1001                               nil)
1002
1003 (spam-install-nocheck-backend 'spam-use-gmane
1004                               nil
1005                               'spam-report-gmane-register-routine
1006                               ;; does Gmane support unregistration?
1007                               nil
1008                               nil)
1009
1010 (spam-install-nocheck-backend 'spam-use-resend
1011                               'spam-report-resend-register-ham-routine
1012                               'spam-report-resend-register-routine
1013                               nil
1014                               nil)
1015
1016 (spam-install-backend 'spam-use-BBDB     
1017                       'spam-check-BBDB
1018                       'spam-BBDB-register-routine
1019                       nil
1020                       'spam-BBDB-unregister-routine
1021                       nil)
1022
1023 (spam-install-backend-alias 'spam-use-BBDB 'spam-use-BBDB-exclusive)
1024
1025 (spam-install-backend 'spam-use-blacklist
1026                       'spam-check-blacklist
1027                       nil
1028                       'spam-blacklist-register-routine
1029                       nil
1030                       'spam-blacklist-unregister-routine)
1031
1032 (spam-install-backend 'spam-use-whitelist
1033                       'spam-check-whitelist
1034                       'spam-whitelist-register-routine
1035                       nil
1036                       'spam-whitelist-unregister-routine
1037                       nil)
1038
1039 (spam-install-statistical-backend 'spam-use-ifile
1040                                   'spam-check-ifile
1041                                   'spam-ifile-register-ham-routine
1042                                   'spam-ifile-register-spam-routine
1043                                   'spam-ifile-unregister-ham-routine
1044                                   'spam-ifile-unregister-spam-routine)
1045
1046 (spam-install-statistical-backend 'spam-use-spamoracle
1047                                   'spam-check-spamoracle
1048                                   'spam-spamoracle-learn-ham
1049                                   'spam-spamoracle-learn-spam
1050                                   'spam-spamoracle-unlearn-ham
1051                                   'spam-spamoracle-unlearn-spam)
1052
1053 (spam-install-statistical-backend 'spam-use-stat
1054                                   'spam-check-stat
1055                                   'spam-stat-register-ham-routine
1056                                   'spam-stat-register-spam-routine
1057                                   'spam-stat-unregister-ham-routine
1058                                   'spam-stat-unregister-spam-routine)
1059
1060 (spam-install-statistical-backend 'spam-use-spamassassin 
1061                                   'spam-check-spamassassin
1062                                   'spam-spamassassin-register-ham-routine
1063                                   'spam-spamassassin-register-spam-routine
1064                                   'spam-spamassassin-unregister-ham-routine
1065                                   'spam-spamassassin-unregister-spam-routine)
1066
1067 (spam-install-statistical-backend 'spam-use-bogofilter
1068                                   'spam-check-bogofilter
1069                                   'spam-bogofilter-register-ham-routine
1070                                   'spam-bogofilter-register-spam-routine
1071                                   'spam-bogofilter-unregister-ham-routine
1072                                   'spam-bogofilter-unregister-spam-routine)
1073
1074 (spam-install-statistical-backend 'spam-use-bsfilter
1075                                   'spam-check-bsfilter
1076                                   'spam-bsfilter-register-ham-routine
1077                                   'spam-bsfilter-register-spam-routine
1078                                   'spam-bsfilter-unregister-ham-routine
1079                                   'spam-bsfilter-unregister-spam-routine)
1080
1081 (spam-install-statistical-backend 'spam-use-crm114
1082                                   'spam-check-crm114
1083                                   'spam-crm114-register-ham-routine
1084                                   'spam-crm114-register-spam-routine
1085                                   ;; does CRM114 Mailfilter support unregistration?
1086                                   nil
1087                                   nil)
1088
1089 ;;}}}
1090
1091 ;;{{{ scoring and summary formatting
1092 (defun spam-necessary-extra-headers ()
1093   "Return the extra headers spam.el thinks are necessary."
1094   (let (list)
1095     (when (or spam-use-spamassassin
1096               spam-use-spamassassin-headers
1097               spam-use-regex-headers)
1098       (push 'X-Spam-Status list))
1099     list))
1100
1101 (defun spam-user-format-function-S (headers)
1102   (when headers
1103     (spam-summary-score headers)))
1104
1105 (defun spam-article-sort-by-spam-status (h1 h2)
1106   "Sort articles by score."
1107   (let (result)
1108     (dolist (header (spam-necessary-extra-headers))
1109       (let ((s1 (spam-summary-score h1 header))
1110             (s2 (spam-summary-score h2 header)))
1111       (unless (= s1 s2)
1112         (setq result (< s1 s2))
1113         (return))))
1114     result))
1115
1116 (defun spam-extra-header-to-number (header headers)
1117   "Transform an extra header to a number."
1118   (if (gnus-extra-header header headers)
1119       (cond
1120        ((eq header 'X-Spam-Status)
1121         (string-to-number (gnus-replace-in-string
1122                            (gnus-extra-header header headers)
1123                            ".*hits=" "")))
1124        ;; for CRM checking, it's probably faster to just do the string match
1125        ((and spam-use-crm114 (string-match "( pR: \\([0-9.-]+\\)" header))
1126         (match-string 1 header))
1127        (t nil))
1128     nil))
1129
1130 (defun spam-summary-score (headers &optional specific-header)
1131   "Score an article for the summary buffer, as fast as possible.
1132 With SPECIFIC-HEADER, returns only that header's score.
1133 Will not return a nil score."
1134   (let (score)
1135     (dolist (header 
1136              (if specific-header
1137                  (list specific-header)
1138                (spam-necessary-extra-headers)))
1139       (setq score 
1140             (spam-extra-header-to-number header headers))
1141       (when score 
1142         (return)))
1143     (or score 0)))
1144
1145 (defun spam-generic-score (&optional recheck)
1146   "Invoke whatever scoring method we can."
1147   (interactive "P")
1148   (cond
1149    ((or spam-use-spamassassin spam-use-spamassassin-headers)
1150     (spam-spamassassin-score recheck))
1151    ((or spam-use-bsfilter spam-use-bsfilter-headers)
1152     (spam-bsfilter-score recheck))
1153    (spam-use-crm114
1154     (spam-crm114-score))
1155    (t (spam-bogofilter-score recheck))))
1156 ;;}}}
1157
1158 ;;{{{ set up widening, processor checks
1159
1160 ;;; set up IMAP widening if it's necessary
1161 (defun spam-setup-widening ()
1162   (when (spam-widening-needed-p)
1163     (setq nnimap-split-download-body-default t)))
1164
1165 (defun spam-widening-needed-p (&optional force-symbols)
1166   (let (found)
1167     (dolist (backend (spam-backend-list))
1168       (when (and (spam-backend-statistical-p backend)
1169                  (or (symbol-value backend) 
1170                      (memq backend force-symbols)))
1171         (setq found backend)))
1172     found))
1173
1174 (defvar spam-list-of-processors
1175   ;; note the nil processors are not defined in gnus.el
1176   '((gnus-group-spam-exit-processor-bogofilter   spam spam-use-bogofilter)
1177     (gnus-group-spam-exit-processor-bsfilter     spam spam-use-bsfilter)
1178     (gnus-group-spam-exit-processor-blacklist    spam spam-use-blacklist)
1179     (gnus-group-spam-exit-processor-ifile        spam spam-use-ifile)
1180     (gnus-group-spam-exit-processor-stat         spam spam-use-stat)
1181     (gnus-group-spam-exit-processor-spamoracle   spam spam-use-spamoracle)
1182     (gnus-group-spam-exit-processor-spamassassin spam spam-use-spamassassin)
1183     (gnus-group-ham-exit-processor-ifile         ham spam-use-ifile)
1184     (gnus-group-ham-exit-processor-bogofilter    ham spam-use-bogofilter)
1185     (gnus-group-ham-exit-processor-bsfilter      ham spam-use-bsfilter)
1186     (gnus-group-ham-exit-processor-stat          ham spam-use-stat)
1187     (gnus-group-ham-exit-processor-whitelist     ham spam-use-whitelist)
1188     (gnus-group-ham-exit-processor-BBDB          ham spam-use-BBDB)
1189     (gnus-group-ham-exit-processor-copy          ham spam-use-ham-copy)
1190     (gnus-group-ham-exit-processor-spamassassin  ham spam-use-spamassassin)
1191     (gnus-group-ham-exit-processor-spamoracle    ham spam-use-spamoracle))
1192   "The OBSOLETE `spam-list-of-processors' list.
1193 This list contains pairs associating the obsolete ham/spam exit
1194 processor variables with a classification and a spam-use-*
1195 variable.  When the processor variable is nil, just the
1196 classification and spam-use-* check variable are used.  This is
1197 superceded by the new spam backend code, so it's only consulted
1198 for backwards compatibility.")
1199
1200 (defun spam-group-processor-p (group backend &optional classification)
1201   "Checks if GROUP has a BACKEND with CLASSIFICATION registered.
1202 Also accepts the obsolete processors, which can be found in
1203 gnus.el and in spam-list-of-processors.  In the case of mover
1204 backends, checks the setting of spam-summary-exit-behavior in
1205 addition to the set values for the group."
1206   (if (and (stringp group)
1207            (symbolp backend))
1208       (let ((old-style (assq backend spam-list-of-processors))
1209             (parameters (nth 0 (gnus-parameter-spam-process group)))
1210             found)
1211         (if old-style  ; old-style processor
1212             (spam-group-processor-p group (nth 2 old-style) (nth 1 old-style))
1213           ;; now search for the parameter
1214           (dolist (parameter parameters)
1215             (when (and (null found)
1216                        (listp parameter)
1217                        (eq classification (nth 0 parameter))
1218                        (eq backend (nth 1 parameter)))
1219               (setq found t)))
1220
1221           ;; now, if the parameter was not found, do the
1222           ;; spam-summary-exit-behavior-logic for mover backends
1223           (unless found
1224             (when (spam-backend-mover-p backend)
1225               (setq 
1226                found
1227                (cond
1228                 ((eq spam-summary-exit-behavior 'move-all) t)
1229                 ((eq spam-summary-exit-behavior 'move-none) nil)
1230                 ((eq spam-summary-exit-behavior 'default)
1231                  (or (eq classification 'spam) ;move spam out of all groups
1232                      ;; move ham out of spam groups
1233                      (and (eq classification 'ham)
1234                           (spam-group-spam-contents-p group))))
1235                 (t (gnus-error 5 "Unknown spam-summary-exit-behavior: %s" 
1236                                spam-summary-exit-behavior))))))
1237
1238           found))
1239     nil))
1240
1241 ;;}}}
1242
1243 ;;{{{ Summary entry and exit processing.
1244
1245 (defun spam-mark-junk-as-spam-routine ()
1246   ;; check the global list of group names spam-junk-mailgroups and the
1247   ;; group parameters
1248   (when (spam-group-spam-contents-p gnus-newsgroup-name)
1249     (gnus-message 6 "Marking %s articles as spam"
1250                   (if spam-mark-only-unseen-as-spam
1251                       "unseen"
1252                     "unread"))
1253     (let ((articles (if spam-mark-only-unseen-as-spam
1254                         gnus-newsgroup-unseen
1255                       gnus-newsgroup-unreads)))
1256       (if spam-mark-new-messages-in-spam-group-as-spam
1257           (dolist (article articles)
1258             (gnus-summary-mark-article article gnus-spam-mark))
1259         (gnus-message 9 "Did not mark new messages as spam.")))))
1260
1261 (defun spam-summary-prepare ()
1262   (setq spam-old-articles
1263         (list (cons 'ham (spam-list-articles gnus-newsgroup-articles 'ham))
1264               (cons 'spam (spam-list-articles gnus-newsgroup-articles 'spam))))
1265   (spam-mark-junk-as-spam-routine))
1266
1267 ;; The spam processors are invoked for any group, spam or ham or neither
1268 (defun spam-summary-prepare-exit ()
1269   (unless gnus-group-is-exiting-without-update-p
1270     (gnus-message 6 "Exiting summary buffer and applying spam rules")
1271
1272     ;; first of all, unregister any articles that are no longer ham or spam
1273     ;; we have to iterate over the processors, or else we'll be too slow
1274     (dolist (classification (spam-classifications))
1275       (let* ((old-articles (cdr-safe (assq classification spam-old-articles)))
1276              (new-articles (spam-list-articles
1277                             gnus-newsgroup-articles
1278                             classification))
1279              (changed-articles (spam-set-difference new-articles old-articles)))
1280         ;; now that we have the changed articles, we go through the processors
1281         (dolist (backend (spam-backend-list))
1282           (let (unregister-list)
1283             (dolist (article changed-articles)
1284               (let ((id (spam-fetch-field-message-id-fast article)))
1285                 (when (spam-log-unregistration-needed-p
1286                        id 'process classification backend)
1287                   (push article unregister-list))))
1288             ;; call spam-register-routine with specific articles to unregister,
1289             ;; when there are articles to unregister and the check is enabled
1290             (when (and unregister-list (symbol-value backend))
1291               (spam-unregister-routine 
1292                classification 
1293                backend 
1294                unregister-list))))))
1295
1296     ;; do the non-moving backends first, then the moving ones
1297     (dolist (backend-type '(non-mover mover))
1298       (dolist (classification '(spam ham))
1299         (dolist (backend (spam-backend-list backend-type))
1300           (when (spam-group-processor-p
1301                  gnus-newsgroup-name
1302                  backend
1303                  classification)
1304             (let ((num (spam-register-routine classification backend)))
1305               (when (> num 0)
1306                 (gnus-message 
1307                  6
1308                  "%d %s messages were processed by backend %s."
1309                  num
1310                  classification
1311                  backend)))))))
1312
1313     ;; we mark all the leftover spam articles as expired at the end
1314     (dolist (article (spam-list-articles
1315                       gnus-newsgroup-articles
1316                       'spam))
1317       (gnus-summary-mark-article article gnus-expirable-mark)))
1318
1319   (setq spam-old-articles nil))
1320
1321 ;;}}}
1322
1323 ;;{{{ spam-use-move and spam-use-copy backend support functions
1324
1325 (defun spam-copy-or-move-routine (copy groups articles classification)
1326
1327   (when (and (car-safe groups) (listp (car-safe groups)))
1328     (setq groups (pop groups)))
1329
1330   (unless (listp groups)
1331     (setq groups (list groups)))
1332
1333     ;; remove the current process mark
1334   (gnus-summary-kill-process-mark)
1335
1336   (let ((backend-supports-deletions
1337          (gnus-check-backend-function
1338           'request-move-article gnus-newsgroup-name))
1339         (respool-method (gnus-find-method-for-group gnus-newsgroup-name))
1340         article mark deletep respool)
1341
1342     (when (member 'respool groups)
1343       (setq respool t)                  ; boolean for later
1344       (setq groups '("fake"))) ; when respooling, groups are dynamic so fake it
1345
1346     ;; now do the actual move
1347     (dolist (group groups)
1348       (when (and articles (stringp group))
1349
1350         ;; first, mark the article with the process mark and, if needed,
1351         ;; the unread or expired mark (for ham and spam respectively)
1352         (dolist (article articles)
1353           (when (and (eq classification 'ham)
1354                      spam-mark-ham-unread-before-move-from-spam-group)
1355             (gnus-message 9 "Marking ham article %d unread before move"
1356                           article)
1357             (gnus-summary-mark-article article gnus-unread-mark))
1358           (when (and (eq classification 'spam)
1359                      (not copy))
1360             (gnus-message 9 "Marking spam article %d expirable before move"
1361                           article)
1362             (gnus-summary-mark-article article gnus-expirable-mark))
1363           (gnus-summary-set-process-mark article)
1364             
1365           (if respool              ; respooling is with a "fake" group
1366               (let ((spam-split-disabled
1367                      (or spam-split-disabled
1368                          (and (eq classification 'ham) 
1369                               spam-disable-spam-split-during-ham-respool))))
1370                 (gnus-message 9 "Respooling article %d with method %s"
1371                               article respool-method)
1372                 (gnus-summary-respool-article nil respool-method))
1373             (if (or (not backend-supports-deletions) ; else, we are not respooling
1374                     (> (length groups) 1))
1375                 (progn              ; if copying, copy and set deletep
1376                   (gnus-message 9 "Copying article %d to group %s"
1377                                 article group)
1378                   (gnus-summary-copy-article nil group)
1379                   (setq deletep t))
1380               (gnus-message 9 "Moving article %d to group %s"
1381                             article group)
1382               (gnus-summary-move-article nil group))))) ; else move articles
1383         
1384       ;; now delete the articles, unless a) copy is t, and there was a copy done
1385       ;;                                 b) a move was done to a single group
1386       ;;                                 c) backend-supports-deletions is nil
1387       (unless copy
1388         (when (and deletep backend-supports-deletions)
1389           (dolist (article articles)
1390               (gnus-summary-set-process-mark article)
1391               (gnus-message 9 "Deleting article %d" article))
1392           (when articles
1393             (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
1394               (gnus-summary-delete-article nil)))))
1395         
1396       (gnus-summary-yank-process-mark)
1397       (length articles))))
1398
1399 (defun spam-copy-spam-routine (articles)
1400   (spam-copy-or-move-routine 
1401    t 
1402    (gnus-parameter-spam-process-destination gnus-newsgroup-name)
1403    articles
1404    'spam))
1405
1406 (defun spam-move-spam-routine (articles)
1407   (spam-copy-or-move-routine 
1408    nil
1409    (gnus-parameter-spam-process-destination gnus-newsgroup-name)
1410    articles
1411    'spam))
1412
1413 (defun spam-copy-ham-routine (articles)
1414   (spam-copy-or-move-routine 
1415    t 
1416    (gnus-parameter-ham-process-destination gnus-newsgroup-name)
1417    articles
1418    'ham))
1419
1420 (defun spam-move-ham-routine (articles)
1421   (spam-copy-or-move-routine 
1422    nil
1423    (gnus-parameter-ham-process-destination gnus-newsgroup-name)
1424    articles
1425    'ham))
1426
1427 ;;}}}
1428
1429 ;;{{{ article and field retrieval code
1430 (defun spam-get-article-as-string (article)
1431   (when (numberp article)
1432     (with-temp-buffer
1433       (gnus-request-article-this-buffer
1434        article
1435        gnus-newsgroup-name)
1436       (buffer-string))))
1437
1438 ;; disabled for now
1439 ;; (defun spam-get-article-as-filename (article)
1440 ;;   (let ((article-filename))
1441 ;;     (when (numberp article)
1442 ;;       (nnml-possibly-change-directory
1443 ;;        (gnus-group-real-name gnus-newsgroup-name))
1444 ;;       (setq article-filename (expand-file-name
1445 ;;                              (int-to-string article) nnml-current-directory)))
1446 ;;     (if (file-exists-p article-filename)
1447 ;;      article-filename
1448 ;;       nil)))
1449
1450 (defun spam-fetch-field-fast (article field &optional prepared-data-header)
1451   "Fetch a FIELD for ARTICLE quickly, using the internal gnus-data-list function.
1452 When PREPARED-DATA-HEADER is given, don't look in the Gnus data.
1453 When FIELD is 'number, ARTICLE can be any number (since we want
1454 to find it out)."
1455   (when (numberp article)
1456     (let* ((data-header (or prepared-data-header
1457                             (spam-fetch-article-header article))))
1458       (if (arrayp data-header)
1459         (cond
1460          ((equal field 'number)
1461           (mail-header-number data-header))
1462          ((equal field 'from)
1463           (mail-header-from data-header))
1464          ((equal field 'message-id)
1465           (mail-header-message-id data-header))
1466          ((equal field 'subject)
1467           (mail-header-subject data-header))
1468          ((equal field 'references)
1469           (mail-header-references data-header))
1470          ((equal field 'date)
1471           (mail-header-date data-header))
1472          ((equal field 'xref)
1473           (mail-header-xref data-header))
1474          ((equal field 'extra)
1475           (mail-header-extra data-header))
1476          (t
1477           (gnus-error 
1478            5 
1479            "spam-fetch-field-fast: unknown field %s requested" 
1480            field)
1481           nil))
1482         (gnus-message 6 "Article %d has a nil data header" article)))))
1483
1484 (defun spam-fetch-field-from-fast (article &optional prepared-data-header)
1485   (spam-fetch-field-fast article 'from prepared-data-header))
1486
1487 (defun spam-fetch-field-subject-fast (article &optional prepared-data-header)
1488   (spam-fetch-field-fast article 'subject prepared-data-header))
1489
1490 (defun spam-fetch-field-message-id-fast (article &optional prepared-data-header)
1491   (spam-fetch-field-fast article 'message-id prepared-data-header))
1492
1493 (defun spam-generate-fake-headers (article)
1494   (let ((dh (spam-fetch-article-header article)))
1495     (if dh
1496         (concat
1497          (format
1498           ;; 80-character limit makes for strange constructs
1499           (concat "From: %s\nSubject: %s\nMessage-ID: %s\n"
1500                   "Date: %s\nReferences: %s\nXref: %s\n")
1501           (spam-fetch-field-fast article 'from dh)
1502           (spam-fetch-field-fast article 'subject dh)
1503           (spam-fetch-field-fast article 'message-id dh)
1504           (spam-fetch-field-fast article 'date dh)
1505           (spam-fetch-field-fast article 'references dh)
1506           (spam-fetch-field-fast article 'xref dh))
1507          (when (spam-fetch-field-fast article 'extra dh)
1508            (format "%s\n" (spam-fetch-field-fast article 'extra dh))))
1509       (gnus-message
1510        5
1511        "spam-generate-fake-headers: article %d didn't have a valid header"
1512        article))))
1513
1514 (defun spam-fetch-article-header (article)
1515   (save-excursion
1516     (set-buffer gnus-summary-buffer)
1517     (gnus-read-header article)
1518     (nth 3 (assq article gnus-newsgroup-data))))
1519 ;;}}}
1520
1521 ;;{{{ Spam determination.
1522
1523 (defun spam-split (&rest specific-checks)
1524   "Split this message into the `spam' group if it is spam.
1525 This function can be used as an entry in the variable `nnmail-split-fancy',
1526 for example like this: (: spam-split).  It can take checks as
1527 parameters.  A string as a parameter will set the
1528 spam-split-group to that string.
1529
1530 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1531   (interactive)
1532   (setq spam-split-last-successful-check nil)
1533   (unless spam-split-disabled
1534     (let ((spam-split-group-choice spam-split-group))
1535       (dolist (check specific-checks)
1536         (when (stringp check)
1537           (setq spam-split-group-choice check)
1538           (setq specific-checks (delq check specific-checks))))
1539
1540       (let ((spam-split-group spam-split-group-choice)
1541             (widening-needed-check (spam-widening-needed-p specific-checks)))
1542         (save-excursion
1543           (save-restriction
1544             (when widening-needed-check
1545               (widen)
1546               (gnus-message 8 "spam-split: widening the buffer (%s requires it)"
1547                             widening-needed-check))
1548             (let ((backends (spam-backend-list))
1549                   decision)
1550               (while (and backends (not decision))
1551                 (let* ((backend (pop backends))
1552                        (check-function (spam-backend-check backend))
1553                        (spam-split-group (if spam-split-symbolic-return
1554                                              'spam
1555                                            spam-split-group)))
1556                   (when (or
1557                          ;; either, given specific checks, this is one of them
1558                          (memq backend specific-checks)
1559                          ;; or, given no specific checks, spam-use-CHECK is set
1560                          (and (null specific-checks) (symbol-value backend)))
1561                     (gnus-message 6 "spam-split: calling the %s function"
1562                                   check-function)
1563                     (setq decision (funcall check-function))
1564                     ;; if we got a decision at all, save the current check
1565                     (when decision
1566                       (setq spam-split-last-successful-check backend))
1567
1568                     (when (eq decision 'spam)
1569                       (unless spam-split-symbolic-return
1570                         (gnus-error
1571                          5
1572                          (format "spam-split got %s but %s is nil"
1573                                  decision
1574                                  spam-split-symbolic-return)))))))
1575               (if (eq decision t)
1576                   (if spam-split-symbolic-return-positive 'ham nil)
1577                 decision))))))))
1578
1579 (defun spam-find-spam ()
1580   "This function will detect spam in the current newsgroup using spam-split."
1581   (interactive)
1582
1583   (let* ((group gnus-newsgroup-name)
1584          (autodetect (gnus-parameter-spam-autodetect group))
1585          (methods (gnus-parameter-spam-autodetect-methods group))
1586          (first-method (nth 0 methods))
1587          (articles (if spam-autodetect-recheck-messages
1588                        gnus-newsgroup-articles
1589                      gnus-newsgroup-unseen))
1590          article-cannot-be-faked)
1591
1592     
1593     (dolist (backend methods)
1594       (when (spam-backend-statistical-p backend)
1595         (setq article-cannot-be-faked t)
1596         (return)))
1597
1598     (when (memq 'default methods)
1599       (setq article-cannot-be-faked t))
1600
1601     (when (and autodetect
1602                (not (equal first-method 'none)))
1603       (mapcar
1604        (lambda (article)
1605          (let ((id (spam-fetch-field-message-id-fast article))
1606                (subject (spam-fetch-field-subject-fast article))
1607                (sender (spam-fetch-field-from-fast article))
1608                registry-lookup)
1609            
1610            (unless id
1611              (gnus-message 6 "Article %d has no message ID!" article))
1612          
1613            (when (and id spam-log-to-registry)
1614              (setq registry-lookup (spam-log-registration-type id 'incoming))
1615              (when registry-lookup
1616                (gnus-message
1617                 9
1618                 "spam-find-spam: message %s was already registered incoming"
1619                 id)))
1620
1621            (let* ((spam-split-symbolic-return t)
1622                   (spam-split-symbolic-return-positive t)
1623                   (fake-headers (spam-generate-fake-headers article))
1624                   (split-return
1625                    (or registry-lookup
1626                        (with-temp-buffer
1627                          (if article-cannot-be-faked
1628                              (gnus-request-article-this-buffer
1629                               article
1630                               group)
1631                            ;; else, we fake the article
1632                            (when fake-headers (insert fake-headers)))
1633                          (if (or (null first-method)
1634                                  (equal first-method 'default))
1635                              (spam-split)
1636                            (apply 'spam-split methods))))))
1637              (if (equal split-return 'spam)
1638                  (gnus-summary-mark-article article gnus-spam-mark))
1639            
1640              (when (and id split-return spam-log-to-registry)
1641                (when (zerop (gnus-registry-group-count id))
1642                  (gnus-registry-add-group
1643                   id group subject sender))
1644                
1645                (unless registry-lookup
1646                  (spam-log-processing-to-registry
1647                   id
1648                   'incoming
1649                   split-return
1650                   spam-split-last-successful-check
1651                   group))))))
1652        articles))))
1653
1654 ;;}}}
1655
1656 ;;{{{ registration/unregistration functions
1657
1658 (defun spam-unregister-routine (classification
1659                                 backend
1660                                 &optional specific-articles)
1661   (spam-register-routine classification backend t specific-articles))
1662
1663 (defun spam-register-routine (classification
1664                               backend
1665                               &optional unregister
1666                               specific-articles)
1667   (when (and (spam-classification-valid-p classification)
1668              (spam-backend-valid-p backend))
1669     (let* ((register-function
1670             (spam-backend-function backend classification 'registration))
1671            (unregister-function
1672             (spam-backend-function backend classification 'unregistration))
1673            (run-function (if unregister
1674                              unregister-function
1675                            register-function))
1676            (log-function (if unregister
1677                              'spam-log-undo-registration
1678                            'spam-log-processing-to-registry))
1679            article articles)
1680
1681       (when run-function
1682         ;; make list of articles, using specific-articles if given
1683         (setq articles (or specific-articles
1684                            (spam-list-articles
1685                             gnus-newsgroup-articles
1686                             classification)))
1687         ;; process them
1688         (when (> (length articles) 0)
1689           (gnus-message 5 "%s %d %s articles as %s using backend %s"
1690                         (if unregister "Unregistering" "Registering")
1691                         (length articles)
1692                         (if specific-articles "specific" "")
1693                         classification
1694                         backend)
1695           (funcall run-function articles)
1696           ;; now log all the registrations (or undo them, depending on unregister)
1697           (dolist (article articles)
1698             (funcall log-function
1699                      (spam-fetch-field-message-id-fast article)
1700                      'process
1701                      classification
1702                      backend
1703                      gnus-newsgroup-name))))
1704     (length articles))))      ;return the number of articles processed
1705
1706 ;;; log a ham- or spam-processor invocation to the registry
1707 (defun spam-log-processing-to-registry (id type classification backend group)
1708   (when spam-log-to-registry
1709     (if (and (stringp id)
1710              (stringp group)
1711              (spam-process-type-valid-p type)
1712              (spam-classification-valid-p classification)
1713              (spam-backend-valid-p backend))
1714         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1715               (cell (list classification backend group)))
1716           (push cell cell-list)
1717           (gnus-registry-store-extra-entry
1718            id
1719            type
1720            cell-list))
1721
1722       (gnus-error
1723        7
1724        (format "%s call with bad ID, type, classification, spam-backend, or group"
1725                "spam-log-processing-to-registry")))))
1726
1727 ;;; check if a ham- or spam-processor registration has been done
1728 (defun spam-log-registered-p (id type)
1729   (when spam-log-to-registry
1730     (if (and (stringp id)
1731              (spam-process-type-valid-p type))
1732         (cdr-safe (gnus-registry-fetch-extra id type))
1733       (progn
1734         (gnus-error
1735          7
1736          (format "%s called with bad ID, type, classification, or spam-backend"
1737                  "spam-log-registered-p"))
1738         nil))))
1739
1740 ;;; check what a ham- or spam-processor registration says
1741 ;;; returns nil if conflicting registrations are found
1742 (defun spam-log-registration-type (id type)
1743   (let ((count 0)
1744         decision)
1745     (dolist (reg (spam-log-registered-p id type))
1746       (let ((classification (nth 0 reg)))
1747         (when (spam-classification-valid-p classification)
1748           (when (and decision
1749                      (not (eq classification decision)))
1750             (setq count (+ 1 count)))
1751           (setq decision classification))))
1752     (if (< 0 count)
1753         nil
1754       decision)))
1755
1756
1757 ;;; check if a ham- or spam-processor registration needs to be undone
1758 (defun spam-log-unregistration-needed-p (id type classification backend)
1759   (when spam-log-to-registry
1760     (if (and (stringp id)
1761              (spam-process-type-valid-p type)
1762              (spam-classification-valid-p classification)
1763              (spam-backend-valid-p backend))
1764         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1765               found)
1766           (dolist (cell cell-list)
1767             (unless found
1768               (when (and (eq classification (nth 0 cell))
1769                          (eq backend (nth 1 cell)))
1770                 (setq found t))))
1771           found)
1772       (progn
1773         (gnus-error
1774          7
1775          (format "%s called with bad ID, type, classification, or spam-backend"
1776                  "spam-log-unregistration-needed-p"))
1777         nil))))
1778
1779
1780 ;;; undo a ham- or spam-processor registration (the group is not used)
1781 (defun spam-log-undo-registration (id type classification backend &optional group)
1782   (when (and spam-log-to-registry
1783              (spam-log-unregistration-needed-p id type classification backend))
1784     (if (and (stringp id)
1785              (spam-process-type-valid-p type)
1786              (spam-classification-valid-p classification)
1787              (spam-backend-valid-p backend))
1788         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1789               new-cell-list found)
1790           (dolist (cell cell-list)
1791             (unless (and (eq classification (nth 0 cell))
1792                          (eq backend (nth 1 cell)))
1793               (push cell new-cell-list)))
1794           (gnus-registry-store-extra-entry
1795            id
1796            type
1797            new-cell-list))
1798       (progn
1799         (gnus-error 7 (format "%s call with bad ID, type, spam-backend, or group"
1800                               "spam-log-undo-registration"))
1801         nil))))
1802
1803 ;;}}}
1804
1805 ;;{{{ backend functions
1806
1807 ;;{{{ Gmane xrefs
1808 (defun spam-check-gmane-xref ()
1809   (let ((header (or
1810                  (message-fetch-field "Xref")
1811                  (message-fetch-field "Newsgroups"))))
1812     (when header                        ; return nil when no header
1813       (when (string-match spam-gmane-xref-spam-group
1814                           header)
1815           spam-split-group))))
1816
1817 ;;}}}
1818
1819 ;;{{{ Regex body
1820
1821 (defun spam-check-regex-body ()
1822   (let ((spam-regex-headers-ham spam-regex-body-ham)
1823         (spam-regex-headers-spam spam-regex-body-spam))
1824     (spam-check-regex-headers t)))
1825
1826 ;;}}}
1827
1828 ;;{{{ Regex headers
1829
1830 (defun spam-check-regex-headers (&optional body)
1831   (let ((type (if body "body" "header"))
1832         ret found)
1833     (dolist (h-regex spam-regex-headers-ham)
1834       (unless found
1835         (goto-char (point-min))
1836         (when (re-search-forward h-regex nil t)
1837           (message "Ham regex %s search positive." type)
1838           (setq found t))))
1839     (dolist (s-regex spam-regex-headers-spam)
1840       (unless found
1841         (goto-char (point-min))
1842         (when (re-search-forward s-regex nil t)
1843           (message "Spam regex %s search positive." type)
1844           (setq found t)
1845           (setq ret spam-split-group))))
1846     ret))
1847
1848 ;;}}}
1849
1850 ;;{{{ Blackholes.
1851
1852 (defun spam-reverse-ip-string (ip)
1853   (when (stringp ip)
1854     (mapconcat 'identity
1855                (nreverse (split-string ip "\\."))
1856                ".")))
1857
1858 (defun spam-check-blackholes ()
1859   "Check the Received headers for blackholed relays."
1860   (let ((headers (message-fetch-field "received"))
1861         ips matches)
1862     (when headers
1863       (with-temp-buffer
1864         (insert headers)
1865         (goto-char (point-min))
1866         (gnus-message 6 "Checking headers for relay addresses")
1867         (while (re-search-forward
1868                 "\\([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\)" nil t)
1869           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
1870           (push (spam-reverse-ip-string (match-string 1))
1871                 ips)))
1872       (dolist (server spam-blackhole-servers)
1873         (dolist (ip ips)
1874           (unless (and spam-blackhole-good-server-regex
1875                        ;; match the good-server-regex against the reversed (again) IP string
1876                        (string-match
1877                         spam-blackhole-good-server-regex
1878                         (spam-reverse-ip-string ip)))
1879             (unless matches
1880               (let ((query-string (concat ip "." server)))
1881                 (if spam-use-dig
1882                     (let ((query-result (query-dig query-string)))
1883                       (when query-result
1884                         (gnus-message 6 "(DIG): positive blackhole check '%s'"
1885                                       query-result)
1886                         (push (list ip server query-result)
1887                               matches)))
1888                   ;; else, if not using dig.el
1889                   (when (query-dns query-string)
1890                     (gnus-message 6 "positive blackhole check")
1891                     (push (list ip server (query-dns query-string 'TXT))
1892                           matches)))))))))
1893     (when matches
1894       spam-split-group)))
1895 ;;}}}
1896
1897 ;;{{{ Hashcash.
1898
1899 (condition-case nil
1900     (progn
1901       (require 'hashcash)
1902
1903       (defun spam-check-hashcash ()
1904         "Check the headers for hashcash payments."
1905         (mail-check-payment)))   ;mail-check-payment returns a boolean
1906
1907   (file-error (progn
1908                 (defalias 'mail-check-payment 'ignore)
1909                 (defalias 'spam-check-hashcash 'ignore))))
1910 ;;}}}
1911
1912 ;;{{{ BBDB
1913
1914 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
1915 ;;; <sacha@giotto.sj.ru>
1916
1917 ;; all this is done inside a condition-case to trap errors
1918
1919 (condition-case nil
1920     (progn
1921       (require 'bbdb)
1922       (require 'bbdb-com)
1923
1924       ;; when the BBDB changes, we want to clear out our cache
1925       (defun spam-clear-cache-BBDB (&rest immaterial)
1926         (spam-clear-cache 'spam-use-BBDB))
1927
1928       (add-hook 'bbdb-change-hook 'spam-clear-cache-BBDB)
1929
1930       (defun spam-enter-ham-BBDB (addresses &optional remove)
1931         "Enter an address into the BBDB; implies ham (non-spam) sender"
1932         (dolist (from addresses)
1933           (when (stringp from)
1934             (let* ((parsed-address (gnus-extract-address-components from))
1935                    (name (or (nth 0 parsed-address) "Ham Sender"))
1936                    (remove-function (if remove
1937                                         'bbdb-delete-record-internal
1938                                       'ignore))
1939                    (net-address (nth 1 parsed-address))
1940                    (record (and net-address
1941                                 (bbdb-search-simple nil net-address))))
1942               (when net-address
1943                 (gnus-message 6 "%s address %s %s BBDB"
1944                               (if remove "Deleting" "Adding")
1945                               from
1946                               (if remove "from" "to"))
1947                 (if record
1948                     (funcall remove-function record)
1949                   (bbdb-create-internal name nil net-address nil nil
1950                                         "ham sender added by spam.el")))))))
1951
1952       (defun spam-BBDB-register-routine (articles &optional unregister)
1953         (let (addresses)
1954           (dolist (article articles)
1955             (when (stringp (spam-fetch-field-from-fast article))
1956               (push (spam-fetch-field-from-fast article) addresses)))
1957           ;; now do the register/unregister action
1958           (spam-enter-ham-BBDB addresses unregister)))
1959
1960       (defun spam-BBDB-unregister-routine (articles)
1961         (spam-BBDB-register-routine articles t))
1962
1963       (defun spam-check-BBDB ()
1964         "Mail from people in the BBDB is classified as ham or non-spam"
1965         (let ((who (message-fetch-field "from"))
1966               bbdb-cache bbdb-hashtable)
1967           (when spam-cache-lookups
1968             (setq bbdb-cache (gethash 'spam-use-BBDB spam-caches))
1969             (unless bbdb-cache
1970               (setq bbdb-cache
1971                     ;; this is the expanded (bbdb-hashtable) macro
1972                     ;; without the debugging support
1973                     (with-current-buffer (bbdb-buffer)
1974                       (save-excursion
1975                         (save-window-excursion
1976                           (bbdb-records nil t)
1977                           bbdb-hashtable))))
1978               (puthash 'spam-use-BBDB bbdb-cache spam-caches)))
1979           (when who
1980             (setq who (nth 1 (gnus-extract-address-components who)))
1981             (if
1982                 (if spam-cache-lookups
1983                     (symbol-value
1984                      (intern-soft who bbdb-cache))
1985                   (bbdb-search-simple nil who))
1986                 t
1987               (if spam-use-BBDB-exclusive
1988                   spam-split-group
1989                 nil))))))
1990
1991   (file-error (progn
1992                 (defalias 'bbdb-search-simple 'ignore)
1993                 (defalias 'bbdb-records 'ignore)
1994                 (defalias 'bbdb-buffer 'ignore)
1995                 (defalias 'spam-check-BBDB 'ignore)
1996                 (defalias 'spam-BBDB-register-routine 'ignore)
1997                 (defalias 'spam-enter-ham-BBDB 'ignore)
1998                 (defalias 'bbdb-create-internal 'ignore)
1999                 (defalias 'bbdb-delete-record-internal 'ignore)
2000                 (defalias 'bbdb-records 'ignore))))
2001
2002 ;;}}}
2003
2004 ;;{{{ ifile
2005
2006 ;;; check the ifile backend; return nil if the mail was NOT classified
2007 ;;; as spam
2008
2009 (defun spam-get-ifile-database-parameter ()
2010   "Get the command-line parameter for ifile's database from
2011   spam-ifile-database-path."
2012   (if spam-ifile-database-path
2013       (format "--db-file=%s" spam-ifile-database-path)
2014     nil))
2015
2016 (defun spam-check-ifile ()
2017   "Check the ifile backend for the classification of this message."
2018   (let ((article-buffer-name (buffer-name))
2019         category return)
2020     (with-temp-buffer
2021       (let ((temp-buffer-name (buffer-name))
2022             (db-param (spam-get-ifile-database-parameter)))
2023         (save-excursion
2024           (set-buffer article-buffer-name)
2025           (apply 'call-process-region
2026                  (point-min) (point-max) spam-ifile-path
2027                  nil temp-buffer-name nil "-c"
2028                  (if db-param `(,db-param "-q") `("-q"))))
2029         ;; check the return now (we're back in the temp buffer)
2030         (goto-char (point-min))
2031         (if (not (eobp))
2032             (setq category (buffer-substring (point) (point-at-eol))))
2033         (when (not (zerop (length category))) ; we need a category here
2034           (if spam-ifile-all-categories
2035               (setq return category)
2036             ;; else, if spam-ifile-all-categories is not set...
2037             (when (string-equal spam-ifile-spam-category category)
2038               (setq return spam-split-group)))))) ; note return is nil otherwise
2039     return))
2040
2041 (defun spam-ifile-register-with-ifile (articles category &optional unregister)
2042   "Register an article, given as a string, with a category.
2043 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
2044   (let ((category (or category gnus-newsgroup-name))
2045         (add-or-delete-option (if unregister "-d" "-i"))
2046         (db (spam-get-ifile-database-parameter))
2047         parameters)
2048     (with-temp-buffer
2049       (dolist (article articles)
2050         (let ((article-string (spam-get-article-as-string article)))
2051           (when (stringp article-string)
2052             (insert article-string))))
2053       (apply 'call-process-region
2054              (point-min) (point-max) spam-ifile-path
2055              nil nil nil
2056              add-or-delete-option category
2057              (if db `(,db "-h") `("-h"))))))
2058
2059 (defun spam-ifile-register-spam-routine (articles &optional unregister)
2060   (spam-ifile-register-with-ifile articles spam-ifile-spam-category unregister))
2061
2062 (defun spam-ifile-unregister-spam-routine (articles)
2063   (spam-ifile-register-spam-routine articles t))
2064
2065 (defun spam-ifile-register-ham-routine (articles &optional unregister)
2066   (spam-ifile-register-with-ifile articles spam-ifile-ham-category unregister))
2067
2068 (defun spam-ifile-unregister-ham-routine (articles)
2069   (spam-ifile-register-ham-routine articles t))
2070
2071 ;;}}}
2072
2073 ;;{{{ spam-stat
2074
2075 (condition-case nil
2076     (progn
2077       (let ((spam-stat-install-hooks nil))
2078         (require 'spam-stat))
2079
2080       (defun spam-check-stat ()
2081         "Check the spam-stat backend for the classification of this message"
2082         (let ((spam-stat-split-fancy-spam-group spam-split-group) ; override
2083               (spam-stat-buffer (buffer-name)) ; stat the current buffer
2084               category return)
2085           (spam-stat-split-fancy)))
2086
2087       (defun spam-stat-register-spam-routine (articles &optional unregister)
2088         (dolist (article articles)
2089           (let ((article-string (spam-get-article-as-string article)))
2090             (with-temp-buffer
2091               (insert article-string)
2092               (if unregister
2093                   (spam-stat-buffer-change-to-non-spam)
2094               (spam-stat-buffer-is-spam))))))
2095
2096       (defun spam-stat-unregister-spam-routine (articles)
2097         (spam-stat-register-spam-routine articles t))
2098
2099       (defun spam-stat-register-ham-routine (articles &optional unregister)
2100         (dolist (article articles)
2101           (let ((article-string (spam-get-article-as-string article)))
2102             (with-temp-buffer
2103               (insert article-string)
2104               (if unregister
2105                   (spam-stat-buffer-change-to-spam)
2106               (spam-stat-buffer-is-non-spam))))))
2107
2108       (defun spam-stat-unregister-ham-routine (articles)
2109         (spam-stat-register-ham-routine articles t))
2110
2111       (defun spam-maybe-spam-stat-load ()
2112         (when spam-use-stat (spam-stat-load)))
2113
2114       (defun spam-maybe-spam-stat-save ()
2115         (when spam-use-stat (spam-stat-save))))
2116
2117   (file-error (progn
2118                 (defalias 'spam-stat-load 'ignore)
2119                 (defalias 'spam-stat-save 'ignore)
2120                 (defalias 'spam-maybe-spam-stat-load 'ignore)
2121                 (defalias 'spam-maybe-spam-stat-save 'ignore)
2122                 (defalias 'spam-stat-register-ham-routine 'ignore)
2123                 (defalias 'spam-stat-unregister-ham-routine 'ignore)
2124                 (defalias 'spam-stat-register-spam-routine 'ignore)
2125                 (defalias 'spam-stat-unregister-spam-routine 'ignore)
2126                 (defalias 'spam-stat-buffer-is-spam 'ignore)
2127                 (defalias 'spam-stat-buffer-change-to-spam 'ignore)
2128                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
2129                 (defalias 'spam-stat-buffer-change-to-non-spam 'ignore)
2130                 (defalias 'spam-stat-split-fancy 'ignore)
2131                 (defalias 'spam-check-stat 'ignore))))
2132
2133
2134
2135 ;;}}}
2136
2137 ;;{{{ Blacklists and whitelists.
2138
2139 (defvar spam-whitelist-cache nil)
2140 (defvar spam-blacklist-cache nil)
2141
2142 (defun spam-kill-whole-line ()
2143   (beginning-of-line)
2144   (let ((kill-whole-line t))
2145     (kill-line)))
2146
2147 ;;; address can be a list, too
2148 (defun spam-enter-whitelist (address &optional remove)
2149   "Enter ADDRESS (list or single) into the whitelist.
2150 With a non-nil REMOVE, remove them."
2151   (interactive "sAddress: ")
2152   (spam-enter-list address spam-whitelist remove)
2153   (setq spam-whitelist-cache nil)
2154   (spam-clear-cache 'spam-use-whitelist))
2155
2156 ;;; address can be a list, too
2157 (defun spam-enter-blacklist (address &optional remove)
2158   "Enter ADDRESS (list or single) into the blacklist.
2159 With a non-nil REMOVE, remove them."
2160   (interactive "sAddress: ")
2161   (spam-enter-list address spam-blacklist remove)
2162   (setq spam-blacklist-cache nil)
2163   (spam-clear-cache 'spam-use-whitelist))
2164
2165 (defun spam-enter-list (addresses file &optional remove)
2166   "Enter ADDRESSES into the given FILE.
2167 Either the whitelist or the blacklist files can be used.  With
2168 REMOVE not nil, remove the ADDRESSES."
2169   (if (stringp addresses)
2170       (spam-enter-list (list addresses) file remove)
2171     ;; else, we have a list of addresses here
2172     (unless (file-exists-p (file-name-directory file))
2173       (make-directory (file-name-directory file) t))
2174     (save-excursion
2175       (set-buffer
2176        (find-file-noselect file))
2177       (dolist (a addresses)
2178         (when (stringp a)
2179           (goto-char (point-min))
2180           (if (re-search-forward (regexp-quote a) nil t)
2181               ;; found the address
2182               (when remove
2183                 (spam-kill-whole-line))
2184             ;; else, the address was not found
2185             (unless remove
2186               (goto-char (point-max))
2187               (unless (bobp)
2188                 (insert "\n"))
2189               (insert a "\n")))))
2190       (save-buffer))))
2191
2192 (defun spam-filelist-build-cache (type)
2193   (let ((cache (if (eq type 'spam-use-blacklist)
2194                    spam-blacklist-cache
2195                  spam-whitelist-cache))
2196         parsed-cache)
2197     (unless (gethash type spam-caches)
2198       (while cache
2199         (let ((address (pop cache)))
2200           (unless (zerop (length address)) ; 0 for a nil address too
2201             (setq address (regexp-quote address))
2202             ;; fix regexp-quote's treatment of user-intended regexes
2203             (while (string-match "\\\\\\*" address)
2204               (setq address (replace-match ".*" t t address))))
2205           (push address parsed-cache)))
2206       (puthash type parsed-cache spam-caches))))
2207
2208 (defun spam-filelist-check-cache (type from)
2209   (when (stringp from)
2210     (spam-filelist-build-cache type)
2211     (let (found)
2212       (dolist (address (gethash type spam-caches))
2213         (when (and address (string-match address from))
2214           (setq found t)
2215           (return)))
2216       found)))
2217
2218 ;;; returns t if the sender is in the whitelist, nil or
2219 ;;; spam-split-group otherwise
2220 (defun spam-check-whitelist ()
2221   ;; FIXME!  Should it detect when file timestamps change?
2222   (unless spam-whitelist-cache
2223     (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
2224   (if (spam-from-listed-p 'spam-use-whitelist)
2225       t
2226     (if spam-use-whitelist-exclusive
2227         spam-split-group
2228       nil)))
2229
2230 (defun spam-check-blacklist ()
2231   ;; FIXME!  Should it detect when file timestamps change?
2232   (unless spam-blacklist-cache
2233     (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
2234   (and (spam-from-listed-p 'spam-use-blacklist)
2235        spam-split-group))
2236
2237 (defun spam-parse-list (file)
2238   (when (file-readable-p file)
2239     (let (contents address)
2240       (with-temp-buffer
2241         (insert-file-contents file)
2242         (while (not (eobp))
2243           (setq address (buffer-substring (point) (point-at-eol)))
2244           (forward-line 1)
2245           ;; insert the e-mail address if detected, otherwise the raw data
2246           (unless (zerop (length address))
2247             (let ((pure-address (nth 1 (gnus-extract-address-components address))))
2248               (push (or pure-address address) contents)))))
2249       (nreverse contents))))
2250
2251 (defun spam-from-listed-p (type)
2252   (let ((from (message-fetch-field "from"))
2253         found)
2254     (spam-filelist-check-cache type from)))
2255
2256 (defun spam-filelist-register-routine (articles blacklist &optional unregister)
2257   (let ((de-symbol (if blacklist 'spam-use-whitelist 'spam-use-blacklist))
2258         (declassification (if blacklist 'ham 'spam))
2259         (enter-function
2260          (if blacklist 'spam-enter-blacklist 'spam-enter-whitelist))
2261         (remove-function
2262          (if blacklist 'spam-enter-whitelist 'spam-enter-blacklist))
2263         from addresses unregister-list article-unregister-list)
2264     (dolist (article articles)
2265       (let ((from (spam-fetch-field-from-fast article))
2266             (id (spam-fetch-field-message-id-fast article))
2267             sender-ignored)
2268         (when (stringp from)
2269           (dolist (ignore-regex spam-blacklist-ignored-regexes)
2270             (when (and (not sender-ignored)
2271                        (stringp ignore-regex)
2272                        (string-match ignore-regex from))
2273               (setq sender-ignored t)))
2274           ;; remember the messages we need to unregister, unless remove is set
2275           (when (and
2276                  (null unregister)
2277                  (spam-log-unregistration-needed-p
2278                   id 'process declassification de-symbol))
2279             (push article article-unregister-list)
2280             (push from unregister-list))
2281           (unless sender-ignored
2282             (push from addresses)))))
2283
2284     (if unregister
2285         (funcall enter-function addresses t) ; unregister all these addresses
2286       ;; else, register normally and unregister what we need to
2287       (funcall remove-function unregister-list t)
2288       (dolist (article article-unregister-list)
2289         (spam-log-undo-registration
2290          (spam-fetch-field-message-id-fast article)
2291          'process
2292          declassification
2293          de-symbol))
2294       (funcall enter-function addresses nil))))
2295
2296 (defun spam-blacklist-unregister-routine (articles)
2297   (spam-blacklist-register-routine articles t))
2298
2299 (defun spam-blacklist-register-routine (articles &optional unregister)
2300   (spam-filelist-register-routine articles t unregister))
2301
2302 (defun spam-whitelist-unregister-routine (articles)
2303   (spam-whitelist-register-routine articles t))
2304
2305 (defun spam-whitelist-register-routine (articles &optional unregister)
2306   (spam-filelist-register-routine articles nil unregister))
2307
2308 ;;}}}
2309
2310 ;;{{{ Spam-report glue (gmane and resend reporting)
2311 (defun spam-report-gmane-register-routine (articles)
2312   (when articles
2313     (apply 'spam-report-gmane articles)))
2314
2315 (defun spam-report-resend-register-ham-routine (articles)
2316   (spam-report-resend-register-routine articles t))
2317
2318 (defun spam-report-resend-register-routine (articles &optional ham)
2319   (let* ((resend-to-gp 
2320           (if ham
2321               (gnus-parameter-ham-resend-to gnus-newsgroup-name)
2322             (gnus-parameter-spam-resend-to gnus-newsgroup-name)))
2323          (spam-report-resend-to (or (car-safe resend-to-gp)
2324                                     spam-report-resend-to)))
2325     (spam-report-resend articles ham)))
2326
2327 ;;}}}
2328
2329 ;;{{{ Bogofilter
2330 (defun spam-check-bogofilter-headers (&optional score)
2331   (let ((header (message-fetch-field spam-bogofilter-header)))
2332     (when header                        ; return nil when no header
2333       (if score                         ; scoring mode
2334           (if (string-match "spamicity=\\([0-9.]+\\)" header)
2335               (match-string 1 header)
2336             "0")
2337         ;; spam detection mode
2338         (when (string-match spam-bogofilter-bogosity-positive-spam-header
2339                             header)
2340           spam-split-group)))))
2341
2342 ;; return something sensible if the score can't be determined
2343 (defun spam-bogofilter-score (&optional recheck)
2344   "Get the Bogofilter spamicity score"
2345   (interactive "P")
2346   (save-window-excursion
2347     (gnus-summary-show-article t)
2348     (set-buffer gnus-article-buffer)
2349     (let ((score (or (unless recheck
2350                        (spam-check-bogofilter-headers t))
2351                      (spam-check-bogofilter t))))
2352       (gnus-summary-show-article)
2353       (message "Spamicity score %s" score)
2354       (or score "0"))))
2355
2356 (defun spam-verify-bogofilter ()
2357   "Verify the Bogofilter version is sufficient."
2358   (when (string-match "^bogofilter version 0\\.\\([0-9]\\|1[01]\\)\\."
2359                       (shell-command-to-string 
2360                        (format "%s -sV" spam-bogofilter-path)))))
2361
2362 (defun spam-check-bogofilter (&optional score)
2363   "Check the Bogofilter backend for the classification of this message."
2364   (if (spam-verify-bogofilter)
2365       (let ((article-buffer-name (buffer-name))
2366             (db spam-bogofilter-database-directory)
2367             return)
2368         (with-temp-buffer
2369           (let ((temp-buffer-name (buffer-name)))
2370             (save-excursion
2371               (set-buffer article-buffer-name)
2372               (apply 'call-process-region
2373                      (point-min) (point-max)
2374                      spam-bogofilter-path
2375                      nil temp-buffer-name nil
2376                      (if db `("-d" ,db "-v") `("-v"))))
2377             (setq return (spam-check-bogofilter-headers score))))
2378         return)
2379     (gnus-error "`spam.el' doesnt support obsolete bogofilter versions")))
2380
2381 (defun spam-bogofilter-register-with-bogofilter (articles
2382                                                  spam
2383                                                  &optional unregister)
2384   "Register an article, given as a string, as spam or non-spam."
2385   (if (spam-verify-bogofilter)
2386       (dolist (article articles)
2387         (let ((article-string (spam-get-article-as-string article))
2388               (db spam-bogofilter-database-directory)
2389               (switch (if unregister
2390                           (if spam
2391                               spam-bogofilter-spam-strong-switch
2392                             spam-bogofilter-ham-strong-switch)
2393                         (if spam
2394                             spam-bogofilter-spam-switch
2395                           spam-bogofilter-ham-switch))))
2396           (when (stringp article-string)
2397             (with-temp-buffer
2398               (insert article-string)
2399               
2400               (apply 'call-process-region
2401                      (point-min) (point-max)
2402                      spam-bogofilter-path
2403                      nil nil nil switch
2404                      (if db `("-d" ,db "-v") `("-v")))))))
2405     (gnus-error "`spam.el' doesnt support obsolete bogofilter versions")))
2406
2407 (defun spam-bogofilter-register-spam-routine (articles &optional unregister)
2408   (spam-bogofilter-register-with-bogofilter articles t unregister))
2409
2410 (defun spam-bogofilter-unregister-spam-routine (articles)
2411   (spam-bogofilter-register-spam-routine articles t))
2412
2413 (defun spam-bogofilter-register-ham-routine (articles &optional unregister)
2414   (spam-bogofilter-register-with-bogofilter articles nil unregister))
2415
2416 (defun spam-bogofilter-unregister-ham-routine (articles)
2417   (spam-bogofilter-register-ham-routine articles t))
2418
2419
2420 ;;}}}
2421
2422 ;;{{{ spamoracle
2423 (defun spam-check-spamoracle ()
2424   "Run spamoracle on an article to determine whether it's spam."
2425   (let ((article-buffer-name (buffer-name)))
2426     (with-temp-buffer
2427       (let ((temp-buffer-name (buffer-name)))
2428         (save-excursion
2429           (set-buffer article-buffer-name)
2430           (let ((status
2431                  (apply 'call-process-region
2432                         (point-min) (point-max)
2433                         spam-spamoracle-binary
2434                         nil temp-buffer-name nil
2435                         (if spam-spamoracle-database
2436                             `("-f" ,spam-spamoracle-database "mark")
2437                           '("mark")))))
2438             (if (eq 0 status)
2439                 (progn
2440                   (set-buffer temp-buffer-name)
2441                   (goto-char (point-min))
2442                   (when (re-search-forward "^X-Spam: yes;" nil t)
2443                     spam-split-group))
2444               (error "Error running spamoracle: %s" status))))))))
2445
2446 (defun spam-spamoracle-learn (articles article-is-spam-p &optional unregister)
2447   "Run spamoracle in training mode."
2448   (with-temp-buffer
2449     (let ((temp-buffer-name (buffer-name)))
2450       (save-excursion
2451         (goto-char (point-min))
2452         (dolist (article articles)
2453           (insert (spam-get-article-as-string article)))
2454         (let* ((arg (if (spam-xor unregister article-is-spam-p)
2455                         "-spam"
2456                       "-good"))
2457                (status
2458                 (apply 'call-process-region
2459                        (point-min) (point-max)
2460                        spam-spamoracle-binary
2461                        nil temp-buffer-name nil
2462                        (if spam-spamoracle-database
2463                            `("-f" ,spam-spamoracle-database
2464                              "add" ,arg)
2465                          `("add" ,arg)))))
2466           (unless (eq 0 status)
2467             (error "Error running spamoracle: %s" status)))))))
2468
2469 (defun spam-spamoracle-learn-ham (articles &optional unregister)
2470   (spam-spamoracle-learn articles nil unregister))
2471
2472 (defun spam-spamoracle-unlearn-ham (articles &optional unregister)
2473   (spam-spamoracle-learn-ham articles t))
2474
2475 (defun spam-spamoracle-learn-spam (articles &optional unregister)
2476   (spam-spamoracle-learn articles t unregister))
2477
2478 (defun spam-spamoracle-unlearn-spam (articles &optional unregister)
2479   (spam-spamoracle-learn-spam articles t))
2480
2481 ;;}}}
2482
2483 ;;{{{ SpamAssassin
2484 ;;; based mostly on the bogofilter code
2485 (defun spam-check-spamassassin-headers (&optional score)
2486   "Check the SpamAssassin headers for the classification of this message."
2487   (if score                             ; scoring mode
2488       (let ((header (message-fetch-field spam-spamassassin-spam-status-header)))
2489         (when header
2490           (if (string-match "hits=\\(-?[0-9.]+\\)" header)
2491               (match-string 1 header)
2492             "0")))
2493     ;; spam detection mode
2494     (let ((header (message-fetch-field spam-spamassassin-spam-flag-header)))
2495           (when header                  ; return nil when no header
2496             (when (string-match spam-spamassassin-positive-spam-flag-header
2497                                 header)
2498               spam-split-group)))))
2499
2500 (defun spam-check-spamassassin (&optional score)
2501   "Check the SpamAssassin backend for the classification of this message."
2502   (let ((article-buffer-name (buffer-name)))
2503     (with-temp-buffer
2504       (let ((temp-buffer-name (buffer-name)))
2505         (save-excursion
2506           (set-buffer article-buffer-name)
2507           (apply 'call-process-region
2508                  (point-min) (point-max) spam-spamassassin-path
2509                  nil temp-buffer-name nil spam-spamassassin-arguments))
2510         ;; check the return now (we're back in the temp buffer)
2511         (goto-char (point-min))
2512         (spam-check-spamassassin-headers score)))))
2513
2514 ;; return something sensible if the score can't be determined
2515 (defun spam-spamassassin-score (&optional recheck)
2516   "Get the SpamAssassin score"
2517   (interactive "P")
2518   (save-window-excursion
2519     (gnus-summary-show-article t)
2520     (set-buffer gnus-article-buffer)
2521     (let ((score (or (unless recheck
2522                        (spam-check-spamassassin-headers t))
2523                      (spam-check-spamassassin t))))
2524       (gnus-summary-show-article)
2525       (message "SpamAssassin score %s" score)
2526       (or score "0"))))
2527
2528 (defun spam-spamassassin-register-with-sa-learn (articles spam
2529                                                  &optional unregister)
2530   "Register articles with spamassassin's sa-learn as spam or non-spam."
2531   (if articles
2532       (let ((action (if unregister spam-sa-learn-unregister-switch
2533                       (if spam spam-sa-learn-spam-switch
2534                         spam-sa-learn-ham-switch)))
2535             (summary-buffer-name (buffer-name)))
2536         (with-temp-buffer
2537           ;; group the articles into mbox format
2538           (dolist (article articles)
2539             (let (article-string)
2540               (save-excursion
2541                 (set-buffer summary-buffer-name)
2542                 (setq article-string (spam-get-article-as-string article)))
2543               (when (stringp article-string)
2544                 (insert "From \n") ; mbox separator (sa-learn only checks the
2545                                    ; first five chars, so we can get away with
2546                                    ; a bogus line))
2547                 (insert article-string)
2548                 (insert "\n"))))
2549           ;; call sa-learn on all messages at the same time
2550           (apply 'call-process-region
2551                  (point-min) (point-max)
2552                  spam-sa-learn-path
2553                  nil nil nil "--mbox"
2554                  (if spam-sa-learn-rebuild
2555                      (list action)
2556                    `("--no-rebuild" ,action)))))))
2557
2558 (defun spam-spamassassin-register-spam-routine (articles &optional unregister)
2559   (spam-spamassassin-register-with-sa-learn articles t unregister))
2560
2561 (defun spam-spamassassin-register-ham-routine (articles &optional unregister)
2562   (spam-spamassassin-register-with-sa-learn articles nil unregister))
2563
2564 (defun spam-spamassassin-unregister-spam-routine (articles)
2565   (spam-spamassassin-register-with-sa-learn articles t t))
2566
2567 (defun spam-spamassassin-unregister-ham-routine (articles)
2568   (spam-spamassassin-register-with-sa-learn articles nil t))
2569
2570 ;;}}}
2571
2572 ;;{{{ Bsfilter
2573 ;;; based mostly on the bogofilter code
2574 (defun spam-check-bsfilter-headers (&optional score)
2575   (if score
2576       (or (nnmail-fetch-field spam-bsfilter-probability-header)
2577           "0")
2578     (let ((header (nnmail-fetch-field spam-bsfilter-header)))
2579       (when header ; return nil when no header
2580         (when (string-match "YES" header)
2581           spam-split-group)))))
2582
2583 ;; return something sensible if the score can't be determined
2584 (defun spam-bsfilter-score (&optional recheck)
2585   "Get the Bsfilter spamicity score"
2586   (interactive "P")
2587   (save-window-excursion
2588     (gnus-summary-show-article t)
2589     (set-buffer gnus-article-buffer)
2590     (let ((score (or (unless recheck
2591                        (spam-check-bsfilter-headers t))
2592                      (spam-check-bsfilter t))))
2593       (gnus-summary-show-article)
2594       (message "Spamicity score %s" score)
2595       (or score "0"))))
2596
2597 (defun spam-check-bsfilter (&optional score)
2598   "Check the Bsfilter backend for the classification of this message"
2599   (let ((article-buffer-name (buffer-name))
2600         (dir spam-bsfilter-database-directory)
2601         return)
2602     (with-temp-buffer
2603       (let ((temp-buffer-name (buffer-name)))
2604         (save-excursion
2605           (set-buffer article-buffer-name)
2606           (apply 'call-process-region
2607                  (point-min) (point-max)
2608                  spam-bsfilter-path
2609                  nil temp-buffer-name nil
2610                  "--pipe"
2611                  "--insert-flag"
2612                  "--insert-probability"
2613                  (when dir
2614                    (list "--homedir" dir))))
2615         (setq return (spam-check-bsfilter-headers score))))
2616     return))
2617
2618 (defun spam-bsfilter-register-with-bsfilter (articles
2619                                              spam
2620                                              &optional unregister)
2621   "Register an article, given as a string, as spam or non-spam."
2622   (dolist (article articles)
2623     (let ((article-string (spam-get-article-as-string article))
2624           (switch (if unregister
2625                       (if spam
2626                           spam-bsfilter-spam-strong-switch
2627                         spam-bsfilter-ham-strong-switch)
2628                     (if spam
2629                         spam-bsfilter-spam-switch
2630                       spam-bsfilter-ham-switch))))
2631       (when (stringp article-string)
2632         (with-temp-buffer
2633           (insert article-string)
2634           (apply 'call-process-region
2635                  (point-min) (point-max)
2636                  spam-bsfilter-path
2637                  nil nil nil switch
2638                  "--update"
2639                  (when spam-bsfilter-database-directory
2640                    (list "--homedir"
2641                          spam-bsfilter-database-directory))))))))
2642
2643 (defun spam-bsfilter-register-spam-routine (articles &optional unregister)
2644   (spam-bsfilter-register-with-bsfilter articles t unregister))
2645
2646 (defun spam-bsfilter-unregister-spam-routine (articles)
2647   (spam-bsfilter-register-spam-routine articles t))
2648
2649 (defun spam-bsfilter-register-ham-routine (articles &optional unregister)
2650   (spam-bsfilter-register-with-bsfilter articles nil unregister))
2651
2652 (defun spam-bsfilter-unregister-ham-routine (articles)
2653   (spam-bsfilter-register-ham-routine articles t))
2654
2655 ;;}}}
2656
2657 ;;{{{ CRM114 Mailfilter
2658 (defun spam-check-crm114-headers (&optional score)
2659   (let ((header (message-fetch-field spam-crm114-header)))
2660     (when header                        ; return nil when no header
2661       (if score                         ; scoring mode
2662           (if (string-match "( pR: \\([0-9.-]+\\)" header)
2663               (match-string 1 header)
2664             "0")
2665         ;; spam detection mode
2666         (when (string-match spam-crm114-positive-spam-header
2667                             header)
2668           spam-split-group)))))
2669
2670 ;; return something sensible if the score can't be determined
2671 (defun spam-crm114-score ()
2672   "Get the CRM114 Mailfilter pR"
2673   (interactive)
2674   (save-window-excursion
2675     (gnus-summary-show-article t)
2676     (set-buffer gnus-article-buffer)
2677     (let ((score (or (spam-check-crm114-headers t)
2678                      (spam-check-crm114 t))))
2679       (gnus-summary-show-article)
2680       (message "pR: %s" score)
2681       (or score "0"))))
2682
2683 (defun spam-check-crm114 (&optional score)
2684   "Check the CRM114 Mailfilter backend for the classification of this message"
2685   (let ((article-buffer-name (buffer-name))
2686         (db spam-crm114-database-directory)
2687         return)
2688     (with-temp-buffer
2689       (let ((temp-buffer-name (buffer-name)))
2690         (save-excursion
2691           (set-buffer article-buffer-name)
2692           (apply 'call-process-region
2693                  (point-min) (point-max)
2694                  spam-crm114-program
2695                  nil temp-buffer-name nil
2696                  (when db (list (concat "--fileprefix=" db)))))
2697         (setq return (spam-check-crm114-headers score))))
2698     return))
2699
2700 (defun spam-crm114-register-with-crm114 (articles
2701                                          spam
2702                                          &optional unregister)
2703   "Register an article, given as a string, as spam or non-spam."
2704   (dolist (article articles)
2705     (let ((article-string (spam-get-article-as-string article))
2706           (db spam-crm114-database-directory)
2707           (switch (if unregister
2708                       (if spam
2709                           spam-crm114-spam-strong-switch
2710                         spam-crm114-ham-strong-switch)
2711                     (if spam
2712                         spam-crm114-spam-switch
2713                       spam-crm114-ham-switch))))
2714       (when (stringp article-string)
2715         (with-temp-buffer
2716           (insert article-string)
2717
2718           (apply 'call-process-region
2719                  (point-min) (point-max)
2720                  spam-crm114-program
2721                  nil nil nil
2722                  (when db (list switch (concat "--fileprefix=" db)))))))))
2723
2724 (defun spam-crm114-register-spam-routine (articles &optional unregister)
2725   (spam-crm114-register-with-crm114 articles t unregister))
2726
2727 (defun spam-crm114-unregister-spam-routine (articles)
2728   (spam-crm114-register-spam-routine articles t))
2729
2730 (defun spam-crm114-register-ham-routine (articles &optional unregister)
2731   (spam-crm114-register-with-crm114 articles nil unregister))
2732
2733 (defun spam-crm114-unregister-ham-routine (articles)
2734   (spam-crm114-register-ham-routine articles t))
2735
2736 ;;}}}
2737
2738 ;;}}}
2739
2740 ;;{{{ Hooks
2741
2742 ;;;###autoload
2743 (defun spam-initialize (&rest symbols)
2744   "Install the spam.el hooks and do other initialization.
2745 When SYMBOLS is given, set those variables to t.  This is so you
2746 can call spam-initialize before you set spam-use-* variables on
2747 explicitly, and matters only if you need the extra headers
2748 installed through spam-necessary-extra-headers."
2749   (interactive)
2750
2751   (dolist (var symbols)
2752     (set var t))
2753
2754   (dolist (header (spam-necessary-extra-headers))
2755     (add-to-list 'nnmail-extra-headers header)
2756     (add-to-list 'gnus-extra-headers header))
2757
2758   (setq spam-install-hooks t)
2759   ;; TODO: How do we redo this every time spam-face is customized?
2760   (push '((eq mark gnus-spam-mark) . spam-face)
2761         gnus-summary-highlight)
2762   ;; Add hooks for loading and saving the spam stats
2763   (add-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
2764   (add-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
2765   (add-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
2766   (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
2767   (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
2768   (add-hook 'gnus-get-new-news-hook 'spam-setup-widening)
2769   (add-hook 'gnus-summary-prepared-hook 'spam-find-spam))
2770
2771 (defun spam-unload-hook ()
2772   "Uninstall the spam.el hooks"
2773   (interactive)
2774   (remove-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
2775   (remove-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
2776   (remove-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
2777   (remove-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
2778   (remove-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
2779   (remove-hook 'gnus-get-new-news-hook 'spam-setup-widening)
2780   (remove-hook 'gnus-summary-prepare-hook 'spam-find-spam))
2781
2782 (when spam-install-hooks
2783   (spam-initialize))
2784 ;;}}}
2785
2786 (provide 'spam)
2787
2788 ;;; arch-tag: 07e6e0ca-ab0a-4412-b445-1f6c72a4f27f
2789 ;;; spam.el ends here