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