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