(spam-registration-functions): add spam-use-ham-copy as a nil
[gnus] / lisp / spam.el
1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: network
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; This module addresses a few aspects of spam control under Gnus.  Page
27 ;;; breaks are used for grouping declarations and documentation relating to
28 ;;; each particular aspect.
29
30 ;;; The integration with Gnus is not yet complete.  See various `FIXME'
31 ;;; comments, below, for supplementary explanations or discussions.
32
33 ;;; Several TODO items are marked as such
34
35 ;; TODO: spam scores, detection of spam in newsgroups, cross-server splitting,
36 ;; remote processing, training through files
37
38 ;;; Code:
39
40 (eval-when-compile (require 'cl))
41
42 (require 'gnus-sum)
43
44 (require 'gnus-uu)                      ; because of key prefix issues
45 ;;; for the definitions of group content classification and spam processors
46 (require 'gnus)
47 (require 'message)              ;for the message-fetch-field functions
48
49 ;; for nnimap-split-download-body-default
50 (eval-when-compile (require 'nnimap))
51
52 ;; autoload query-dig
53 (eval-and-compile
54   (autoload 'query-dig "dig"))
55
56 ;; autoload spam-report
57 (eval-and-compile
58   (autoload 'spam-report-gmane "spam-report"))
59
60 ;; autoload gnus-registry
61 (eval-and-compile
62   (autoload 'gnus-registry-group-count "gnus-registry")
63   (autoload 'gnus-registry-add-group "gnus-registry")
64   (autoload 'gnus-registry-store-extra-entry "gnus-registry")
65   (autoload 'gnus-registry-fetch-extra "gnus-registry"))
66
67 ;; autoload query-dns
68 (eval-and-compile
69   (autoload 'query-dns "dns"))
70
71 ;;; Main parameters.
72
73 (defgroup spam nil
74   "Spam configuration.")
75
76 (defcustom spam-directory (nnheader-concat gnus-directory "spam/")
77   "Directory for spam whitelists and blacklists."
78   :type 'directory
79   :group 'spam)
80
81 (defcustom spam-move-spam-nonspam-groups-only t
82   "Whether spam should be moved in non-spam groups only.
83 When t, only ham and unclassified groups will have their spam moved
84 to the spam-process-destination.  When nil, spam will also be moved from
85 spam groups."
86   :type 'boolean
87   :group 'spam)
88
89 (defcustom spam-process-ham-in-nonham-groups nil
90   "Whether ham should be processed in non-ham groups."
91   :type 'boolean
92   :group 'spam)
93
94 (defcustom spam-log-to-registry nil
95   "Whether spam/ham processing should be logged in the registry."
96   :type 'boolean
97   :group 'spam)
98
99 (defcustom spam-split-symbolic-return nil
100   "Whether `spam-split' should work with symbols or group names."
101   :type 'boolean
102   :group 'spam)
103
104 (defcustom spam-split-symbolic-return-positive nil
105   "Whether `spam-split' should ALWAYS work with symbols or group names.
106 Do not set this if you use `spam-split' in a fancy split
107   method."
108   :type 'boolean
109   :group 'spam)
110
111 (defcustom spam-process-ham-in-spam-groups nil
112   "Whether ham should be processed in spam groups."
113   :type 'boolean
114   :group 'spam)
115
116 (defcustom spam-mark-only-unseen-as-spam t
117   "Whether only unseen articles should be marked as spam in spam groups.
118 When nil, all unread articles in a spam group are marked as
119 spam.  Set this if you want to leave an article unread in a spam group
120 without losing it to the automatic spam-marking process."
121   :type 'boolean
122   :group 'spam)
123
124 (defcustom spam-mark-ham-unread-before-move-from-spam-group nil
125   "Whether ham should be marked unread before it's moved.
126 The article is moved out of a spam group according to ham-process-destination.
127 This variable is an official entry in the international Longest Variable Name
128 Competition."
129   :type 'boolean
130   :group 'spam)
131
132 (defcustom spam-disable-spam-split-during-ham-respool nil
133   "Whether `spam-split' should be ignored while resplitting ham.
134 This is useful to prevent ham from ending up in the same spam
135 group after the resplit.  Don't set this to t if you have `spam-split' as the
136 last rule in your split configuration."
137   :type 'boolean
138   :group 'spam)
139
140 (defcustom spam-autodetect-recheck-messages nil
141   "Should spam.el recheck all meessages when autodetecting?
142 Normally this is nil, so only unseen messages will be checked."
143   :type 'boolean
144   :group 'spam)
145
146 (defcustom spam-whitelist (expand-file-name "whitelist" spam-directory)
147   "The location of the whitelist.
148 The file format is one regular expression per line.
149 The regular expression is matched against the address."
150   :type 'file
151   :group 'spam)
152
153 (defcustom spam-blacklist (expand-file-name "blacklist" spam-directory)
154   "The location of the blacklist.
155 The file format is one regular expression per line.
156 The regular expression is matched against the address."
157   :type 'file
158   :group 'spam)
159
160 (defcustom spam-use-dig t
161   "Whether `query-dig' should be used instead of `query-dns'."
162   :type 'boolean
163   :group 'spam)
164
165 (defcustom spam-use-blacklist nil
166   "Whether the blacklist should be used by `spam-split'."
167   :type 'boolean
168   :group 'spam)
169
170 (defcustom spam-blacklist-ignored-regexes nil
171   "Regular expressions that the blacklist should ignore."
172   :type '(repeat (regexp :tag "Regular expression to ignore when blacklisting"))
173   :group 'spam)
174
175 (defcustom spam-use-whitelist nil
176   "Whether the whitelist should be used by `spam-split'."
177   :type 'boolean
178   :group 'spam)
179
180 (defcustom spam-use-whitelist-exclusive nil
181   "Whether whitelist-exclusive should be used by `spam-split'.
182 Exclusive whitelisting means that all messages from senders not in the whitelist
183 are considered spam."
184   :type 'boolean
185   :group 'spam)
186
187 (defcustom spam-use-blackholes nil
188   "Whether blackholes should be used by `spam-split'."
189   :type 'boolean
190   :group 'spam)
191
192 (defcustom spam-use-hashcash nil
193   "Whether hashcash payments should be detected by `spam-split'."
194   :type 'boolean
195   :group 'spam)
196
197 (defcustom spam-use-regex-headers nil
198   "Whether a header regular expression match should be used by `spam-split'.
199 Also see the variables `spam-regex-headers-spam' and `spam-regex-headers-ham'."
200   :type 'boolean
201   :group 'spam)
202
203 (defcustom spam-use-regex-body nil
204   "Whether a body regular expression match should be used by `spam-split'.
205 Also see the variables `spam-regex-body-spam' and `spam-regex-body-ham'."
206   :type 'boolean
207   :group 'spam)
208
209 (defcustom spam-use-bogofilter-headers nil
210   "Whether bogofilter headers should be used by `spam-split'.
211 Enable this if you pre-process messages with Bogofilter BEFORE Gnus sees them."
212   :type 'boolean
213   :group 'spam)
214
215 (defcustom spam-use-bogofilter nil
216   "Whether bogofilter should be invoked by `spam-split'.
217 Enable this if you want Gnus to invoke Bogofilter on new messages."
218   :type 'boolean
219   :group 'spam)
220
221 (defcustom spam-use-BBDB nil
222   "Whether BBDB should be used by `spam-split'."
223   :type 'boolean
224   :group 'spam)
225
226 (defcustom spam-use-BBDB-exclusive nil
227   "Whether BBDB-exclusive should be used by `spam-split'.
228 Exclusive BBDB means that all messages from senders not in the BBDB are
229 considered spam."
230   :type 'boolean
231   :group 'spam)
232
233 (defcustom spam-use-ifile nil
234   "Whether ifile should be used by `spam-split'."
235   :type 'boolean
236   :group 'spam)
237
238 (defcustom spam-use-stat nil
239   "Whether `spam-stat' should be used by `spam-split'."
240   :type 'boolean
241   :group 'spam)
242
243 (defcustom spam-use-spamoracle nil
244   "Whether spamoracle should be used by `spam-split'."
245   :type 'boolean
246   :group 'spam)
247
248 (defcustom spam-use-spamassassin nil
249   "Whether spamassassin should be invoked by `spam-split'.
250 Enable this if you want Gnus to invoke SpamAssassin on new messages."
251   :type 'boolean
252   :group 'spam)
253
254 (defcustom spam-use-spamassassin-headers nil
255   "Whether spamassassin headers should be checked by `spam-split'.
256 Enable this if you pre-process messages with SpamAssassin BEFORE Gnus sees
257 them."
258   :type 'boolean
259   :group 'spam)
260
261 (defcustom spam-install-hooks (or
262                                spam-use-dig
263                                spam-use-blacklist
264                                spam-use-whitelist
265                                spam-use-whitelist-exclusive
266                                spam-use-blackholes
267                                spam-use-hashcash
268                                spam-use-regex-headers
269                                spam-use-regex-body
270                                spam-use-bogofilter
271                                spam-use-bogofilter-headers
272                                spam-use-spamassassin
273                                spam-use-spamassassin-headers
274                                spam-use-BBDB
275                                spam-use-BBDB-exclusive
276                                spam-use-ifile
277                                spam-use-stat
278                                spam-use-spamoracle)
279   "Whether the spam hooks should be installed.
280 Default to t if one of the spam-use-* variables is set."
281   :group 'spam
282   :type 'boolean)
283
284 (defcustom spam-split-group "spam"
285   "Group name where incoming spam should be put by `spam-split'."
286   :type 'string
287   :group 'spam)
288
289 ;;; TODO: deprecate this variable, it's confusing since it's a list of strings,
290 ;;; not regular expressions
291 (defcustom spam-junk-mailgroups (cons
292                                  spam-split-group
293                                  '("mail.junk" "poste.pourriel"))
294   "Mailgroups with spam contents.
295 All unmarked article in such group receive the spam mark on group entry."
296   :type '(repeat (string :tag "Group"))
297   :group 'spam)
298
299 (defcustom spam-blackhole-servers '("bl.spamcop.net" "relays.ordb.org"
300                                     "dev.null.dk" "relays.visi.com")
301   "List of blackhole servers."
302   :type '(repeat (string :tag "Server"))
303   :group 'spam)
304
305 (defcustom spam-blackhole-good-server-regex nil
306   "String matching IP addresses that should not be checked in the blackholes."
307   :type '(radio (const nil)
308                 (regexp :format "%t: %v\n" :size 0))
309   :group 'spam)
310
311 (defcustom spam-face 'gnus-splash-face
312   "Face for spam-marked articles."
313   :type 'face
314   :group 'spam)
315
316 (defcustom spam-regex-headers-spam '("^X-Spam-Flag: YES")
317   "Regular expression for positive header spam matches."
318   :type '(repeat (regexp :tag "Regular expression to match spam header"))
319   :group 'spam)
320
321 (defcustom spam-regex-headers-ham '("^X-Spam-Flag: NO")
322   "Regular expression for positive header ham matches."
323   :type '(repeat (regexp :tag "Regular expression to match ham header"))
324   :group 'spam)
325
326 (defcustom spam-regex-body-spam '()
327   "Regular expression for positive body spam matches."
328   :type '(repeat (regexp :tag "Regular expression to match spam body"))
329   :group 'spam)
330
331 (defcustom spam-regex-body-ham '()
332   "Regular expression for positive body ham matches."
333   :type '(repeat (regexp :tag "Regular expression to match ham body"))
334   :group 'spam)
335
336 (defgroup spam-ifile nil
337   "Spam ifile configuration."
338   :group 'spam)
339
340 (defcustom spam-ifile-path (executable-find "ifile")
341   "File path of the ifile executable program."
342   :type '(choice (file :tag "Location of ifile")
343                  (const :tag "ifile is not installed"))
344   :group 'spam-ifile)
345
346 (defcustom spam-ifile-database-path nil
347   "File path of the ifile database."
348   :type '(choice (file :tag "Location of the ifile database")
349                  (const :tag "Use the default"))
350   :group 'spam-ifile)
351
352 (defcustom spam-ifile-spam-category "spam"
353   "Name of the spam ifile category."
354   :type 'string
355   :group 'spam-ifile)
356
357 (defcustom spam-ifile-ham-category nil
358   "Name of the ham ifile category.
359 If nil, the current group name will be used."
360   :type '(choice (string :tag "Use a fixed category")
361                  (const :tag "Use the current group name"))
362   :group 'spam-ifile)
363
364 (defcustom spam-ifile-all-categories nil
365   "Whether the ifile check will return all categories, or just spam.
366 Set this to t if you want to use the `spam-split' invocation of ifile as
367 your main source of newsgroup names."
368   :type 'boolean
369   :group 'spam-ifile)
370
371 (defgroup spam-bogofilter nil
372   "Spam bogofilter configuration."
373   :group 'spam)
374
375 (defcustom spam-bogofilter-path (executable-find "bogofilter")
376   "File path of the Bogofilter executable program."
377   :type '(choice (file :tag "Location of bogofilter")
378                  (const :tag "Bogofilter is not installed"))
379   :group 'spam-bogofilter)
380
381 (defcustom spam-bogofilter-header "X-Bogosity"
382   "The header that Bogofilter inserts in messages."
383   :type 'string
384   :group 'spam-bogofilter)
385
386 (defcustom spam-bogofilter-spam-switch "-s"
387   "The switch that Bogofilter uses to register spam messages."
388   :type 'string
389   :group 'spam-bogofilter)
390
391 (defcustom spam-bogofilter-ham-switch "-n"
392   "The switch that Bogofilter uses to register ham messages."
393   :type 'string
394   :group 'spam-bogofilter)
395
396 (defcustom spam-bogofilter-spam-strong-switch "-S"
397   "The switch that Bogofilter uses to unregister ham messages."
398   :type 'string
399   :group 'spam-bogofilter)
400
401 (defcustom spam-bogofilter-ham-strong-switch "-N"
402   "The switch that Bogofilter uses to unregister spam messages."
403   :type 'string
404   :group 'spam-bogofilter)
405
406 (defcustom spam-bogofilter-bogosity-positive-spam-header "^\\(Yes\\|Spam\\)"
407   "The regex on `spam-bogofilter-header' for positive spam identification."
408   :type 'regexp
409   :group 'spam-bogofilter)
410
411 (defcustom spam-bogofilter-database-directory nil
412   "Directory path of the Bogofilter databases."
413   :type '(choice (directory
414                   :tag "Location of the Bogofilter database directory")
415                  (const :tag "Use the default"))
416   :group 'spam-bogofilter)
417
418 (defgroup spam-spamoracle nil
419   "Spam spamoracle configuration."
420   :group 'spam)
421
422 (defcustom spam-spamoracle-database nil
423   "Location of spamoracle database file.
424 When nil, use the default spamoracle database."
425   :type '(choice (directory :tag "Location of spamoracle database file.")
426                  (const :tag "Use the default"))
427   :group 'spam-spamoracle)
428
429 (defcustom spam-spamoracle-binary (executable-find "spamoracle")
430   "Location of the spamoracle binary."
431   :type '(choice (directory :tag "Location of the spamoracle binary")
432                  (const :tag "Use the default"))
433   :group 'spam-spamoracle)
434
435 (defgroup spam-spamassassin nil
436   "Spam SpamAssassin configuration."
437   :group 'spam)
438
439 (defcustom spam-spamassassin-path (executable-find "spamassassin")
440   "File path of the spamassassin executable program.
441 Hint: set this to \"spamc\" if you have spamd running.  See the spamc and
442 spamd man pages for more information on these programs."
443   :type '(choice (file :tag "Location of spamc")
444                  (const :tag "spamassassin is not installed"))
445   :group 'spam-spamassassin)
446
447 (defcustom spam-spamassassin-arguments ()
448   "Arguments to pass to the spamassassin executable.
449 This must be a list.  For example, `(\"-C\" \"configfile\")'."
450   :type '(restricted-sexp :match-alternatives (listp))
451   :group 'spam-spamassassin)
452
453 (defcustom spam-spamassassin-spam-flag-header "X-Spam-Flag"
454   "The header inserted by SpamAssassin to flag spam."
455   :type 'string
456   :group 'spam-spamassassin)
457
458 (defcustom spam-spamassassin-positive-spam-flag-header "YES"
459   "The regex on `spam-spamassassin-spam-flag-header' for positive spam
460 identification"
461   :type 'string
462   :group 'spam-spamassassin)
463
464 (defcustom spam-spamassassin-spam-status-header "X-Spam-Status"
465   "The header inserted by SpamAssassin, giving extended scoring information"
466   :type 'string
467   :group 'spam-spamassassin)
468
469 (defcustom spam-sa-learn-path (executable-find "sa-learn")
470   "File path of the sa-learn executable program."
471   :type '(choice (file :tag "Location of spamassassin")
472                  (const :tag "spamassassin is not installed"))
473   :group 'spam-spamassassin)
474
475 (defcustom spam-sa-learn-rebuild t
476   "Whether sa-learn should rebuild the database every time it is called
477 Enable this if you want sa-learn to rebuild the database automatically.  Doing
478 this will slightly increase the running time of the spam registration process.
479 If you choose not to do this, you will have to run \"sa-learn --rebuild\" in
480 order for SpamAssassin to recognize the new registered spam."
481   :type 'boolean
482   :group 'spam-spamassassin)
483
484 (defcustom spam-sa-learn-spam-switch "--spam"
485   "The switch that sa-learn uses to register spam messages"
486   :type 'string
487   :group 'spam-spamassassin)
488
489 (defcustom spam-sa-learn-ham-switch "--ham"
490   "The switch that sa-learn uses to register ham messages"
491   :type 'string
492   :group 'spam-spamassassin)
493
494 (defcustom spam-sa-learn-unregister-switch "--forget"
495   "The switch that sa-learn uses to unregister messages messages"
496   :type 'string
497   :group 'spam-spamassassin)
498
499 ;;; Key bindings for spam control.
500
501 (gnus-define-keys gnus-summary-mode-map
502   "St" spam-generic-score
503   "Sx" gnus-summary-mark-as-spam
504   "Mst" spam-generic-score
505   "Msx" gnus-summary-mark-as-spam
506   "\M-d" gnus-summary-mark-as-spam)
507
508 (defvar spam-cache-lookups t
509   "Whether spam.el will try to cache lookups using `spam-caches'.")
510
511 (defvar spam-caches (make-hash-table
512                      :size 10
513                      :test 'equal)
514   "Cache of spam detection entries.")
515
516 (defvar spam-old-ham-articles nil
517   "List of old ham articles, generated when a group is entered.")
518
519 (defvar spam-old-spam-articles nil
520   "List of old spam articles, generated when a group is entered.")
521
522 (defvar spam-split-disabled nil
523   "If non-nil, `spam-split' is disabled, and always returns nil.")
524
525 (defvar spam-split-last-successful-check nil
526   "Internal variable.
527 `spam-split' will set this to nil or a spam-use-XYZ check if it
528 finds ham or spam.")
529
530 ;; convenience functions
531 (defun spam-clear-cache (symbol)
532   "Clear the spam-caches entry for a check."
533   (remhash symbol spam-caches))
534
535 (defun spam-xor (a b)
536   "Logical A xor B."
537   (and (or a b) (not (and a b))))
538
539 (defun spam-group-ham-mark-p (group mark &optional spam)
540   "Checks if MARK is considered a ham mark in GROUP."
541   (when (stringp group)
542     (let* ((marks (spam-group-ham-marks group spam))
543            (marks (if (symbolp mark)
544                       marks
545                     (mapcar 'symbol-value marks))))
546       (memq mark marks))))
547
548 (defun spam-group-spam-mark-p (group mark)
549   "Checks if MARK is considered a spam mark in GROUP."
550   (spam-group-ham-mark-p group mark t))
551
552 (defun spam-group-ham-marks (group &optional spam)
553   "In GROUP, get all the ham marks."
554   (when (stringp group)
555     (let* ((marks (if spam
556                       (gnus-parameter-spam-marks group)
557                     (gnus-parameter-ham-marks group)))
558            (marks (car marks))
559            (marks (if (listp (car marks)) (car marks) marks)))
560       marks)))
561
562 (defun spam-group-spam-marks (group)
563   "In GROUP, get all the spam marks."
564   (spam-group-ham-marks group t))
565
566 (defun spam-group-spam-contents-p (group)
567   "Is GROUP a spam group?"
568   (if (stringp group)
569       (or (member group spam-junk-mailgroups)
570           (memq 'gnus-group-spam-classification-spam
571                 (gnus-parameter-spam-contents group)))
572     nil))
573
574 (defun spam-group-ham-contents-p (group)
575   "Is GROUP a ham group?"
576   (if (stringp group)
577       (memq 'gnus-group-spam-classification-ham
578             (gnus-parameter-spam-contents group))
579     nil))
580
581 (defvar spam-list-of-processors
582   '((gnus-group-spam-exit-processor-report-gmane spam spam-use-gmane)
583     (gnus-group-spam-exit-processor-bogofilter   spam spam-use-bogofilter)
584     (gnus-group-spam-exit-processor-blacklist    spam spam-use-blacklist)
585     (gnus-group-spam-exit-processor-ifile        spam spam-use-ifile)
586     (gnus-group-spam-exit-processor-stat         spam spam-use-stat)
587     (gnus-group-spam-exit-processor-spamoracle   spam spam-use-spamoracle)
588     (gnus-group-spam-exit-processor-spamassassin spam spam-use-spamassassin)
589     (gnus-group-ham-exit-processor-ifile         ham spam-use-ifile)
590     (gnus-group-ham-exit-processor-bogofilter    ham spam-use-bogofilter)
591     (gnus-group-ham-exit-processor-stat          ham spam-use-stat)
592     (gnus-group-ham-exit-processor-whitelist     ham spam-use-whitelist)
593     (gnus-group-ham-exit-processor-BBDB          ham spam-use-BBDB)
594     (gnus-group-ham-exit-processor-copy          ham spam-use-ham-copy)
595     (gnus-group-ham-exit-processor-spamassassin  ham spam-use-spamassassin)
596     (gnus-group-ham-exit-processor-spamoracle    ham spam-use-spamoracle))
597   "The `spam-list-of-processors' list.
598 This list contains pairs associating a ham/spam exit processor
599 variable with a classification and a spam-use-* variable.")
600
601 (defun spam-group-processor-p (group processor)
602   (if (and (stringp group)
603            (symbolp processor))
604       (or (member processor (nth 0 (gnus-parameter-spam-process group)))
605           (spam-group-processor-multiple-p
606            group
607            (cdr-safe (assoc processor spam-list-of-processors))))
608     nil))
609
610 (defun spam-group-processor-multiple-p (group processor-info)
611   (let* ((classification (nth 0 processor-info))
612          (check (nth 1 processor-info))
613          (parameters (nth 0 (gnus-parameter-spam-process group)))
614          found)
615     (dolist (parameter parameters)
616       (when (and (null found)
617                  (listp parameter)
618                  (eq classification (nth 0 parameter))
619                  (eq check (nth 1 parameter)))
620         (setq found t)))
621     found))
622
623 (defun spam-group-spam-processor-report-gmane-p (group)
624   (spam-group-processor-p group 'gnus-group-spam-exit-processor-report-gmane))
625
626 (defun spam-group-spam-processor-bogofilter-p (group)
627   (spam-group-processor-p group 'gnus-group-spam-exit-processor-bogofilter))
628
629 (defun spam-group-spam-processor-blacklist-p (group)
630   (spam-group-processor-p group 'gnus-group-spam-exit-processor-blacklist))
631
632 (defun spam-group-spam-processor-ifile-p (group)
633   (spam-group-processor-p group 'gnus-group-spam-exit-processor-ifile))
634
635 (defun spam-group-ham-processor-ifile-p (group)
636   (spam-group-processor-p group 'gnus-group-ham-exit-processor-ifile))
637
638 (defun spam-group-spam-processor-spamoracle-p (group)
639   (spam-group-processor-p group 'gnus-group-spam-exit-processor-spamoracle))
640
641 (defun spam-group-ham-processor-bogofilter-p (group)
642   (spam-group-processor-p group 'gnus-group-ham-exit-processor-bogofilter))
643
644 (defun spam-group-spam-processor-stat-p (group)
645   (spam-group-processor-p group 'gnus-group-spam-exit-processor-stat))
646
647 (defun spam-group-ham-processor-stat-p (group)
648   (spam-group-processor-p group 'gnus-group-ham-exit-processor-stat))
649
650 (defun spam-group-ham-processor-whitelist-p (group)
651   (spam-group-processor-p group 'gnus-group-ham-exit-processor-whitelist))
652
653 (defun spam-group-ham-processor-BBDB-p (group)
654   (spam-group-processor-p group 'gnus-group-ham-exit-processor-BBDB))
655
656 (defun spam-group-ham-processor-copy-p (group)
657   (spam-group-processor-p group 'gnus-group-ham-exit-processor-copy))
658
659 (defun spam-group-ham-processor-spamoracle-p (group)
660   (spam-group-processor-p group 'gnus-group-ham-exit-processor-spamoracle))
661
662 (defun spam-report-articles-gmane (n)
663   "Report the current message as spam.
664 Respects the process/prefix convention."
665   (interactive "P")
666   (dolist (article (gnus-summary-work-articles n))
667     (gnus-summary-remove-process-mark article)
668     (spam-report-gmane article)))
669
670 (defun spam-generic-score ()
671   (interactive)
672   "Invoke whatever scoring method we can."
673   (if (or
674        spam-use-spamassassin
675        spam-use-spamassassin-headers)
676       (spam-spamassassin-score)
677     (spam-bogofilter-score)))
678
679 ;;; Summary entry and exit processing.
680
681 (defun spam-summary-prepare ()
682   (setq spam-old-ham-articles
683         (spam-list-articles gnus-newsgroup-articles 'ham))
684   (setq spam-old-spam-articles
685         (spam-list-articles gnus-newsgroup-articles 'spam))
686   (spam-mark-junk-as-spam-routine))
687
688 ;; The spam processors are invoked for any group, spam or ham or neither
689 (defun spam-summary-prepare-exit ()
690   (unless gnus-group-is-exiting-without-update-p
691     (gnus-message 6 "Exiting summary buffer and applying spam rules")
692
693     ;; first of all, unregister any articles that are no longer ham or spam
694     ;; we have to iterate over the processors, or else we'll be too slow
695     (dolist (classification '(spam ham))
696       (let* ((old-articles (if (eq classification 'spam)
697                                spam-old-spam-articles
698                              spam-old-ham-articles))
699              (new-articles (spam-list-articles
700                             gnus-newsgroup-articles
701                             classification))
702              (changed-articles (gnus-set-difference new-articles old-articles)))
703         ;; now that we have the changed articles, we go through the processors
704         (dolist (processor-param spam-list-of-processors)
705           (let ((processor (nth 0 processor-param))
706                 (processor-classification (nth 1 processor-param))
707                 (check (nth 2 processor-param))
708                 unregister-list)
709             (dolist (article changed-articles)
710               (let ((id (spam-fetch-field-message-id-fast article)))
711                 (when (spam-log-unregistration-needed-p
712                        id 'process classification check)
713                   (push article unregister-list))))
714             ;; call spam-register-routine with specific articles to unregister,
715             ;; when there are articles to unregister and the check is enabled
716             (when (and unregister-list (symbol-value check))
717               (spam-register-routine classification check t unregister-list))))))
718
719     ;; find all the spam processors applicable to this group
720     (dolist (processor-param spam-list-of-processors)
721       (let ((processor (nth 0 processor-param))
722             (classification (nth 1 processor-param))
723             (check (nth 2 processor-param)))
724         (when (and (eq 'spam classification)
725                    (spam-group-processor-p gnus-newsgroup-name processor))
726           (spam-register-routine classification check))))
727
728     (if spam-move-spam-nonspam-groups-only
729         (when (not (spam-group-spam-contents-p gnus-newsgroup-name))
730           (spam-mark-spam-as-expired-and-move-routine
731            (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
732       (gnus-message 5 "Marking spam as expired and moving it to %s"
733                     gnus-newsgroup-name)
734       (spam-mark-spam-as-expired-and-move-routine
735        (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
736
737     ;; now we redo spam-mark-spam-as-expired-and-move-routine to only
738     ;; expire spam, in case the above did not expire them
739     (gnus-message 5 "Marking spam as expired without moving it")
740     (spam-mark-spam-as-expired-and-move-routine nil)
741
742     (when (or (spam-group-ham-contents-p gnus-newsgroup-name)
743               (and (spam-group-spam-contents-p gnus-newsgroup-name)
744                    spam-process-ham-in-spam-groups)
745               spam-process-ham-in-nonham-groups)
746       ;; find all the ham processors applicable to this group
747       (dolist (processor-param spam-list-of-processors)
748         (let ((processor (nth 0 processor-param))
749               (classification (nth 1 processor-param))
750               (check (nth 2 processor-param)))
751           (when (and (eq 'ham classification)
752                      (spam-group-processor-p gnus-newsgroup-name processor))
753             (spam-register-routine classification check)))))
754
755     (when (spam-group-ham-processor-copy-p gnus-newsgroup-name)
756       (gnus-message 5 "Copying ham")
757       (spam-ham-copy-routine
758        (gnus-parameter-ham-process-destination gnus-newsgroup-name)))
759
760     ;; now move all ham articles out of spam groups
761     (when (spam-group-spam-contents-p gnus-newsgroup-name)
762       (gnus-message 5 "Moving ham messages from spam group")
763       (spam-ham-move-routine
764        (gnus-parameter-ham-process-destination gnus-newsgroup-name))))
765
766   (setq spam-old-ham-articles nil)
767   (setq spam-old-spam-articles nil))
768
769 (defun spam-mark-junk-as-spam-routine ()
770   ;; check the global list of group names spam-junk-mailgroups and the
771   ;; group parameters
772   (when (spam-group-spam-contents-p gnus-newsgroup-name)
773     (gnus-message 5 "Marking %s articles as spam"
774                   (if spam-mark-only-unseen-as-spam
775                       "unseen"
776                     "unread"))
777     (let ((articles (if spam-mark-only-unseen-as-spam
778                         gnus-newsgroup-unseen
779                       gnus-newsgroup-unreads)))
780       (dolist (article articles)
781         (gnus-summary-mark-article article gnus-spam-mark)))))
782
783 (defun spam-mark-spam-as-expired-and-move-routine (&rest groups)
784   (if (and (car-safe groups) (listp (car-safe groups)))
785       (apply 'spam-mark-spam-as-expired-and-move-routine (car groups))
786     (gnus-summary-kill-process-mark)
787     (let ((articles gnus-newsgroup-articles)
788           (backend-supports-deletions
789            (gnus-check-backend-function
790             'request-move-article gnus-newsgroup-name))
791           article tomove deletep)
792       (dolist (article articles)
793         (when (eq (gnus-summary-article-mark article) gnus-spam-mark)
794           (gnus-summary-mark-article article gnus-expirable-mark)
795           (push article tomove)))
796
797       ;; now do the actual copies
798       (dolist (group groups)
799         (when (and tomove
800                    (stringp group))
801           (dolist (article tomove)
802             (gnus-summary-set-process-mark article))
803           (when tomove
804             (if (or (not backend-supports-deletions)
805                     (> (length groups) 1))
806                 (progn
807                   (gnus-summary-copy-article nil group)
808                   (setq deletep t))
809               (gnus-summary-move-article nil group)))))
810
811       ;; now delete the articles, if there was a copy done, and the
812       ;; backend allows it
813       (when (and deletep backend-supports-deletions)
814         (dolist (article tomove)
815           (gnus-summary-set-process-mark article))
816         (when tomove
817           (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
818             (gnus-summary-delete-article nil))))
819
820       (gnus-summary-yank-process-mark))))
821
822 (defun spam-ham-copy-or-move-routine (copy groups)
823   (gnus-summary-kill-process-mark)
824   (let ((todo (spam-list-articles gnus-newsgroup-articles 'ham))
825         (backend-supports-deletions
826          (gnus-check-backend-function
827           'request-move-article gnus-newsgroup-name))
828         (respool-method (gnus-find-method-for-group gnus-newsgroup-name))
829         article mark todo deletep respool)
830
831     (when (member 'respool groups)
832       (setq respool t)                  ; boolean for later
833       (setq groups '("fake"))) ; when respooling, groups are dynamic so fake it
834
835     ;; now do the actual move
836     (dolist (group groups)
837       (when (and todo (stringp group))
838         (dolist (article todo)
839           (when spam-mark-ham-unread-before-move-from-spam-group
840             (gnus-summary-mark-article article gnus-unread-mark))
841           (gnus-summary-set-process-mark article))
842
843         (if respool                        ; respooling is with a "fake" group
844             (let ((spam-split-disabled
845                    (or spam-split-disabled
846                        spam-disable-spam-split-during-ham-respool)))
847               (gnus-summary-respool-article nil respool-method))
848           (if (or (not backend-supports-deletions) ; else, we are not respooling
849                   (> (length groups) 1))
850               (progn                ; if copying, copy and set deletep
851                 (gnus-summary-copy-article nil group)
852                 (setq deletep t))
853             (gnus-summary-move-article nil group))))) ; else move articles
854
855     ;; now delete the articles, unless a) copy is t, and there was a copy done
856     ;;                                 b) a move was done to a single group
857     ;;                                 c) backend-supports-deletions is nil
858     (unless copy
859       (when (and deletep backend-supports-deletions)
860         (dolist (article todo)
861           (gnus-summary-set-process-mark article))
862         (when todo
863           (let ((gnus-novice-user nil)) ; don't ask me if I'm sure
864             (gnus-summary-delete-article nil))))))
865
866   (gnus-summary-yank-process-mark))
867
868 (defun spam-ham-copy-routine (&rest groups)
869   (if (and (car-safe groups) (listp (car-safe groups)))
870       (apply 'spam-ham-copy-routine (car groups))
871     (spam-ham-copy-or-move-routine t groups)))
872
873 (defun spam-ham-move-routine (&rest groups)
874   (if (and (car-safe groups) (listp (car-safe groups)))
875       (apply 'spam-ham-move-routine (car groups))
876     (spam-ham-copy-or-move-routine nil groups)))
877
878 (defun spam-get-article-as-string (article)
879   (when (numberp article)
880     (with-temp-buffer
881       (gnus-request-article-this-buffer
882        article
883        gnus-newsgroup-name)
884       (buffer-string))))
885
886 ;; disabled for now
887 ;; (defun spam-get-article-as-filename (article)
888 ;;   (let ((article-filename))
889 ;;     (when (numberp article)
890 ;;       (nnml-possibly-change-directory
891 ;;        (gnus-group-real-name gnus-newsgroup-name))
892 ;;       (setq article-filename (expand-file-name
893 ;;                              (int-to-string article) nnml-current-directory)))
894 ;;     (if (file-exists-p article-filename)
895 ;;      article-filename
896 ;;       nil)))
897
898 (defun spam-fetch-field-fast (article field &optional prepared-data-header)
899   "Fetch a field quickly, using the internal gnus-data-list function"
900   (when (numberp article)
901     (let* ((data-header (or prepared-data-header
902                             (spam-fetch-article-header article))))
903       (if (arrayp data-header)
904         (cond
905          ((equal field 'from)
906           (mail-header-from data-header))
907          ((equal field 'message-id)
908           (mail-header-message-id data-header))
909          ((equal field 'subject)
910           (mail-header-subject data-header))
911          ((equal field 'references)
912           (mail-header-references data-header))
913          ((equal field 'date)
914           (mail-header-date data-header))
915          ((equal field 'xref)
916           (mail-header-xref data-header))
917          ((equal field 'extra)
918           (mail-header-extra data-header))
919          (t
920           nil))
921         (gnus-error 5 "Article %d has a nil data header" article)))))
922
923 (defun spam-fetch-field-from-fast (article &optional prepared-data-header)
924   (spam-fetch-field-fast article 'from prepared-data-header))
925
926 (defun spam-fetch-field-subject-fast (article &optional prepared-data-header)
927   (spam-fetch-field-fast article 'subject prepared-data-header))
928
929 (defun spam-fetch-field-message-id-fast (article &optional prepared-data-header)
930   (spam-fetch-field-fast article 'message-id prepared-data-header))
931
932 (defun spam-generate-fake-headers (article)
933   (let ((dh (spam-fetch-article-header article)))
934     (if dh
935         (concat
936          (format 
937           (concat "From: %s\nSubject: %s\nMessage-ID: %s\n"
938                   "Date: %s\nReferences: %s\nXref: %s\n")
939           (spam-fetch-field-fast article 'from dh)
940           (spam-fetch-field-fast article 'subject dh)
941           (spam-fetch-field-fast article 'message-id dh)
942           (spam-fetch-field-fast article 'date dh)
943           (spam-fetch-field-fast article 'references dh)
944           (spam-fetch-field-fast article 'xref dh))
945          (when (spam-fetch-field-fast article 'extra dh)
946            (format "%s\n" (spam-fetch-field-fast article 'extra dh))))
947       (gnus-error
948        5
949        "spam-generate-fake-headers: article %d didn't have a valid header"
950        article))))
951
952 (defun spam-fetch-article-header (article)
953   (save-excursion
954     (set-buffer gnus-summary-buffer)
955     (nth 3 (assq article gnus-newsgroup-data))))
956
957 \f
958 ;;;; Spam determination.
959
960 (defvar spam-list-of-checks
961   '((spam-use-blacklist                 .       spam-check-blacklist)
962     (spam-use-regex-headers             .       spam-check-regex-headers)
963     (spam-use-regex-body                .       spam-check-regex-body)
964     (spam-use-whitelist                 .       spam-check-whitelist)
965     (spam-use-BBDB                      .       spam-check-BBDB)
966     (spam-use-BBDB-exclusive            .       spam-check-BBDB)
967     (spam-use-ifile                     .       spam-check-ifile)
968     (spam-use-spamoracle                .       spam-check-spamoracle)
969     (spam-use-stat                      .       spam-check-stat)
970     (spam-use-blackholes                .       spam-check-blackholes)
971     (spam-use-hashcash                  .       spam-check-hashcash)
972     (spam-use-spamassassin-headers      .       spam-check-spamassassin-headers)
973     (spam-use-spamassassin              .       spam-check-spamassassin)
974     (spam-use-bogofilter-headers        .       spam-check-bogofilter-headers)
975     (spam-use-bogofilter                .       spam-check-bogofilter))
976   "The spam-list-of-checks list contains pairs associating a
977 parameter variable with a spam checking function.  If the
978 parameter variable is true, then the checking function is called,
979 and its value decides what happens.  Each individual check may
980 return nil, t, or a mailgroup name.  The value nil means that the
981 check does not yield a decision, and so, that further checks are
982 needed.  The value t means that the message is definitely not
983 spam, and that further spam checks should be inhibited.
984 Otherwise, a mailgroup name or the symbol 'spam (depending on
985 spam-split-symbolic-return) is returned where the mail should go,
986 and further checks are also inhibited.  The usual mailgroup name
987 is the value of `spam-split-group', meaning that the message is
988 definitely a spam.")
989
990 (defvar spam-list-of-statistical-checks
991   '(spam-use-ifile
992     spam-use-regex-body
993     spam-use-stat
994     spam-use-bogofilter
995     spam-use-blackholes
996     spam-use-spamassassin
997     spam-use-spamoracle)
998   "The spam-list-of-statistical-checks list contains all the mail
999 splitters that need to have the full message body available.
1000 Note that you should fetch extra headers if you don't like this,
1001 e.g. fetch the 'Received' header for spam-use-blackholes.")
1002
1003 (defun spam-split (&rest specific-checks)
1004   "Split this message into the `spam' group if it is spam.
1005 This function can be used as an entry in the variable `nnmail-split-fancy',
1006 for example like this: (: spam-split).  It can take checks as
1007 parameters.  A string as a parameter will set the
1008 spam-split-group to that string.
1009
1010 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1011   (interactive)
1012   (setq spam-split-last-successful-check nil)
1013   (unless spam-split-disabled
1014     (let ((spam-split-group-choice spam-split-group))
1015       (dolist (check specific-checks)
1016         (when (stringp check)
1017           (setq spam-split-group-choice check)
1018           (setq specific-checks (delq check specific-checks))))
1019
1020       (let ((spam-split-group spam-split-group-choice))
1021         (save-excursion
1022           (save-restriction
1023             (dolist (check spam-list-of-statistical-checks)
1024               (when (and (symbolp check)
1025                          (or (symbol-value check)
1026                              (memq check specific-checks)))
1027                 (widen)
1028                 (gnus-message 8 "spam-split: widening the buffer (%s requires it)"
1029                               (symbol-name check))
1030                 (return)))
1031             ;;   (progn (widen) (debug (buffer-string)))
1032             (let ((list-of-checks spam-list-of-checks)
1033                   decision)
1034               (while (and list-of-checks (not decision))
1035                 (let ((pair (pop list-of-checks)))
1036                   (when (or
1037                          ;; either, given specific checks, this is one of them
1038                          (and specific-checks (memq (car pair) specific-checks))
1039                          ;; or, given no specific checks, spam-use-CHECK is set
1040                          (and (null specific-checks) (symbol-value (car pair))))
1041                     (gnus-message 5 "spam-split: calling the %s function"
1042                                   (symbol-name (cdr pair)))
1043                     (setq decision (funcall (cdr pair)))
1044                     ;; if we got a decision at all, save the current check
1045                     (when decision
1046                       (setq spam-split-last-successful-check (car pair)))
1047
1048                     (when (eq decision 'spam)
1049                       (unless spam-split-symbolic-return
1050                         (gnus-error
1051                          5
1052                          (format "spam-split got %s but %s is nil"
1053                                  (symbol-name decision)
1054                                  (symbol-name spam-split-symbolic-return))))))))
1055               (if (eq decision t)
1056                   (if spam-split-symbolic-return-positive 'ham nil)
1057                 decision))))))))
1058
1059 (defun spam-find-spam ()
1060   "This function will detect spam in the current newsgroup using spam-split."
1061   (interactive)
1062
1063   (let* ((group gnus-newsgroup-name)
1064          (autodetect (gnus-parameter-spam-autodetect group))
1065          (methods (gnus-parameter-spam-autodetect-methods group))
1066          (first-method (nth 0 methods))
1067          (articles (if spam-autodetect-recheck-messages
1068                        gnus-newsgroup-articles
1069                      gnus-newsgroup-unseen))
1070          article-cannot-be-faked)
1071
1072     (dolist (check spam-list-of-statistical-checks)
1073       (when (and (symbolp check)
1074                  (memq check methods))
1075         (setq article-cannot-be-faked t)
1076         (return)))
1077
1078     (when (memq 'default methods)
1079       (setq article-cannot-be-faked t))
1080
1081     (when (and autodetect
1082                (not (equal first-method 'none)))
1083     (mapcar
1084      (lambda (article)
1085        (let ((id (spam-fetch-field-message-id-fast article))
1086              (subject (spam-fetch-field-subject-fast article))
1087              (sender (spam-fetch-field-from-fast article))
1088              registry-lookup)
1089          
1090          (unless id
1091            (gnus-error 5 "Article %d has no message ID!" article))
1092          
1093          (when (and id spam-log-to-registry)
1094            (setq registry-lookup (spam-log-registration-type id 'incoming))
1095            (when registry-lookup
1096              (gnus-message
1097               9
1098               "spam-find-spam: message %s was already registered incoming"
1099               id)))
1100
1101          (let* ((spam-split-symbolic-return t)
1102                 (spam-split-symbolic-return-positive t)
1103                 (fake-headers (spam-generate-fake-headers article))
1104                 (split-return
1105                  (or registry-lookup
1106                      (with-temp-buffer
1107                        (if article-cannot-be-faked
1108                            (gnus-request-article-this-buffer
1109                             article
1110                             group)
1111                          ;; else, we fake the article
1112                          (when fake-headers (insert fake-headers)))
1113                        (if (or (null first-method)
1114                                (equal first-method 'default))
1115                            (spam-split)
1116                          (apply 'spam-split methods))))))
1117            (if (equal split-return 'spam)
1118                (gnus-summary-mark-article article gnus-spam-mark))
1119            
1120            (when (and id split-return spam-log-to-registry)
1121              (when (zerop (gnus-registry-group-count id))
1122                (gnus-registry-add-group
1123                 id group subject sender))
1124                
1125              (unless registry-lookup
1126                (spam-log-processing-to-registry
1127                 id
1128                 'incoming
1129                 split-return
1130                 spam-split-last-successful-check
1131                 group))))))
1132     articles))))
1133
1134 (defvar spam-registration-functions
1135   ;; first the ham register, second the spam register function
1136   ;; third the ham unregister, fourth the spam unregister function
1137   '((spam-use-blacklist  nil
1138                          spam-blacklist-register-routine
1139                          nil
1140                          spam-blacklist-unregister-routine)
1141     (spam-use-whitelist  spam-whitelist-register-routine
1142                          nil
1143                          spam-whitelist-unregister-routine
1144                          nil)
1145     (spam-use-ham-copy   nil
1146                          nil
1147                          nil
1148                          nil)
1149     (spam-use-BBDB       spam-BBDB-register-routine
1150                          nil
1151                          spam-BBDB-unregister-routine
1152                          nil)
1153     (spam-use-ifile      spam-ifile-register-ham-routine
1154                          spam-ifile-register-spam-routine
1155                          spam-ifile-unregister-ham-routine
1156                          spam-ifile-unregister-spam-routine)
1157     (spam-use-spamoracle spam-spamoracle-learn-ham
1158                          spam-spamoracle-learn-spam
1159                          spam-spamoracle-unlearn-ham
1160                          spam-spamoracle-unlearn-spam)
1161     (spam-use-stat       spam-stat-register-ham-routine
1162                          spam-stat-register-spam-routine
1163                          spam-stat-unregister-ham-routine
1164                          spam-stat-unregister-spam-routine)
1165     ;; note that spam-use-gmane is not a legitimate check
1166     (spam-use-gmane      nil
1167                          spam-report-gmane-register-routine
1168                          ;; does Gmane support unregistration?
1169                          nil
1170                          nil)
1171     (spam-use-spamassassin spam-spamassassin-register-ham-routine
1172                            spam-spamassassin-register-spam-routine
1173                            spam-spamassassin-unregister-ham-routine
1174                            spam-spamassassin-unregister-spam-routine)
1175     (spam-use-bogofilter spam-bogofilter-register-ham-routine
1176                          spam-bogofilter-register-spam-routine
1177                          spam-bogofilter-unregister-ham-routine
1178                          spam-bogofilter-unregister-spam-routine))
1179   "The spam-registration-functions list contains pairs
1180 associating a parameter variable with the ham and spam
1181 registration functions, and the ham and spam unregistration
1182 functions")
1183
1184 (defun spam-classification-valid-p (classification)
1185   (or  (eq classification 'spam)
1186        (eq classification 'ham)))
1187
1188 (defun spam-process-type-valid-p (process-type)
1189   (or  (eq process-type 'incoming)
1190        (eq process-type 'process)))
1191
1192 (defun spam-registration-check-valid-p (check)
1193   (assoc check spam-registration-functions))
1194
1195 (defun spam-unregistration-check-valid-p (check)
1196   (assoc check spam-registration-functions))
1197
1198 (defun spam-registration-function (classification check)
1199   (let ((flist (cdr-safe (assoc check spam-registration-functions))))
1200     (if (eq classification 'spam)
1201         (nth 1 flist)
1202       (nth 0 flist))))
1203
1204 (defun spam-unregistration-function (classification check)
1205   (let ((flist (cdr-safe (assoc check spam-registration-functions))))
1206     (if (eq classification 'spam)
1207         (nth 3 flist)
1208       (nth 2 flist))))
1209
1210 (defun spam-list-articles (articles classification)
1211   (let ((mark-check (if (eq classification 'spam)
1212                         'spam-group-spam-mark-p
1213                       'spam-group-ham-mark-p))
1214         list mark-cache-yes mark-cache-no)
1215     (dolist (article articles)
1216       (let ((mark (gnus-summary-article-mark article)))
1217         (unless (memq mark mark-cache-no)
1218           (if (memq mark mark-cache-yes)
1219               (push article list)
1220             ;; else, we have to actually check the mark
1221             (if (funcall mark-check
1222                          gnus-newsgroup-name
1223                          mark)
1224                 (progn
1225                   (push article list)
1226                   (push mark mark-cache-yes))
1227               (push mark mark-cache-no))))))
1228     list))
1229
1230 (defun spam-register-routine (classification
1231                               check
1232                               &optional unregister
1233                               specific-articles)
1234   (when (and (spam-classification-valid-p classification)
1235              (spam-registration-check-valid-p check))
1236     (let* ((register-function
1237             (spam-registration-function classification check))
1238            (unregister-function
1239             (spam-unregistration-function classification check))
1240            (run-function (if unregister
1241                              unregister-function
1242                            register-function))
1243            (log-function (if unregister
1244                              'spam-log-undo-registration
1245                            'spam-log-processing-to-registry))
1246            article articles)
1247
1248       (when run-function
1249         ;; make list of articles, using specific-articles if given
1250         (setq articles (or specific-articles
1251                            (spam-list-articles
1252                             gnus-newsgroup-articles
1253                             classification)))
1254         ;; process them
1255         (gnus-message 5 "%s %d %s articles as %s using backend %s"
1256                       (if unregister "Unregistering" "Registering")
1257                       (length articles)
1258                       (if specific-articles "specific" "")
1259                       (symbol-name classification)
1260                       (symbol-name check))
1261         (funcall run-function articles)
1262         ;; now log all the registrations (or undo them, depending on unregister)
1263         (dolist (article articles)
1264           (funcall log-function
1265                    (spam-fetch-field-message-id-fast article)
1266                    'process
1267                    classification
1268                    check
1269                    gnus-newsgroup-name))))))
1270
1271 ;;; log a ham- or spam-processor invocation to the registry
1272 (defun spam-log-processing-to-registry (id type classification check group)
1273   (when spam-log-to-registry
1274     (if (and (stringp id)
1275              (stringp group)
1276              (spam-process-type-valid-p type)
1277              (spam-classification-valid-p classification)
1278              (spam-registration-check-valid-p check))
1279         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1280               (cell (list classification check group)))
1281           (push cell cell-list)
1282           (gnus-registry-store-extra-entry
1283            id
1284            type
1285            cell-list))
1286
1287       (gnus-error 
1288        5 
1289        (format "%s call with bad ID, type, classification, spam-check, or group"
1290                "spam-log-processing-to-registry")))))
1291
1292 ;;; check if a ham- or spam-processor registration has been done
1293 (defun spam-log-registered-p (id type)
1294   (when spam-log-to-registry
1295     (if (and (stringp id)
1296              (spam-process-type-valid-p type))
1297         (cdr-safe (gnus-registry-fetch-extra id type))
1298       (progn
1299         (gnus-error 
1300          5 
1301          (format "%s called with bad ID, type, classification, or spam-check"
1302                  "spam-log-registered-p"))
1303         nil))))
1304
1305 ;;; check what a ham- or spam-processor registration says
1306 ;;; returns nil if conflicting registrations are found
1307 (defun spam-log-registration-type (id type)
1308   (let ((count 0)
1309         decision)
1310     (dolist (reg (spam-log-registered-p id type))
1311       (let ((classification (nth 0 reg)))
1312         (when (spam-classification-valid-p classification)
1313           (when (and decision
1314                      (not (eq classification decision)))
1315             (setq count (+ 1 count)))
1316           (setq decision classification))))
1317     (if (< 0 count)
1318         nil
1319       decision)))
1320
1321
1322 ;;; check if a ham- or spam-processor registration needs to be undone
1323 (defun spam-log-unregistration-needed-p (id type classification check)
1324   (when spam-log-to-registry
1325     (if (and (stringp id)
1326              (spam-process-type-valid-p type)
1327              (spam-classification-valid-p classification)
1328              (spam-registration-check-valid-p check))
1329         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1330               found)
1331           (dolist (cell cell-list)
1332             (unless found
1333               (when (and (eq classification (nth 0 cell))
1334                          (eq check (nth 1 cell)))
1335                 (setq found t))))
1336           found)
1337       (progn
1338         (gnus-error 
1339          5 
1340          (format "%s called with bad ID, type, classification, or spam-check"
1341                  "spam-log-unregistration-needed-p"))
1342         nil))))
1343
1344
1345 ;;; undo a ham- or spam-processor registration (the group is not used)
1346 (defun spam-log-undo-registration (id type classification check &optional group)
1347   (when (and spam-log-to-registry
1348              (spam-log-unregistration-needed-p id type classification check))
1349     (if (and (stringp id)
1350              (spam-process-type-valid-p type)
1351              (spam-classification-valid-p classification)
1352              (spam-registration-check-valid-p check))
1353         (let ((cell-list (cdr-safe (gnus-registry-fetch-extra id type)))
1354               new-cell-list found)
1355           (dolist (cell cell-list)
1356             (unless (and (eq classification (nth 0 cell))
1357                          (eq check (nth 1 cell)))
1358               (push cell new-cell-list)))
1359           (gnus-registry-store-extra-entry
1360            id
1361            type
1362            new-cell-list))
1363       (progn
1364         (gnus-error 5 (format "%s call with bad ID, type, spam-check, or group"
1365                               "spam-log-undo-registration"))
1366         nil))))
1367
1368 ;;; set up IMAP widening if it's necessary
1369 (defun spam-setup-widening ()
1370   (dolist (check spam-list-of-statistical-checks)
1371     (when (symbol-value check)
1372       (setq nnimap-split-download-body-default t))))
1373
1374 \f
1375 ;;;; Regex body
1376
1377 (defun spam-check-regex-body ()
1378   (let ((spam-regex-headers-ham spam-regex-body-ham)
1379         (spam-regex-headers-spam spam-regex-body-spam))
1380     (spam-check-regex-headers t)))
1381
1382 \f
1383 ;;;; Regex headers
1384
1385 (defun spam-check-regex-headers (&optional body)
1386   (let ((type (if body "body" "header"))
1387         (spam-split-group (if spam-split-symbolic-return
1388                               'spam
1389                             spam-split-group))
1390         ret found)
1391     (dolist (h-regex spam-regex-headers-ham)
1392       (unless found
1393         (goto-char (point-min))
1394         (when (re-search-forward h-regex nil t)
1395           (message "Ham regex %s search positive." type)
1396           (setq found t))))
1397     (dolist (s-regex spam-regex-headers-spam)
1398       (unless found
1399         (goto-char (point-min))
1400         (when (re-search-forward s-regex nil t)
1401           (message "Spam regex %s search positive." type)
1402           (setq found t)
1403           (setq ret spam-split-group))))
1404     ret))
1405
1406 \f
1407 ;;;; Blackholes.
1408
1409 (defun spam-reverse-ip-string (ip)
1410   (when (stringp ip)
1411     (mapconcat 'identity
1412                (nreverse (split-string ip "\\."))
1413                ".")))
1414
1415 (defun spam-check-blackholes ()
1416   "Check the Received headers for blackholed relays."
1417   (let ((headers (message-fetch-field "received"))
1418         (spam-split-group (if spam-split-symbolic-return
1419                               'spam
1420                             spam-split-group))
1421         ips matches)
1422     (when headers
1423       (with-temp-buffer
1424         (insert headers)
1425         (goto-char (point-min))
1426         (gnus-message 5 "Checking headers for relay addresses")
1427         (while (re-search-forward
1428                 "\\([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\)" nil t)
1429           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
1430           (push (spam-reverse-ip-string (match-string 1))
1431                 ips)))
1432       (dolist (server spam-blackhole-servers)
1433         (dolist (ip ips)
1434           (unless (and spam-blackhole-good-server-regex
1435                        ;; match the good-server-regex against the reversed (again) IP string
1436                        (string-match
1437                         spam-blackhole-good-server-regex
1438                         (spam-reverse-ip-string ip)))
1439             (unless matches
1440               (let ((query-string (concat ip "." server)))
1441                 (if spam-use-dig
1442                     (let ((query-result (query-dig query-string)))
1443                       (when query-result
1444                         (gnus-message 5 "(DIG): positive blackhole check '%s'"
1445                                       query-result)
1446                         (push (list ip server query-result)
1447                               matches)))
1448                   ;; else, if not using dig.el
1449                   (when (query-dns query-string)
1450                     (gnus-message 5 "positive blackhole check")
1451                     (push (list ip server (query-dns query-string 'TXT))
1452                           matches)))))))))
1453     (when matches
1454       spam-split-group)))
1455 \f
1456 ;;;; Hashcash.
1457
1458 (condition-case nil
1459     (progn
1460       (require 'hashcash)
1461
1462       (defun spam-check-hashcash ()
1463         "Check the headers for hashcash payments."
1464         (mail-check-payment)))   ;mail-check-payment returns a boolean
1465
1466   (file-error (progn
1467                 (defalias 'mail-check-payment 'ignore)
1468                 (defalias 'spam-check-hashcash 'ignore))))
1469 \f
1470 ;;;; BBDB
1471
1472 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
1473 ;;; <sacha@giotto.sj.ru>
1474
1475 ;; all this is done inside a condition-case to trap errors
1476
1477 (condition-case nil
1478     (progn
1479       (require 'bbdb)
1480       (require 'bbdb-com)
1481
1482       ;; when the BBDB changes, we want to clear out our cache
1483       (defun spam-clear-cache-BBDB (&rest immaterial)
1484         (spam-clear-cache 'spam-use-BBDB))
1485
1486       (add-hook 'bbdb-change-hook 'spam-clear-cache-BBDB)
1487
1488       (defun spam-enter-ham-BBDB (addresses &optional remove)
1489         "Enter an address into the BBDB; implies ham (non-spam) sender"
1490         (dolist (from addresses)
1491           (when (stringp from)
1492             (let* ((parsed-address (gnus-extract-address-components from))
1493                    (name (or (nth 0 parsed-address) "Ham Sender"))
1494                    (remove-function (if remove
1495                                         'bbdb-delete-record-internal
1496                                       'ignore))
1497                    (net-address (nth 1 parsed-address))
1498                    (record (and net-address
1499                                 (bbdb-search-simple nil net-address))))
1500               (when net-address
1501                 (gnus-message 5 "%s address %s %s BBDB"
1502                               (if remove "Deleting" "Adding")
1503                               from
1504                               (if remove "from" "to"))
1505                 (if record
1506                     (funcall remove-function record)
1507                   (bbdb-create-internal name nil net-address nil nil
1508                                         "ham sender added by spam.el")))))))
1509
1510       (defun spam-BBDB-register-routine (articles &optional unregister)
1511         (let (addresses)
1512           (dolist (article articles)
1513             (when (stringp (spam-fetch-field-from-fast article))
1514               (push (spam-fetch-field-from-fast article) addresses)))
1515           ;; now do the register/unregister action
1516           (spam-enter-ham-BBDB addresses unregister)))
1517
1518       (defun spam-BBDB-unregister-routine (articles)
1519         (spam-BBDB-register-routine articles t))
1520
1521       (defun spam-check-BBDB ()
1522         "Mail from people in the BBDB is classified as ham or non-spam"
1523         (let ((who (message-fetch-field "from"))
1524               (spam-split-group (if spam-split-symbolic-return
1525                                     'spam
1526                                   spam-split-group))
1527               bbdb-cache bbdb-hashtable)
1528           (when spam-cache-lookups
1529             (setq bbdb-cache (gethash 'spam-use-BBDB spam-caches))
1530             (unless bbdb-cache
1531               (setq bbdb-cache
1532                     ;; this is the expanded (bbdb-hashtable) macro
1533                     ;; without the debugging support
1534                     (with-current-buffer (bbdb-buffer)
1535                       (save-excursion
1536                         (save-window-excursion
1537                           (bbdb-records nil t)
1538                           bbdb-hashtable))))
1539               (puthash 'spam-use-BBDB bbdb-cache spam-caches)))
1540           (when who
1541             (setq who (nth 1 (gnus-extract-address-components who)))
1542             (if
1543                 (if spam-cache-lookups
1544                     (symbol-value
1545                      (intern-soft who bbdb-cache))
1546                   (bbdb-search-simple nil who))
1547                 t
1548               (if spam-use-BBDB-exclusive
1549                   spam-split-group
1550                 nil))))))
1551
1552   (file-error (progn
1553                 (defalias 'bbdb-search-simple 'ignore)
1554                 (defalias 'bbdb-records 'ignore)
1555                 (defalias 'bbdb-buffer 'ignore)
1556                 (defalias 'spam-check-BBDB 'ignore)
1557                 (defalias 'spam-BBDB-register-routine 'ignore)
1558                 (defalias 'spam-enter-ham-BBDB 'ignore)
1559                 (defalias 'bbdb-create-internal 'ignore)
1560                 (defalias 'bbdb-delete-record-internal 'ignore)
1561                 (defalias 'bbdb-records 'ignore))))
1562
1563 \f
1564 ;;;; ifile
1565
1566 ;;; check the ifile backend; return nil if the mail was NOT classified
1567 ;;; as spam
1568
1569 (defun spam-get-ifile-database-parameter ()
1570   "Get the command-line parameter for ifile's database from
1571   spam-ifile-database-path."
1572   (if spam-ifile-database-path
1573       (format "--db-file=%s" spam-ifile-database-path)
1574     nil))
1575
1576 (defun spam-check-ifile ()
1577   "Check the ifile backend for the classification of this message."
1578   (let ((article-buffer-name (buffer-name))
1579         (spam-split-group (if spam-split-symbolic-return
1580                               'spam
1581                             spam-split-group))
1582         category return)
1583     (with-temp-buffer
1584       (let ((temp-buffer-name (buffer-name))
1585             (db-param (spam-get-ifile-database-parameter)))
1586         (save-excursion
1587           (set-buffer article-buffer-name)
1588           (apply 'call-process-region
1589                  (point-min) (point-max) spam-ifile-path
1590                  nil temp-buffer-name nil "-c"
1591                  (if db-param `(,db-param "-q") `("-q"))))
1592         ;; check the return now (we're back in the temp buffer)
1593         (goto-char (point-min))
1594         (if (not (eobp))
1595             (setq category (buffer-substring (point) (point-at-eol))))
1596         (when (not (zerop (length category))) ; we need a category here
1597           (if spam-ifile-all-categories
1598               (setq return category)
1599             ;; else, if spam-ifile-all-categories is not set...
1600             (when (string-equal spam-ifile-spam-category category)
1601               (setq return spam-split-group)))))) ; note return is nil otherwise
1602     return))
1603
1604 (defun spam-ifile-register-with-ifile (articles category &optional unregister)
1605   "Register an article, given as a string, with a category.
1606 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
1607   (let ((category (or category gnus-newsgroup-name))
1608         (add-or-delete-option (if unregister "-d" "-i"))
1609         (db (spam-get-ifile-database-parameter))
1610         parameters)
1611     (with-temp-buffer
1612       (dolist (article articles)
1613         (let ((article-string (spam-get-article-as-string article)))
1614           (when (stringp article-string)
1615             (insert article-string))))
1616       (apply 'call-process-region
1617              (point-min) (point-max) spam-ifile-path
1618              nil nil nil
1619              add-or-delete-option category
1620              (if db `(,db "-h") `("-h"))))))
1621
1622 (defun spam-ifile-register-spam-routine (articles &optional unregister)
1623   (spam-ifile-register-with-ifile articles spam-ifile-spam-category unregister))
1624
1625 (defun spam-ifile-unregister-spam-routine (articles)
1626   (spam-ifile-register-spam-routine articles t))
1627
1628 (defun spam-ifile-register-ham-routine (articles &optional unregister)
1629   (spam-ifile-register-with-ifile articles spam-ifile-ham-category unregister))
1630
1631 (defun spam-ifile-unregister-ham-routine (articles)
1632   (spam-ifile-register-ham-routine articles t))
1633
1634 \f
1635 ;;;; spam-stat
1636
1637 (condition-case nil
1638     (progn
1639       (let ((spam-stat-install-hooks nil))
1640         (require 'spam-stat))
1641
1642       (defun spam-check-stat ()
1643         "Check the spam-stat backend for the classification of this message"
1644         (let ((spam-split-group (if spam-split-symbolic-return
1645                                     'spam
1646                                   spam-split-group))
1647               (spam-stat-split-fancy-spam-group spam-split-group) ; override
1648               (spam-stat-buffer (buffer-name)) ; stat the current buffer
1649               category return)
1650           (spam-stat-split-fancy)))
1651
1652       (defun spam-stat-register-spam-routine (articles &optional unregister)
1653         (dolist (article articles)
1654           (let ((article-string (spam-get-article-as-string article)))
1655             (with-temp-buffer
1656               (insert article-string)
1657               (if unregister
1658                   (spam-stat-buffer-change-to-non-spam)
1659               (spam-stat-buffer-is-spam))))))
1660
1661       (defun spam-stat-unregister-spam-routine (articles)
1662         (spam-stat-register-spam-routine articles t))
1663
1664       (defun spam-stat-register-ham-routine (articles &optional unregister)
1665         (dolist (article articles)
1666           (let ((article-string (spam-get-article-as-string article)))
1667             (with-temp-buffer
1668               (insert article-string)
1669               (if unregister
1670                   (spam-stat-buffer-change-to-spam)
1671               (spam-stat-buffer-is-non-spam))))))
1672
1673       (defun spam-stat-unregister-ham-routine (articles)
1674         (spam-stat-register-ham-routine articles t))
1675
1676       (defun spam-maybe-spam-stat-load ()
1677         (when spam-use-stat (spam-stat-load)))
1678
1679       (defun spam-maybe-spam-stat-save ()
1680         (when spam-use-stat (spam-stat-save))))
1681
1682   (file-error (progn
1683                 (defalias 'spam-stat-load 'ignore)
1684                 (defalias 'spam-stat-save 'ignore)
1685                 (defalias 'spam-maybe-spam-stat-load 'ignore)
1686                 (defalias 'spam-maybe-spam-stat-save 'ignore)
1687                 (defalias 'spam-stat-register-ham-routine 'ignore)
1688                 (defalias 'spam-stat-unregister-ham-routine 'ignore)
1689                 (defalias 'spam-stat-register-spam-routine 'ignore)
1690                 (defalias 'spam-stat-unregister-spam-routine 'ignore)
1691                 (defalias 'spam-stat-buffer-is-spam 'ignore)
1692                 (defalias 'spam-stat-buffer-change-to-spam 'ignore)
1693                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
1694                 (defalias 'spam-stat-buffer-change-to-non-spam 'ignore)
1695                 (defalias 'spam-stat-split-fancy 'ignore)
1696                 (defalias 'spam-check-stat 'ignore))))
1697
1698 \f
1699
1700 ;;;; Blacklists and whitelists.
1701
1702 (defvar spam-whitelist-cache nil)
1703 (defvar spam-blacklist-cache nil)
1704
1705 (defun spam-kill-whole-line ()
1706   (beginning-of-line)
1707   (let ((kill-whole-line t))
1708     (kill-line)))
1709
1710 ;;; address can be a list, too
1711 (defun spam-enter-whitelist (address &optional remove)
1712   "Enter ADDRESS (list or single) into the whitelist.
1713 With a non-nil REMOVE, remove them."
1714   (interactive "sAddress: ")
1715   (spam-enter-list address spam-whitelist remove)
1716   (setq spam-whitelist-cache nil)
1717   (spam-clear-cache 'spam-use-whitelist))
1718
1719 ;;; address can be a list, too
1720 (defun spam-enter-blacklist (address &optional remove)
1721   "Enter ADDRESS (list or single) into the blacklist.
1722 With a non-nil REMOVE, remove them."
1723   (interactive "sAddress: ")
1724   (spam-enter-list address spam-blacklist remove)
1725   (setq spam-blacklist-cache nil)
1726   (spam-clear-cache 'spam-use-whitelist))
1727
1728 (defun spam-enter-list (addresses file &optional remove)
1729   "Enter ADDRESSES into the given FILE.
1730 Either the whitelist or the blacklist files can be used.  With
1731 REMOVE not nil, remove the ADDRESSES."
1732   (if (stringp addresses)
1733       (spam-enter-list (list addresses) file remove)
1734     ;; else, we have a list of addresses here
1735     (unless (file-exists-p (file-name-directory file))
1736       (make-directory (file-name-directory file) t))
1737     (save-excursion
1738       (set-buffer
1739        (find-file-noselect file))
1740       (dolist (a addresses)
1741         (when (stringp a)
1742           (goto-char (point-min))
1743           (if (re-search-forward (regexp-quote a) nil t)
1744               ;; found the address
1745               (when remove
1746                 (spam-kill-whole-line))
1747             ;; else, the address was not found
1748             (unless remove
1749               (goto-char (point-max))
1750               (unless (bobp)
1751                 (insert "\n"))
1752               (insert a "\n")))))
1753       (save-buffer))))
1754
1755 (defun spam-filelist-build-cache (type)
1756   (let ((cache (if (eq type 'spam-use-blacklist)
1757                    spam-blacklist-cache
1758                  spam-whitelist-cache))
1759         parsed-cache)
1760     (unless (gethash type spam-caches)
1761       (while cache
1762         (let ((address (pop cache)))
1763           (unless (zerop (length address)) ; 0 for a nil address too
1764             (setq address (regexp-quote address))
1765             ;; fix regexp-quote's treatment of user-intended regexes
1766             (while (string-match "\\\\\\*" address)
1767               (setq address (replace-match ".*" t t address))))
1768           (push address parsed-cache)))
1769       (puthash type parsed-cache spam-caches))))
1770
1771 (defun spam-filelist-check-cache (type from)
1772   (when (stringp from)
1773     (spam-filelist-build-cache type)
1774     (let (found)
1775       (dolist (address (gethash type spam-caches))
1776         (when (and address (string-match address from))
1777           (setq found t)
1778           (return)))
1779       found)))
1780
1781 ;;; returns t if the sender is in the whitelist, nil or
1782 ;;; spam-split-group otherwise
1783 (defun spam-check-whitelist ()
1784   ;; FIXME!  Should it detect when file timestamps change?
1785   (let ((spam-split-group (if spam-split-symbolic-return
1786                               'spam
1787                             spam-split-group)))
1788     (unless spam-whitelist-cache
1789       (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
1790     (if (spam-from-listed-p 'spam-use-whitelist)
1791         t
1792       (if spam-use-whitelist-exclusive
1793           spam-split-group
1794         nil))))
1795
1796 (defun spam-check-blacklist ()
1797   ;; FIXME!  Should it detect when file timestamps change?
1798   (let ((spam-split-group (if spam-split-symbolic-return
1799                               'spam
1800                             spam-split-group)))
1801     (unless spam-blacklist-cache
1802       (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
1803     (and (spam-from-listed-p 'spam-use-blacklist) spam-split-group)))
1804
1805 (defun spam-parse-list (file)
1806   (when (file-readable-p file)
1807     (let (contents address)
1808       (with-temp-buffer
1809         (insert-file-contents file)
1810         (while (not (eobp))
1811           (setq address (buffer-substring (point) (point-at-eol)))
1812           (forward-line 1)
1813           ;; insert the e-mail address if detected, otherwise the raw data
1814           (unless (zerop (length address))
1815             (let ((pure-address (nth 1 (gnus-extract-address-components address))))
1816               (push (or pure-address address) contents)))))
1817       (nreverse contents))))
1818
1819 (defun spam-from-listed-p (type)
1820   (let ((from (message-fetch-field "from"))
1821         found)
1822     (spam-filelist-check-cache type from)))
1823
1824 (defun spam-filelist-register-routine (articles blacklist &optional unregister)
1825   (let ((de-symbol (if blacklist 'spam-use-whitelist 'spam-use-blacklist))
1826         (declassification (if blacklist 'ham 'spam))
1827         (enter-function
1828          (if blacklist 'spam-enter-blacklist 'spam-enter-whitelist))
1829         (remove-function
1830          (if blacklist 'spam-enter-whitelist 'spam-enter-blacklist))
1831         from addresses unregister-list)
1832     (dolist (article articles)
1833       (let ((from (spam-fetch-field-from-fast article))
1834             (id (spam-fetch-field-message-id-fast article))
1835             sender-ignored)
1836         (when (stringp from)
1837           (dolist (ignore-regex spam-blacklist-ignored-regexes)
1838             (when (and (not sender-ignored)
1839                        (stringp ignore-regex)
1840                        (string-match ignore-regex from))
1841               (setq sender-ignored t)))
1842           ;; remember the messages we need to unregister, unless remove is set
1843           (when (and
1844                  (null unregister)
1845                  (spam-log-unregistration-needed-p
1846                   id 'process declassification de-symbol))
1847             (push from unregister-list))
1848           (unless sender-ignored
1849             (push from addresses)))))
1850
1851     (if unregister
1852         (funcall enter-function addresses t) ; unregister all these addresses
1853       ;; else, register normally and unregister what we need to
1854       (funcall remove-function unregister-list t)
1855       (dolist (article unregister-list)
1856         (spam-log-undo-registration
1857          (spam-fetch-field-message-id-fast article)
1858          'process
1859          declassification
1860          de-symbol))
1861       (funcall enter-function addresses nil))))
1862
1863 (defun spam-blacklist-unregister-routine (articles)
1864   (spam-blacklist-register-routine articles t))
1865
1866 (defun spam-blacklist-register-routine (articles &optional unregister)
1867   (spam-filelist-register-routine articles t unregister))
1868
1869 (defun spam-whitelist-unregister-routine (articles)
1870   (spam-whitelist-register-routine articles t))
1871
1872 (defun spam-whitelist-register-routine (articles &optional unregister)
1873   (spam-filelist-register-routine articles nil unregister))
1874
1875 \f
1876 ;;;; Spam-report glue
1877 (defun spam-report-gmane-register-routine (articles)
1878   (when articles
1879     (apply 'spam-report-gmane articles)))
1880
1881 \f
1882 ;;;; Bogofilter
1883 (defun spam-check-bogofilter-headers (&optional score)
1884   (let ((header (message-fetch-field spam-bogofilter-header))
1885         (spam-split-group (if spam-split-symbolic-return
1886                               'spam
1887                             spam-split-group)))
1888     (when header                        ; return nil when no header
1889       (if score                         ; scoring mode
1890           (if (string-match "spamicity=\\([0-9.]+\\)" header)
1891               (match-string 1 header)
1892             "0")
1893         ;; spam detection mode
1894         (when (string-match spam-bogofilter-bogosity-positive-spam-header
1895                             header)
1896           spam-split-group)))))
1897
1898 ;; return something sensible if the score can't be determined
1899 (defun spam-bogofilter-score ()
1900   "Get the Bogofilter spamicity score"
1901   (interactive)
1902   (save-window-excursion
1903     (gnus-summary-show-article t)
1904     (set-buffer gnus-article-buffer)
1905     (let ((score (or (spam-check-bogofilter-headers t)
1906                      (spam-check-bogofilter t))))
1907       (gnus-summary-show-article)
1908       (message "Spamicity score %s" score)
1909       (or score "0"))))
1910
1911 (defun spam-check-bogofilter (&optional score)
1912   "Check the Bogofilter backend for the classification of this message"
1913   (let ((article-buffer-name (buffer-name))
1914         (db spam-bogofilter-database-directory)
1915         return)
1916     (with-temp-buffer
1917       (let ((temp-buffer-name (buffer-name)))
1918         (save-excursion
1919           (set-buffer article-buffer-name)
1920           (apply 'call-process-region
1921                  (point-min) (point-max)
1922                  spam-bogofilter-path
1923                  nil temp-buffer-name nil
1924                  (if db `("-d" ,db "-v") `("-v"))))
1925         (setq return (spam-check-bogofilter-headers score))))
1926     return))
1927
1928 (defun spam-bogofilter-register-with-bogofilter (articles
1929                                                  spam
1930                                                  &optional unregister)
1931   "Register an article, given as a string, as spam or non-spam."
1932   (dolist (article articles)
1933     (let ((article-string (spam-get-article-as-string article))
1934           (db spam-bogofilter-database-directory)
1935           (switch (if unregister
1936                       (if spam
1937                           spam-bogofilter-spam-strong-switch
1938                         spam-bogofilter-ham-strong-switch)
1939                     (if spam
1940                         spam-bogofilter-spam-switch
1941                       spam-bogofilter-ham-switch))))
1942       (when (stringp article-string)
1943         (with-temp-buffer
1944           (insert article-string)
1945
1946           (apply 'call-process-region
1947                  (point-min) (point-max)
1948                  spam-bogofilter-path
1949                  nil nil nil switch
1950                  (if db `("-d" ,db "-v") `("-v"))))))))
1951
1952 (defun spam-bogofilter-register-spam-routine (articles &optional unregister)
1953   (spam-bogofilter-register-with-bogofilter articles t unregister))
1954
1955 (defun spam-bogofilter-unregister-spam-routine (articles)
1956   (spam-bogofilter-register-spam-routine articles t))
1957
1958 (defun spam-bogofilter-register-ham-routine (articles &optional unregister)
1959   (spam-bogofilter-register-with-bogofilter articles nil unregister))
1960
1961 (defun spam-bogofilter-unregister-ham-routine (articles)
1962   (spam-bogofilter-register-ham-routine articles t))
1963
1964
1965 \f
1966 ;;;; spamoracle
1967 (defun spam-check-spamoracle ()
1968   "Run spamoracle on an article to determine whether it's spam."
1969   (let ((article-buffer-name (buffer-name))
1970         (spam-split-group (if spam-split-symbolic-return
1971                               'spam
1972                             spam-split-group)))
1973     (with-temp-buffer
1974       (let ((temp-buffer-name (buffer-name)))
1975         (save-excursion
1976           (set-buffer article-buffer-name)
1977           (let ((status
1978                  (apply 'call-process-region
1979                         (point-min) (point-max)
1980                         spam-spamoracle-binary
1981                         nil temp-buffer-name nil
1982                         (if spam-spamoracle-database
1983                             `("-f" ,spam-spamoracle-database "mark")
1984                           '("mark")))))
1985             (if (eq 0 status)
1986                 (progn
1987                   (set-buffer temp-buffer-name)
1988                   (goto-char (point-min))
1989                   (when (re-search-forward "^X-Spam: yes;" nil t)
1990                     spam-split-group))
1991               (error "Error running spamoracle: %s" status))))))))
1992
1993 (defun spam-spamoracle-learn (articles article-is-spam-p &optional unregister)
1994   "Run spamoracle in training mode."
1995   (with-temp-buffer
1996     (let ((temp-buffer-name (buffer-name)))
1997       (save-excursion
1998         (goto-char (point-min))
1999         (dolist (article articles)
2000           (insert (spam-get-article-as-string article)))
2001         (let* ((arg (if (spam-xor unregister article-is-spam-p)
2002                         "-spam"
2003                       "-good"))
2004                (status
2005                 (apply 'call-process-region
2006                        (point-min) (point-max)
2007                        spam-spamoracle-binary
2008                        nil temp-buffer-name nil
2009                        (if spam-spamoracle-database
2010                            `("-f" ,spam-spamoracle-database
2011                              "add" ,arg)
2012                          `("add" ,arg)))))
2013           (unless (eq 0 status)
2014             (error "Error running spamoracle: %s" status)))))))
2015
2016 (defun spam-spamoracle-learn-ham (articles &optional unregister)
2017   (spam-spamoracle-learn articles nil unregister))
2018
2019 (defun spam-spamoracle-unlearn-ham (articles &optional unregister)
2020   (spam-spamoracle-learn-ham articles t))
2021
2022 (defun spam-spamoracle-learn-spam (articles &optional unregister)
2023   (spam-spamoracle-learn articles t unregister))
2024
2025 (defun spam-spamoracle-unlearn-spam (articles &optional unregister)
2026   (spam-spamoracle-learn-spam articles t))
2027
2028 \f
2029 ;;;; SpamAssassin
2030 ;;; based mostly on the bogofilter code
2031 (defun spam-check-spamassassin-headers (&optional score)
2032   "Check the SpamAssassin headers for the classification of this message."
2033   (if score                             ; scoring mode
2034       (let ((header (message-fetch-field spam-spamassassin-spam-status-header)))
2035         (when header
2036           (if (string-match "hits=\\(-?[0-9.]+\\)" header)
2037               (match-string 1 header)
2038             "0")))
2039     ;; spam detection mode
2040     (let ((header (message-fetch-field spam-spamassassin-spam-flag-header))
2041           (spam-split-group (if spam-split-symbolic-return
2042                                  'spam
2043                                spam-split-group)))
2044           (when header                  ; return nil when no header
2045             (when (string-match spam-spamassassin-positive-spam-flag-header
2046                                 header)
2047               spam-split-group)))))
2048
2049 (defun spam-check-spamassassin (&optional score)
2050   "Check the SpamAssassin backend for the classification of this message."
2051   (let ((article-buffer-name (buffer-name)))
2052     (with-temp-buffer
2053       (let ((temp-buffer-name (buffer-name)))
2054         (save-excursion
2055           (set-buffer article-buffer-name)
2056           (apply 'call-process-region
2057                  (point-min) (point-max) spam-spamassassin-path
2058                  nil temp-buffer-name nil spam-spamassassin-arguments))
2059         ;; check the return now (we're back in the temp buffer)
2060         (goto-char (point-min))
2061         (spam-check-spamassassin-headers score)))))
2062
2063 ;; return something sensible if the score can't be determined
2064 (defun spam-spamassassin-score ()
2065   "Get the SpamAssassin score"
2066   (interactive)
2067   (save-window-excursion
2068     (gnus-summary-show-article t)
2069     (set-buffer gnus-article-buffer)
2070     (let ((score (or (spam-check-spamassassin-headers t)
2071                      (spam-check-spamassassin t))))
2072       (gnus-summary-show-article)
2073       (message "SpamAssassin score %s" score)
2074       (or score "0"))))
2075
2076 (defun spam-spamassassin-register-with-sa-learn (articles spam
2077                                                  &optional unregister)
2078   "Register articles with spamassassin's sa-learn as spam or non-spam."
2079   (if articles
2080       (let ((action (if unregister spam-sa-learn-unregister-switch
2081                       (if spam spam-sa-learn-spam-switch
2082                         spam-sa-learn-ham-switch)))
2083             (summary-buffer-name (buffer-name)))
2084         (with-temp-buffer
2085           ;; group the articles into mbox format
2086           (dolist (article articles)
2087             (let (article-string)
2088               (save-excursion
2089                 (set-buffer summary-buffer-name)
2090                 (setq article-string (spam-get-article-as-string article)))
2091               (when (stringp article-string)
2092                 (insert "From \n") ; mbox separator (sa-learn only checks the
2093                                    ; first five chars, so we can get away with
2094                                    ; a bogus line))
2095                 (insert article-string)
2096                 (insert "\n"))))
2097           ;; call sa-learn on all messages at the same time
2098           (apply 'call-process-region
2099                  (point-min) (point-max)
2100                  spam-sa-learn-path
2101                  nil nil nil "--mbox"
2102                  (if spam-sa-learn-rebuild
2103                      (list action)
2104                    `("--no-rebuild" ,action)))))))
2105
2106 (defun spam-spamassassin-register-spam-routine (articles &optional unregister)
2107   (spam-spamassassin-register-with-sa-learn articles t unregister))
2108
2109 (defun spam-spamassassin-register-ham-routine (articles &optional unregister)
2110   (spam-spamassassin-register-with-sa-learn articles nil unregister))
2111
2112 (defun spam-spamassassin-unregister-spam-routine (articles)
2113   (spam-spamassassin-register-with-sa-learn articles t t))
2114
2115 (defun spam-spamassassin-unregister-ham-routine (articles)
2116   (spam-spamassassin-register-with-sa-learn articles nil t))
2117 \f
2118 ;;;; Hooks
2119
2120 ;;;###autoload
2121 (defun spam-initialize ()
2122   "Install the spam.el hooks and do other initialization"
2123   (interactive)
2124   (setq spam-install-hooks t)
2125   ;; TODO: How do we redo this every time spam-face is customized?
2126   (push '((eq mark gnus-spam-mark) . spam-face)
2127         gnus-summary-highlight)
2128   ;; Add hooks for loading and saving the spam stats
2129   (add-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
2130   (add-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
2131   (add-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
2132   (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
2133   (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
2134   (add-hook 'gnus-get-new-news-hook 'spam-setup-widening)
2135   (add-hook 'gnus-summary-prepared-hook 'spam-find-spam))
2136
2137 (defun spam-unload-hook ()
2138   "Uninstall the spam.el hooks"
2139   (interactive)
2140   (remove-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
2141   (remove-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
2142   (remove-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load)
2143   (remove-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
2144   (remove-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
2145   (remove-hook 'gnus-get-new-news-hook 'spam-setup-widening)
2146   (remove-hook 'gnus-summary-prepare-hook 'spam-find-spam))
2147
2148 (when spam-install-hooks
2149   (spam-initialize))
2150
2151 (provide 'spam)
2152
2153 ;;; spam.el ends here