* uudecode.el (uudecode-use-external): Add :version.
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile
30   (require 'cl)
31   (require 'imap)
32   (eval-when-compile (defvar display-time-mail-function)))
33 (eval-and-compile
34   (autoload 'pop3-movemail "pop3")
35   (autoload 'pop3-get-message-count "pop3")
36   (autoload 'nnheader-cancel-timer "nnheader"))
37 (require 'format-spec)
38 (require 'mm-util)
39 (require 'message) ;; for `message-directory'
40
41 (defgroup mail-source nil
42   "The mail-fetching library."
43   :version "21.1"
44   :group 'gnus)
45
46 ;; Define these at compile time to avoid dragging in imap always.
47 (defconst mail-source-imap-authenticators
48   (eval-when-compile
49     (mapcar (lambda (a)
50               (list 'const (car a)))
51      imap-authenticator-alist)))
52 (defconst mail-source-imap-streams
53   (eval-when-compile
54     (mapcar (lambda (a)
55               (list 'const (car a)))
56      imap-stream-alist)))
57
58 (defcustom mail-sources nil
59   "*Where the mail backends will look for incoming mail.
60 This variable is a list of mail source specifiers.
61 See Info node `(gnus)Mail Source Specifiers'."
62   :group 'mail-source
63   :link '(custom-manual "(gnus)Mail Source Specifiers")
64   :type `(repeat
65           (choice :format "%[Value Menu%] %v"
66                   :value (file)
67                   (cons :tag "Spool file"
68                         (const :format "" file)
69                         (checklist :tag "Options" :greedy t
70                                    (group :inline t
71                                           (const :format "" :value :path)
72                                           file)))
73                   (cons :tag "Several files in a directory"
74                         (const :format "" directory)
75                         (checklist :tag "Options" :greedy t
76                                    (group :inline t
77                                           (const :format "" :value :path)
78                                           (directory :tag "Path"))
79                                    (group :inline t
80                                           (const :format "" :value :suffix)
81                                           (string :tag "Suffix"))
82                                    (group :inline t
83                                           (const :format "" :value :predicate)
84                                           (function :tag "Predicate"))
85                                    (group :inline t
86                                           (const :format "" :value :prescript)
87                                           (choice :tag "Prescript"
88                                                   :value nil
89                                                   (string :format "%v")
90                                                   (function :format "%v")))
91                                    (group :inline t
92                                           (const :format "" :value :postscript)
93                                           (choice :tag "Postscript"
94                                                   :value nil
95                                                   (string :format "%v")
96                                                   (function :format "%v")))
97                                    (group :inline t
98                                           (const :format "" :value :plugged)
99                                           (boolean :tag "Plugged"))))
100                   (cons :tag "POP3 server"
101                         (const :format "" pop)
102                         (checklist :tag "Options" :greedy t
103                                    (group :inline t
104                                           (const :format "" :value :server)
105                                           (string :tag "Server"))
106                                    (group :inline t
107                                           (const :format "" :value :port)
108                                           (choice :tag "Port"
109                                                   :value "pop3"
110                                                   (number :format "%v")
111                                                   (string :format "%v")))
112                                    (group :inline t
113                                           (const :format "" :value :user)
114                                           (string :tag "User"))
115                                    (group :inline t
116                                           (const :format "" :value :password)
117                                           (string :tag "Password"))
118                                    (group :inline t
119                                           (const :format "" :value :program)
120                                           (string :tag "Program"))
121                                    (group :inline t
122                                           (const :format "" :value :prescript)
123                                           (choice :tag "Prescript"
124                                                   :value nil
125                                                   (string :format "%v")
126                                                   (function :format "%v")))
127                                    (group :inline t
128                                           (const :format "" :value :postscript)
129                                           (choice :tag "Postscript"
130                                                   :value nil
131                                                   (string :format "%v")
132                                                   (function :format "%v")))
133                                    (group :inline t
134                                           (const :format "" :value :function)
135                                           (function :tag "Function"))
136                                    (group :inline t
137                                           (const :format ""
138                                                  :value :authentication)
139                                           (choice :tag "Authentication"
140                                                   :value apop
141                                                   (const password)
142                                                   (const apop)))
143                                    (group :inline t
144                                           (const :format "" :value :plugged)
145                                           (boolean :tag "Plugged"))))
146                   (cons :tag "Maildir (qmail, postfix...)"
147                         (const :format "" maildir)
148                         (checklist :tag "Options" :greedy t
149                                    (group :inline t
150                                           (const :format "" :value :path)
151                                           (directory :tag "Path"))
152                                    (group :inline t
153                                           (const :format "" :value :plugged)
154                                           (boolean :tag "Plugged"))))
155                   (cons :tag "IMAP server"
156                         (const :format "" imap)
157                         (checklist :tag "Options" :greedy t
158                                    (group :inline t
159                                           (const :format "" :value :server)
160                                           (string :tag "Server"))
161                                    (group :inline t
162                                           (const :format "" :value :port)
163                                           (choice :tag "Port"
164                                                   :value 143
165                                                   number string))
166                                    (group :inline t
167                                           (const :format "" :value :user)
168                                           (string :tag "User"))
169                                    (group :inline t
170                                           (const :format "" :value :password)
171                                           (string :tag "Password"))
172                                    (group :inline t
173                                           (const :format "" :value :stream)
174                                           (choice :tag "Stream"
175                                                   :value network
176                                                   ,@mail-source-imap-streams))
177                                    (group :inline t
178                                           (const :format "" :value :program)
179                                           (string :tag "Program"))
180                                    (group :inline t
181                                           (const :format ""
182                                                  :value :authenticator)
183                                           (choice :tag "Authenticator"
184                                                   :value login
185                                                   ,@mail-source-imap-authenticators))
186                                    (group :inline t
187                                           (const :format "" :value :mailbox)
188                                           (string :tag "Mailbox"
189                                                   :value "INBOX"))
190                                    (group :inline t
191                                           (const :format "" :value :predicate)
192                                           (string :tag "Predicate"
193                                                   :value "UNSEEN UNDELETED"))
194                                    (group :inline t
195                                           (const :format "" :value :fetchflag)
196                                           (string :tag "Fetchflag"
197                                                   :value  "\\Deleted"))
198                                    (group :inline t
199                                           (const :format ""
200                                                  :value :dontexpunge)
201                                           (boolean :tag "Dontexpunge"))
202                                    (group :inline t
203                                           (const :format "" :value :plugged)
204                                           (boolean :tag "Plugged"))))
205                   (cons :tag "Webmail server"
206                         (const :format "" webmail)
207                         (checklist :tag "Options" :greedy t
208                                    (group :inline t
209                                          (const :format "" :value :subtype)
210                                          ;; Should be generated from
211                                          ;; `webmail-type-definition', but we
212                                          ;; can't require webmail without W3.
213                                          (choice :tag "Subtype"
214                                                  :value hotmail
215                                                  (const hotmail)
216                                                  (const yahoo)
217                                                  (const netaddress)
218                                                  (const netscape)
219                                                  (const my-deja)))
220                                    (group :inline t
221                                           (const :format "" :value :user)
222                                           (string :tag "User"))
223                                    (group :inline t
224                                           (const :format "" :value :password)
225                                           (string :tag "Password"))
226                                    (group :inline t
227                                           (const :format ""
228                                                  :value :dontexpunge)
229                                           (boolean :tag "Dontexpunge"))
230                                    (group :inline t
231                                           (const :format "" :value :plugged)
232                                           (boolean :tag "Plugged")))))))
233
234 (defcustom mail-source-ignore-errors nil
235   "*Ignore errors when querying mail sources.
236 If nil, the user will be prompted when an error occurs.  If non-nil,
237 the error will be ignored."
238   :version "21.4"
239   :group 'mail-source
240   :type 'boolean)
241
242 (defcustom mail-source-primary-source nil
243   "*Primary source for incoming mail.
244 If non-nil, this maildrop will be checked periodically for new mail."
245   :group 'mail-source
246   :type 'sexp)
247
248 (defcustom mail-source-flash t
249   "*If non-nil, flash periodically when mail is available."
250   :group 'mail-source
251   :type 'boolean)
252
253 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
254   "File where mail will be stored while processing it."
255   :group 'mail-source
256   :type 'file)
257
258 (defcustom mail-source-directory message-directory
259   "Directory where incoming mail source files (if any) will be stored."
260   :group 'mail-source
261   :type 'directory)
262
263 (defcustom mail-source-default-file-modes 384
264   "Set the mode bits of all new mail files to this integer."
265   :group 'mail-source
266   :type 'integer)
267
268 (defcustom mail-source-delete-incoming nil
269   "*If non-nil, delete incoming files after handling.
270 If t, delete immediately, if nil, never delete.  If a positive number, delete
271 files older than number of days."
272   ;; Note: The removing happens in `mail-source-callback', i.e. no old
273   ;; incoming files will be deleted, unless you receive new mail.
274   ;;
275   ;; You may also set this to `nil' and call `mail-source-delete-old-incoming'
276   ;; from a hook or interactively.
277   :group 'mail-source
278   :type '(choice (const :tag "immediately" t)
279                  (const :tag "never" nil)
280                  (integer :tag "days")))
281
282 (defcustom mail-source-delete-old-incoming-confirm t
283   "*If non-nil, ask for for confirmation before deleting old incoming files.
284 This variable only applies when `mail-source-delete-incoming' is a positive
285 number."
286   :version "21.4"
287   :group 'mail-source
288   :type 'boolean)
289
290 (defcustom mail-source-incoming-file-prefix "Incoming"
291   "Prefix for file name for storing incoming mail"
292   :group 'mail-source
293   :type 'string)
294
295 (defcustom mail-source-report-new-mail-interval 5
296   "Interval in minutes between checks for new mail."
297   :group 'mail-source
298   :type 'number)
299
300 (defcustom mail-source-idle-time-delay 5
301   "Number of idle seconds to wait before checking for new mail."
302   :group 'mail-source
303   :type 'number)
304
305 (defcustom mail-source-movemail-program nil
306   "If non-nil, name of program for fetching new mail."
307   :version "21.4"
308   :group 'mail-source
309   :type '(choice (const nil) string))
310
311 ;;; Internal variables.
312
313 (defvar mail-source-string ""
314   "A dynamically bound string that says what the current mail source is.")
315
316 (defvar mail-source-new-mail-available nil
317   "Flag indicating when new mail is available.")
318
319 (eval-and-compile
320   (defvar mail-source-common-keyword-map
321     '((:plugged))
322     "Mapping from keywords to default values.
323 Common keywords should be listed here.")
324
325   (defvar mail-source-keyword-map
326     '((file
327        (:prescript)
328        (:prescript-delay)
329        (:postscript)
330        (:path (or (getenv "MAIL")
331                   (expand-file-name (user-login-name) rmail-spool-directory))))
332       (directory
333        (:prescript)
334        (:prescript-delay)
335        (:postscript)
336        (:path)
337        (:suffix ".spool")
338        (:predicate identity))
339       (pop
340        (:prescript)
341        (:prescript-delay)
342        (:postscript)
343        (:server (getenv "MAILHOST"))
344        (:port 110)
345        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
346        (:program)
347        (:function)
348        (:password)
349        (:authentication password))
350       (maildir
351        (:path (or (getenv "MAILDIR") "~/Maildir/"))
352        (:subdirs ("cur" "new"))
353        (:function))
354       (imap
355        (:server (getenv "MAILHOST"))
356        (:port)
357        (:stream)
358        (:program)
359        (:authentication)
360        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
361        (:password)
362        (:mailbox "INBOX")
363        (:predicate "UNSEEN UNDELETED")
364        (:fetchflag "\\Deleted")
365        (:prescript)
366        (:prescript-delay)
367        (:postscript)
368        (:dontexpunge))
369       (webmail
370        (:subtype hotmail)
371        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
372        (:password)
373        (:dontexpunge)
374        (:authentication password)))
375     "Mapping from keywords to default values.
376 All keywords that can be used must be listed here."))
377
378 (defvar mail-source-fetcher-alist
379   '((file mail-source-fetch-file)
380     (directory mail-source-fetch-directory)
381     (pop mail-source-fetch-pop)
382     (maildir mail-source-fetch-maildir)
383     (imap mail-source-fetch-imap)
384     (webmail mail-source-fetch-webmail))
385   "A mapping from source type to fetcher function.")
386
387 (defvar mail-source-password-cache nil)
388
389 (defvar mail-source-plugged t)
390
391 ;;; Functions
392
393 (eval-and-compile
394   (defun mail-source-strip-keyword (keyword)
395     "Strip the leading colon off the KEYWORD."
396     (intern (substring (symbol-name keyword) 1))))
397
398 (eval-and-compile
399   (defun mail-source-bind-1 (type)
400     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
401            default bind)
402       (while (setq default (pop defaults))
403         (push (list (mail-source-strip-keyword (car default))
404                     nil)
405               bind))
406       bind)))
407
408 (defmacro mail-source-bind (type-source &rest body)
409   "Return a `let' form that binds all variables in source TYPE.
410 TYPE-SOURCE is a list where the first element is the TYPE, and
411 the second variable is the SOURCE.
412 At run time, the mail source specifier SOURCE will be inspected,
413 and the variables will be set according to it.  Variables not
414 specified will be given default values.
415
416 After this is done, BODY will be executed in the scope
417 of the `let' form.
418
419 The variables bound and their default values are described by
420 the `mail-source-keyword-map' variable."
421   `(let ,(mail-source-bind-1 (car type-source))
422      (mail-source-set-1 ,(cadr type-source))
423      ,@body))
424
425 (put 'mail-source-bind 'lisp-indent-function 1)
426 (put 'mail-source-bind 'edebug-form-spec '(sexp body))
427
428 (defun mail-source-set-1 (source)
429   (let* ((type (pop source))
430          (defaults (cdr (assq type mail-source-keyword-map)))
431          default value keyword)
432     (while (setq default (pop defaults))
433       (set (mail-source-strip-keyword (setq keyword (car default)))
434            (if (setq value (plist-get source keyword))
435                (mail-source-value value)
436              (mail-source-value (cadr default)))))))
437
438 (eval-and-compile
439   (defun mail-source-bind-common-1 ()
440     (let* ((defaults mail-source-common-keyword-map)
441            default bind)
442       (while (setq default (pop defaults))
443         (push (list (mail-source-strip-keyword (car default))
444                     nil)
445               bind))
446       bind)))
447
448 (defun mail-source-set-common-1 (source)
449   (let* ((type (pop source))
450          (defaults mail-source-common-keyword-map)
451          (defaults-1 (cdr (assq type mail-source-keyword-map)))
452          default value keyword)
453     (while (setq default (pop defaults))
454       (set (mail-source-strip-keyword (setq keyword (car default)))
455            (if (setq value (plist-get source keyword))
456                (mail-source-value value)
457              (if (setq value (assq  keyword defaults-1))
458                  (mail-source-value (cadr value))
459                (mail-source-value (cadr default))))))))
460
461 (defmacro mail-source-bind-common (source &rest body)
462   "Return a `let' form that binds all common variables.
463 See `mail-source-bind'."
464   `(let ,(mail-source-bind-common-1)
465      (mail-source-set-common-1 source)
466      ,@body))
467
468 (put 'mail-source-bind-common 'lisp-indent-function 1)
469 (put 'mail-source-bind-common 'edebug-form-spec '(sexp body))
470
471 (defun mail-source-value (value)
472   "Return the value of VALUE."
473   (cond
474    ;; String
475    ((stringp value)
476     value)
477    ;; Function
478    ((and (listp value)
479          (functionp (car value)))
480     (eval value))
481    ;; Just return the value.
482    (t
483     value)))
484
485 (defun mail-source-fetch (source callback)
486   "Fetch mail from SOURCE and call CALLBACK zero or more times.
487 CALLBACK will be called with the name of the file where (some of)
488 the mail from SOURCE is put.
489 Return the number of files that were found."
490   (mail-source-bind-common source
491     (if (or mail-source-plugged plugged)
492         (save-excursion
493           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
494                 (found 0))
495             (unless function
496               (error "%S is an invalid mail source specification" source))
497             ;; If there's anything in the crash box, we do it first.
498             (when (file-exists-p mail-source-crash-box)
499               (message "Processing mail from %s..." mail-source-crash-box)
500               (setq found (mail-source-callback
501                            callback mail-source-crash-box))
502               (mail-source-delete-crash-box))
503             (+ found
504                (if (or debug-on-quit debug-on-error)
505                    (funcall function source callback)
506                  (condition-case err
507                      (funcall function source callback)
508                    (error
509                     (if (and (not mail-source-ignore-errors)
510                              (not
511                               (yes-or-no-p
512                                (format "Mail source %s error (%s).  Continue? "
513                                        (if (memq ':password source)
514                                            (let ((s (copy-sequence source)))
515                                              (setcar (cdr (memq ':password s)) 
516                                                      "********")
517                                              s)
518                                          source)
519                                        (cadr err)))))
520                       (error "Cannot get new mail"))
521                     0)))))))))
522
523 (defun mail-source-delete-old-incoming (&optional age confirm)
524   "Remove incoming files older than AGE days.
525 If CONFIRM is non-nil, ask for confirmation before removing a file."
526   (interactive "P")
527   (let* ((high2days (/ 65536.0 60 60 24));; convert high bits to days
528          (low2days  (/ 1.0 65536.0))     ;; convert low bits to days
529          (diff (if (natnump age) age 30));; fallback, if no valid AGE given
530          currday files)
531     (setq files (directory-files
532                  mail-source-directory t
533                  (concat mail-source-incoming-file-prefix "*"))
534           currday (* (car (current-time)) high2days)
535           currday (+ currday (* low2days (nth 1 (current-time)))))
536     (while files
537       (let* ((ffile (car files))
538              (bfile (gnus-replace-in-string
539                      ffile "\\`.*/\\([^/]+\\)\\'" "\\1"))
540              (filetime (nth 5 (file-attributes ffile)))
541              (fileday (* (car filetime) high2days))
542              (fileday (+ fileday (* low2days (nth 1 filetime)))))
543         (setq files (cdr files))
544         (when (and (> (- currday fileday) diff)
545                    (gnus-message 8 "File `%s' is older than %s day(s)"
546                                  bfile diff)
547                    (or (not confirm)
548                        (y-or-n-p (concat "Remove file `" bfile "'? "))))
549           (delete-file ffile))))))
550
551 (defun mail-source-callback (callback info)
552   "Call CALLBACK on the mail file.  Pass INFO on to CALLBACK."
553   (if (or (not (file-exists-p mail-source-crash-box))
554           (zerop (nth 7 (file-attributes mail-source-crash-box))))
555       (progn
556         (when (file-exists-p mail-source-crash-box)
557           (delete-file mail-source-crash-box))
558         0)
559     (funcall callback mail-source-crash-box info)))
560
561 (defun mail-source-delete-crash-box ()
562   (when (file-exists-p mail-source-crash-box)
563     ;; Delete or move the incoming mail out of the way.
564     (if (eq mail-source-delete-incoming t)
565         (delete-file mail-source-crash-box)
566       (let ((incoming
567              (mm-make-temp-file
568               (expand-file-name
569                mail-source-incoming-file-prefix
570                mail-source-directory))))
571         (unless (file-exists-p (file-name-directory incoming))
572           (make-directory (file-name-directory incoming) t))
573         (rename-file mail-source-crash-box incoming t)
574         ;; remove old incoming files?
575         (when (natnump mail-source-delete-incoming)
576           (mail-source-delete-old-incoming
577            mail-source-delete-incoming
578            mail-source-delete-old-incoming-confirm))))))
579
580 (defun mail-source-movemail (from to)
581   "Move FROM to TO using movemail."
582   (if (not (file-writable-p to))
583       (error "Can't write to crash box %s.  Not moving mail" to)
584     (let ((to (file-truename (expand-file-name to)))
585           errors result)
586       (setq to (file-truename to)
587             from (file-truename from))
588       ;; Set TO if have not already done so, and rename or copy
589       ;; the file FROM to TO if and as appropriate.
590       (cond
591        ((file-exists-p to)
592         ;; The crash box exists already.
593         t)
594        ((not (file-exists-p from))
595         ;; There is no inbox.
596         (setq to nil))
597        ((zerop (nth 7 (file-attributes from)))
598         ;; Empty file.
599         (setq to nil))
600        (t
601         ;; If getting from mail spool directory, use movemail to move
602         ;; rather than just renaming, so as to interlock with the
603         ;; mailer.
604         (unwind-protect
605             (save-excursion
606               (setq errors (generate-new-buffer " *mail source loss*"))
607               (let ((default-directory "/"))
608                 (setq result
609                       (apply
610                        'call-process
611                        (append
612                         (list
613                          (or mail-source-movemail-program
614                              (expand-file-name "movemail" exec-directory))
615                          nil errors nil from to)))))
616               (when (file-exists-p to)
617                 (set-file-modes to mail-source-default-file-modes))
618               (if (and (or (not (buffer-modified-p errors))
619                            (zerop (buffer-size errors)))
620                        (and (numberp result)
621                             (zerop result)))
622                   ;; No output => movemail won.
623                   t
624                 (set-buffer errors)
625                 ;; There may be a warning about older revisions.  We
626                 ;; ignore that.
627                 (goto-char (point-min))
628                 (if (search-forward "older revision" nil t)
629                     t
630                   ;; Probably a real error.
631                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
632                   (goto-char (point-max))
633                   (skip-chars-backward " \t")
634                   (delete-region (point) (point-max))
635                   (goto-char (point-min))
636                   (when (looking-at "movemail: ")
637                     (delete-region (point-min) (match-end 0)))
638                   ;; Result may be a signal description string.
639                   (unless (yes-or-no-p
640                            (format "movemail: %s (%s return).  Continue? "
641                                    (buffer-string) result))
642                     (error "%s" (buffer-string)))
643                   (setq to nil)))))))
644       (when (and errors
645                  (buffer-name errors))
646         (kill-buffer errors))
647       ;; Return whether we moved successfully or not.
648       to)))
649
650 (defun mail-source-movemail-and-remove (from to)
651   "Move FROM to TO using movemail, then remove FROM if empty."
652   (or (not (mail-source-movemail from to))
653       (not (zerop (nth 7 (file-attributes from))))
654       (delete-file from)))
655
656 (defun mail-source-fetch-with-program (program)
657   (eq 0 (call-process shell-file-name nil nil nil
658                       shell-command-switch program)))
659
660 (defun mail-source-run-script (script spec &optional delay)
661   (when script
662     (if (functionp script)
663         (funcall script)
664       (mail-source-call-script
665        (format-spec script spec))))
666   (when delay
667     (sleep-for delay)))
668
669 (defun mail-source-call-script (script)
670   (let ((background nil))
671     (when (string-match "& *$" script)
672       (setq script (substring script 0 (match-beginning 0))
673             background 0))
674     (call-process shell-file-name nil background nil
675                   shell-command-switch script)))
676
677 ;;;
678 ;;; Different fetchers
679 ;;;
680
681 (defun mail-source-fetch-file (source callback)
682   "Fetcher for single-file sources."
683   (mail-source-bind (file source)
684     (mail-source-run-script
685      prescript (format-spec-make ?t mail-source-crash-box)
686      prescript-delay)
687     (let ((mail-source-string (format "file:%s" path)))
688       (if (mail-source-movemail path mail-source-crash-box)
689           (prog1
690               (mail-source-callback callback path)
691             (mail-source-run-script
692              postscript (format-spec-make ?t mail-source-crash-box))
693             (mail-source-delete-crash-box))
694         0))))
695
696 (defun mail-source-fetch-directory (source callback)
697   "Fetcher for directory sources."
698   (mail-source-bind (directory source)
699     (mail-source-run-script
700      prescript (format-spec-make ?t path) prescript-delay)
701     (let ((found 0)
702           (mail-source-string (format "directory:%s" path)))
703       (dolist (file (directory-files
704                      path t (concat (regexp-quote suffix) "$")))
705         (when (and (file-regular-p file)
706                    (funcall predicate file)
707                    (mail-source-movemail file mail-source-crash-box))
708           (incf found (mail-source-callback callback file))
709           (mail-source-run-script postscript (format-spec-make ?t path))
710           (mail-source-delete-crash-box)))
711       found)))
712
713 (defun mail-source-fetch-pop (source callback)
714   "Fetcher for single-file sources."
715   (mail-source-bind (pop source)
716     (mail-source-run-script
717      prescript
718      (format-spec-make ?p password ?t mail-source-crash-box
719                        ?s server ?P port ?u user)
720      prescript-delay)
721     (let ((from (format "%s:%s:%s" server user port))
722           (mail-source-string (format "pop:%s@%s" user server))
723           result)
724       (when (eq authentication 'password)
725         (setq password
726               (or password
727                   (cdr (assoc from mail-source-password-cache))
728                   (read-passwd
729                    (format "Password for %s at %s: " user server)))))
730       (when server
731         (setenv "MAILHOST" server))
732       (setq result
733             (cond
734              (program
735               (mail-source-fetch-with-program
736                (format-spec
737                 program
738                 (format-spec-make ?p password ?t mail-source-crash-box
739                                   ?s server ?P port ?u user))))
740              (function
741               (funcall function mail-source-crash-box))
742              ;; The default is to use pop3.el.
743              (t
744               (let ((pop3-password password)
745                     (pop3-maildrop user)
746                     (pop3-mailhost server)
747                     (pop3-port port)
748                     (pop3-authentication-scheme
749                      (if (eq authentication 'apop) 'apop 'pass)))
750                 (if (or debug-on-quit debug-on-error)
751                     (save-excursion (pop3-movemail mail-source-crash-box))
752                   (condition-case err
753                       (save-excursion (pop3-movemail mail-source-crash-box))
754                     (error
755                      ;; We nix out the password in case the error
756                      ;; was because of a wrong password being given.
757                      (setq mail-source-password-cache
758                            (delq (assoc from mail-source-password-cache)
759                                  mail-source-password-cache))
760                      (signal (car err) (cdr err)))))))))
761       (if result
762           (progn
763             (when (eq authentication 'password)
764               (unless (assoc from mail-source-password-cache)
765                 (push (cons from password) mail-source-password-cache)))
766             (prog1
767                 (mail-source-callback callback server)
768               ;; Update display-time's mail flag, if relevant.
769               (if (equal source mail-source-primary-source)
770                   (setq mail-source-new-mail-available nil))
771               (mail-source-run-script
772                postscript
773                (format-spec-make ?p password ?t mail-source-crash-box
774                                  ?s server ?P port ?u user))
775               (mail-source-delete-crash-box)))
776         ;; We nix out the password in case the error
777         ;; was because of a wrong password being given.
778         (setq mail-source-password-cache
779               (delq (assoc from mail-source-password-cache)
780                     mail-source-password-cache))
781         0))))
782
783 (defun mail-source-check-pop (source)
784   "Check whether there is new mail."
785   (mail-source-bind (pop source)
786     (let ((from (format "%s:%s:%s" server user port))
787           (mail-source-string (format "pop:%s@%s" user server))
788           result)
789       (when (eq authentication 'password)
790         (setq password
791               (or password
792                   (cdr (assoc from mail-source-password-cache))
793                   (read-passwd
794                    (format "Password for %s at %s: " user server))))
795         (unless (assoc from mail-source-password-cache)
796           (push (cons from password) mail-source-password-cache)))
797       (when server
798         (setenv "MAILHOST" server))
799       (setq result
800             (cond
801              ;; No easy way to check whether mail is waiting for these.
802              (program)
803              (function)
804              ;; The default is to use pop3.el.
805              (t
806               (let ((pop3-password password)
807                     (pop3-maildrop user)
808                     (pop3-mailhost server)
809                     (pop3-port port)
810                     (pop3-authentication-scheme
811                      (if (eq authentication 'apop) 'apop 'pass)))
812                 (if (or debug-on-quit debug-on-error)
813                     (save-excursion (pop3-get-message-count))
814                   (condition-case err
815                       (save-excursion (pop3-get-message-count))
816                     (error
817                      ;; We nix out the password in case the error
818                      ;; was because of a wrong password being given.
819                      (setq mail-source-password-cache
820                            (delq (assoc from mail-source-password-cache)
821                                  mail-source-password-cache))
822                      (signal (car err) (cdr err)))))))))
823       (if result
824           ;; Inform display-time that we have new mail.
825           (setq mail-source-new-mail-available (> result 0))
826         ;; We nix out the password in case the error
827         ;; was because of a wrong password being given.
828         (setq mail-source-password-cache
829               (delq (assoc from mail-source-password-cache)
830                     mail-source-password-cache)))
831       result)))
832
833 (defun mail-source-touch-pop ()
834   "Open and close a POP connection shortly.
835 POP server should be defined in `mail-source-primary-source' (which is
836 preferred) or `mail-sources'.  You may use it for the POP-before-SMTP
837 authentication.  To do that, you need to set the
838 `message-send-mail-function' variable as `message-smtpmail-send-it'
839 and put the following line in your ~/.gnus.el file:
840
841 \(add-hook 'message-send-mail-hook 'mail-source-touch-pop)
842
843 See the Gnus manual for details."
844   (let ((sources (if mail-source-primary-source
845                      (list mail-source-primary-source)
846                    mail-sources)))
847     (while sources
848       (if (eq 'pop (car (car sources)))
849           (mail-source-check-pop (car sources)))
850       (setq sources (cdr sources)))))
851
852 (defun mail-source-new-mail-p ()
853   "Handler for `display-time' to indicate when new mail is available."
854   ;; Flash (ie. ring the visible bell) if mail is available.
855   (if (and mail-source-flash mail-source-new-mail-available)
856       (let ((visible-bell t))
857         (ding)))
858   ;; Only report flag setting; flag is updated on a different schedule.
859   mail-source-new-mail-available)
860
861
862 (defvar mail-source-report-new-mail nil)
863 (defvar mail-source-report-new-mail-timer nil)
864 (defvar mail-source-report-new-mail-idle-timer nil)
865
866 (eval-when-compile
867   (if (featurep 'xemacs)
868       (require 'itimer)
869     (require 'timer)))
870
871 (defun mail-source-start-idle-timer ()
872   ;; Start our idle timer if necessary, so we delay the check until the
873   ;; user isn't typing.
874   (unless mail-source-report-new-mail-idle-timer
875     (setq mail-source-report-new-mail-idle-timer
876           (run-with-idle-timer
877            mail-source-idle-time-delay
878            nil
879            (lambda ()
880              (unwind-protect
881                  (mail-source-check-pop mail-source-primary-source)
882                (setq mail-source-report-new-mail-idle-timer nil)))))
883     ;; Since idle timers created when Emacs is already in the idle
884     ;; state don't get activated until Emacs _next_ becomes idle, we
885     ;; need to force our timer to be considered active now.  We do
886     ;; this by being naughty and poking the timer internals directly
887     ;; (element 0 of the vector is nil if the timer is active).
888     (aset mail-source-report-new-mail-idle-timer 0 nil)))
889
890 (defun mail-source-report-new-mail (arg)
891   "Toggle whether to report when new mail is available.
892 This only works when `display-time' is enabled."
893   (interactive "P")
894   (if (not mail-source-primary-source)
895       (error "Need to set `mail-source-primary-source' to check for new mail"))
896   (let ((on (if (null arg)
897                 (not mail-source-report-new-mail)
898               (> (prefix-numeric-value arg) 0))))
899     (setq mail-source-report-new-mail on)
900     (and mail-source-report-new-mail-timer
901          (nnheader-cancel-timer mail-source-report-new-mail-timer))
902     (and mail-source-report-new-mail-idle-timer
903          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
904     (setq mail-source-report-new-mail-timer nil)
905     (setq mail-source-report-new-mail-idle-timer nil)
906     (if on
907         (progn
908           (require 'time)
909           ;; display-time-mail-function is an Emacs 21 feature.
910           (setq display-time-mail-function #'mail-source-new-mail-p)
911           ;; Set up the main timer.
912           (setq mail-source-report-new-mail-timer
913                 (run-at-time
914                  (* 60 mail-source-report-new-mail-interval)
915                  (* 60 mail-source-report-new-mail-interval)
916                  #'mail-source-start-idle-timer))
917           ;; When you get new mail, clear "Mail" from the mode line.
918           (add-hook 'nnmail-post-get-new-mail-hook
919                     'display-time-event-handler)
920           (message "Mail check enabled"))
921       (setq display-time-mail-function nil)
922       (remove-hook 'nnmail-post-get-new-mail-hook
923                    'display-time-event-handler)
924       (message "Mail check disabled"))))
925
926 (defun mail-source-fetch-maildir (source callback)
927   "Fetcher for maildir sources."
928   (mail-source-bind (maildir source)
929     (let ((found 0)
930           mail-source-string)
931       (unless (string-match "/$" path)
932         (setq path (concat path "/")))
933       (dolist (subdir subdirs)
934         (when (file-directory-p (concat path subdir))
935           (setq mail-source-string (format "maildir:%s%s" path subdir))
936           (dolist (file (directory-files (concat path subdir) t))
937             (when (and (not (file-directory-p file))
938                        (not (if function
939                                 (funcall function file mail-source-crash-box)
940                               (let ((coding-system-for-write
941                                      mm-text-coding-system)
942                                     (coding-system-for-read
943                                      mm-text-coding-system))
944                                 (with-temp-file mail-source-crash-box
945                                   (insert-file-contents file)
946                                   (goto-char (point-min))
947 ;;;                               ;; Unix mail format
948 ;;;                               (unless (looking-at "\n*From ")
949 ;;;                                 (insert "From maildir "
950 ;;;                                         (current-time-string) "\n"))
951 ;;;                               (while (re-search-forward "^From " nil t)
952 ;;;                                 (replace-match ">From "))
953 ;;;                               (goto-char (point-max))
954 ;;;                               (insert "\n\n")
955                                   ;; MMDF mail format
956                                   (insert "\001\001\001\001\n"))
957                                 (delete-file file)))))
958               (incf found (mail-source-callback callback file))
959               (mail-source-delete-crash-box)))))
960       found)))
961
962 (eval-and-compile
963   (autoload 'imap-open "imap")
964   (autoload 'imap-authenticate "imap")
965   (autoload 'imap-mailbox-select "imap")
966   (autoload 'imap-mailbox-unselect "imap")
967   (autoload 'imap-mailbox-close "imap")
968   (autoload 'imap-search "imap")
969   (autoload 'imap-fetch "imap")
970   (autoload 'imap-close "imap")
971   (autoload 'imap-error-text "imap")
972   (autoload 'imap-message-flags-add "imap")
973   (autoload 'imap-list-to-message-set "imap")
974   (autoload 'imap-range-to-message-set "imap")
975   (autoload 'nnheader-ms-strip-cr "nnheader"))
976
977 (defvar mail-source-imap-file-coding-system 'binary
978   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
979
980 (defun mail-source-fetch-imap (source callback)
981   "Fetcher for imap sources."
982   (mail-source-bind (imap source)
983     (mail-source-run-script
984      prescript (format-spec-make ?p password ?t mail-source-crash-box
985                                  ?s server ?P port ?u user)
986      prescript-delay)
987     (let ((from (format "%s:%s:%s" server user port))
988           (found 0)
989           (buf (generate-new-buffer " *imap source*"))
990           (mail-source-string (format "imap:%s:%s" server mailbox))
991           (imap-shell-program (or (list program) imap-shell-program))
992           remove)
993       (if (and (imap-open server port stream authentication buf)
994                (imap-authenticate
995                 user (or (cdr (assoc from mail-source-password-cache))
996                          password) buf)
997                (imap-mailbox-select mailbox nil buf))
998           (let ((coding-system-for-write mail-source-imap-file-coding-system)
999                 str)
1000             (with-temp-file mail-source-crash-box
1001               ;; Avoid converting 8-bit chars from inserted strings to
1002               ;; multibyte.
1003               (mm-disable-multibyte)
1004               ;; remember password
1005               (with-current-buffer buf
1006                 (when (and imap-password
1007                            (not (assoc from mail-source-password-cache)))
1008                   (push (cons from imap-password) mail-source-password-cache)))
1009               ;; if predicate is nil, use all uids
1010               (dolist (uid (imap-search (or predicate "1:*") buf))
1011                 (when (setq str
1012                             (if (imap-capability 'IMAP4rev1 buf)
1013                                 (caddar (imap-fetch uid "BODY.PEEK[]"
1014                                                     'BODYDETAIL nil buf))
1015                               (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf)))
1016                   (push uid remove)
1017                   (insert "From imap " (current-time-string) "\n")
1018                   (save-excursion
1019                     (insert str "\n\n"))
1020                   (while (re-search-forward "^From " nil t)
1021                     (replace-match ">From "))
1022                   (goto-char (point-max))))
1023               (nnheader-ms-strip-cr))
1024             (incf found (mail-source-callback callback server))
1025             (mail-source-delete-crash-box)
1026             (when (and remove fetchflag)
1027               (setq remove (nreverse remove))
1028               (imap-message-flags-add
1029                (imap-range-to-message-set (gnus-compress-sequence remove))
1030                fetchflag nil buf))
1031             (if dontexpunge
1032                 (imap-mailbox-unselect buf)
1033               (imap-mailbox-close nil buf))
1034             (imap-close buf))
1035         (imap-close buf)
1036         ;; We nix out the password in case the error
1037         ;; was because of a wrong password being given.
1038         (setq mail-source-password-cache
1039               (delq (assoc from mail-source-password-cache)
1040                     mail-source-password-cache))
1041         (error "IMAP error: %s" (imap-error-text buf)))
1042       (kill-buffer buf)
1043       (mail-source-run-script
1044        postscript
1045        (format-spec-make ?p password ?t mail-source-crash-box
1046                          ?s server ?P port ?u user))
1047       found)))
1048
1049 (eval-and-compile
1050   (autoload 'webmail-fetch "webmail"))
1051
1052 (defun mail-source-fetch-webmail (source callback)
1053   "Fetch for webmail source."
1054   (mail-source-bind (webmail source)
1055     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
1056           (webmail-newmail-only dontexpunge)
1057           (webmail-move-to-trash-can (not dontexpunge)))
1058       (when (eq authentication 'password)
1059         (setq password
1060               (or password
1061                   (cdr (assoc (format "webmail:%s:%s" subtype user)
1062                               mail-source-password-cache))
1063                   (read-passwd
1064                    (format "Password for %s at %s: " user subtype))))
1065         (when (and password
1066                    (not (assoc (format "webmail:%s:%s" subtype user)
1067                                mail-source-password-cache)))
1068           (push (cons (format "webmail:%s:%s" subtype user) password)
1069                 mail-source-password-cache)))
1070       (webmail-fetch mail-source-crash-box subtype user password)
1071       (mail-source-callback callback (symbol-name subtype))
1072       (mail-source-delete-crash-box))))
1073
1074 (provide 'mail-source)
1075
1076 ;;; arch-tag: 72948025-1d17-4d6c-bb12-ef1aa2c490fd
1077 ;;; mail-source.el ends here