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