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