* mail-source.el (mail-source-directory): Fix doc-string.
[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
239 (defcustom mail-source-primary-source nil
240   "*Primary source for incoming mail.
241 If non-nil, this maildrop will be checked periodically for new mail."
242   :group 'mail-source
243   :type 'sexp)
244
245 (defcustom mail-source-flash t
246   "*If non-nil, flash periodically when mail is available."
247   :group 'mail-source
248   :type 'boolean)
249
250 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
251   "File where mail will be stored while processing it."
252   :group 'mail-source
253   :type 'file)
254
255 (defcustom mail-source-directory message-directory
256   "Directory where incoming mail source files (if any) will be stored."
257   :group 'mail-source
258   :type 'directory)
259
260 (defcustom mail-source-default-file-modes 384
261   "Set the mode bits of all new mail files to this integer."
262   :group 'mail-source
263   :type 'integer)
264
265 (defcustom mail-source-delete-incoming nil
266   "*If non-nil, delete incoming files after handling.
267 If t, delete immediately, if nil, never delete.  If a positive number, delete
268 files older than number of days."
269   ;; Note: The removing happens in `mail-source-callback', i.e. no old
270   ;; incoming files will be deleted, unless you receive new mail.
271   ;;
272   ;; You may also set this to `nil' and call `mail-source-delete-old-incoming'
273   ;; from a hook or interactively.
274   :group 'mail-source
275   :type '(choice (const :tag "immediately" t)
276                  (const :tag "never" nil)
277                  (integer :tag "days")))
278
279 (defcustom mail-source-delete-old-incoming-confirm t
280   "*If non-nil, ask for for confirmation before deleting old incoming files.
281 This variable only applies when `mail-source-delete-incoming' is a positive
282 number."
283   :group 'mail-source
284   :type 'boolean)
285
286 (defcustom mail-source-incoming-file-prefix "Incoming"
287   "Prefix for file name for storing incoming mail"
288   :group 'mail-source
289   :type 'string)
290
291 (defcustom mail-source-report-new-mail-interval 5
292   "Interval in minutes between checks for new mail."
293   :group 'mail-source
294   :type 'number)
295
296 (defcustom mail-source-idle-time-delay 5
297   "Number of idle seconds to wait before checking for new mail."
298   :group 'mail-source
299   :type 'number)
300
301 (defcustom mail-source-movemail-program nil
302   "If non-nil, name of program for fetching new mail."
303   :group 'mail-source
304   :type '(choice (const nil) string))
305
306 ;;; Internal variables.
307
308 (defvar mail-source-string ""
309   "A dynamically bound string that says what the current mail source is.")
310
311 (defvar mail-source-new-mail-available nil
312   "Flag indicating when new mail is available.")
313
314 (eval-and-compile
315   (defvar mail-source-common-keyword-map
316     '((:plugged))
317     "Mapping from keywords to default values.
318 Common keywords should be listed here.")
319
320   (defvar mail-source-keyword-map
321     '((file
322        (:prescript)
323        (:prescript-delay)
324        (:postscript)
325        (:path (or (getenv "MAIL")
326                   (expand-file-name (user-login-name) rmail-spool-directory))))
327       (directory
328        (:prescript)
329        (:prescript-delay)
330        (:postscript)
331        (:path)
332        (:suffix ".spool")
333        (:predicate identity))
334       (pop
335        (:prescript)
336        (:prescript-delay)
337        (:postscript)
338        (:server (getenv "MAILHOST"))
339        (:port 110)
340        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
341        (:program)
342        (:function)
343        (:password)
344        (:authentication password))
345       (maildir
346        (:path (or (getenv "MAILDIR") "~/Maildir/"))
347        (:subdirs ("cur" "new"))
348        (:function))
349       (imap
350        (:server (getenv "MAILHOST"))
351        (:port)
352        (:stream)
353        (:program)
354        (:authentication)
355        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
356        (:password)
357        (:mailbox "INBOX")
358        (:predicate "UNSEEN UNDELETED")
359        (:fetchflag "\\Deleted")
360        (:prescript)
361        (:prescript-delay)
362        (:postscript)
363        (:dontexpunge))
364       (webmail
365        (:subtype hotmail)
366        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
367        (:password)
368        (:dontexpunge)
369        (:authentication password)))
370     "Mapping from keywords to default values.
371 All keywords that can be used must be listed here."))
372
373 (defvar mail-source-fetcher-alist
374   '((file mail-source-fetch-file)
375     (directory mail-source-fetch-directory)
376     (pop mail-source-fetch-pop)
377     (maildir mail-source-fetch-maildir)
378     (imap mail-source-fetch-imap)
379     (webmail mail-source-fetch-webmail))
380   "A mapping from source type to fetcher function.")
381
382 (defvar mail-source-password-cache nil)
383
384 (defvar mail-source-plugged t)
385
386 ;;; Functions
387
388 (eval-and-compile
389   (defun mail-source-strip-keyword (keyword)
390     "Strip the leading colon off the KEYWORD."
391     (intern (substring (symbol-name keyword) 1))))
392
393 (eval-and-compile
394   (defun mail-source-bind-1 (type)
395     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
396            default bind)
397       (while (setq default (pop defaults))
398         (push (list (mail-source-strip-keyword (car default))
399                     nil)
400               bind))
401       bind)))
402
403 (defmacro mail-source-bind (type-source &rest body)
404   "Return a `let' form that binds all variables in source TYPE.
405 TYPE-SOURCE is a list where the first element is the TYPE, and
406 the second variable is the SOURCE.
407 At run time, the mail source specifier SOURCE will be inspected,
408 and the variables will be set according to it.  Variables not
409 specified will be given default values.
410
411 After this is done, BODY will be executed in the scope
412 of the `let' form.
413
414 The variables bound and their default values are described by
415 the `mail-source-keyword-map' variable."
416   `(let ,(mail-source-bind-1 (car type-source))
417      (mail-source-set-1 ,(cadr type-source))
418      ,@body))
419
420 (put 'mail-source-bind 'lisp-indent-function 1)
421 (put 'mail-source-bind 'edebug-form-spec '(sexp body))
422
423 (defun mail-source-set-1 (source)
424   (let* ((type (pop source))
425          (defaults (cdr (assq type mail-source-keyword-map)))
426          default value keyword)
427     (while (setq default (pop defaults))
428       (set (mail-source-strip-keyword (setq keyword (car default)))
429            (if (setq value (plist-get source keyword))
430                (mail-source-value value)
431              (mail-source-value (cadr default)))))))
432
433 (eval-and-compile
434   (defun mail-source-bind-common-1 ()
435     (let* ((defaults mail-source-common-keyword-map)
436            default bind)
437       (while (setq default (pop defaults))
438         (push (list (mail-source-strip-keyword (car default))
439                     nil)
440               bind))
441       bind)))
442
443 (defun mail-source-set-common-1 (source)
444   (let* ((type (pop source))
445          (defaults mail-source-common-keyword-map)
446          (defaults-1 (cdr (assq type mail-source-keyword-map)))
447          default value keyword)
448     (while (setq default (pop defaults))
449       (set (mail-source-strip-keyword (setq keyword (car default)))
450            (if (setq value (plist-get source keyword))
451                (mail-source-value value)
452              (if (setq value (assq  keyword defaults-1))
453                  (mail-source-value (cadr value))
454                (mail-source-value (cadr default))))))))
455
456 (defmacro mail-source-bind-common (source &rest body)
457   "Return a `let' form that binds all common variables.
458 See `mail-source-bind'."
459   `(let ,(mail-source-bind-common-1)
460      (mail-source-set-common-1 source)
461      ,@body))
462
463 (put 'mail-source-bind-common 'lisp-indent-function 1)
464 (put 'mail-source-bind-common 'edebug-form-spec '(sexp body))
465
466 (defun mail-source-value (value)
467   "Return the value of VALUE."
468   (cond
469    ;; String
470    ((stringp value)
471     value)
472    ;; Function
473    ((and (listp value)
474          (functionp (car value)))
475     (eval value))
476    ;; Just return the value.
477    (t
478     value)))
479
480 (defun mail-source-fetch (source callback)
481   "Fetch mail from SOURCE and call CALLBACK zero or more times.
482 CALLBACK will be called with the name of the file where (some of)
483 the mail from SOURCE is put.
484 Return the number of files that were found."
485   (mail-source-bind-common source
486     (if (or mail-source-plugged plugged)
487         (save-excursion
488           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
489                 (found 0))
490             (unless function
491               (error "%S is an invalid mail source specification" source))
492             ;; If there's anything in the crash box, we do it first.
493             (when (file-exists-p mail-source-crash-box)
494               (message "Processing mail from %s..." mail-source-crash-box)
495               (setq found (mail-source-callback
496                            callback mail-source-crash-box))
497               (mail-source-delete-crash-box))
498             (+ found
499                (if (or debug-on-quit debug-on-error)
500                    (funcall function source callback)
501                  (condition-case err
502                      (funcall function source callback)
503                    (error
504                     (if (and (not mail-source-ignore-errors)
505                              (not
506                               (yes-or-no-p
507                                (format "Mail source %s error (%s).  Continue? "
508                                        (if (memq ':password source)
509                                            (let ((s (copy-sequence source)))
510                                              (setcar (cdr (memq ':password s)) 
511                                                      "********")
512                                              s)
513                                          source)
514                                        (cadr err)))))
515                       (error "Cannot get new mail"))
516                     0)))))))))
517
518 (defun mail-source-delete-old-incoming (&optional age confirm)
519   "Remove incoming files older than AGE days.
520 If CONFIRM is non-nil, ask for confirmation before removing a file."
521   (interactive "P")
522   (let* ((high2days (/ 65536.0 60 60 24));; convert high bits to days
523          (low2days  (/ 1.0 65536.0))     ;; convert low bits to days
524          (diff (if (natnump age) age 30));; fallback, if no valid AGE given
525          currday files)
526     (setq files (directory-files
527                  mail-source-directory t
528                  (concat mail-source-incoming-file-prefix "*"))
529           currday (* (car (current-time)) high2days)
530           currday (+ currday (* low2days (nth 1 (current-time)))))
531     (while files
532       (let* ((ffile (car files))
533              (bfile (gnus-replace-in-string
534                      ffile "\\`.*/\\([^/]+\\)\\'" "\\1"))
535              (filetime (nth 5 (file-attributes ffile)))
536              (fileday (* (car filetime) high2days))
537              (fileday (+ fileday (* low2days (nth 1 filetime)))))
538         (setq files (cdr files))
539         (when (and (> (- currday fileday) diff)
540                    (gnus-message 8 "File `%s' is older than %s day(s)"
541                                  bfile diff)
542                    (or (not confirm)
543                        (y-or-n-p (concat "Remove file `" bfile "'? "))))
544           (delete-file ffile))))))
545
546 (defun mail-source-callback (callback info)
547   "Call CALLBACK on the mail file.  Pass INFO on to CALLBACK."
548   (if (or (not (file-exists-p mail-source-crash-box))
549           (zerop (nth 7 (file-attributes mail-source-crash-box))))
550       (progn
551         (when (file-exists-p mail-source-crash-box)
552           (delete-file mail-source-crash-box))
553         0)
554     (funcall callback mail-source-crash-box info)))
555
556 (defun mail-source-delete-crash-box ()
557   (when (file-exists-p mail-source-crash-box)
558     ;; Delete or move the incoming mail out of the way.
559     (if (eq mail-source-delete-incoming t)
560         (delete-file mail-source-crash-box)
561       (let ((incoming
562              (mm-make-temp-file
563               (expand-file-name
564                mail-source-incoming-file-prefix
565                mail-source-directory))))
566         (unless (file-exists-p (file-name-directory incoming))
567           (make-directory (file-name-directory incoming) t))
568         (rename-file mail-source-crash-box incoming t)
569         ;; remove old incoming files?
570         (when (natnump mail-source-delete-incoming)
571           (mail-source-delete-old-incoming
572            mail-source-delete-incoming
573            mail-source-delete-old-incoming-confirm))))))
574
575 (defun mail-source-movemail (from to)
576   "Move FROM to TO using movemail."
577   (if (not (file-writable-p to))
578       (error "Can't write to crash box %s.  Not moving mail" to)
579     (let ((to (file-truename (expand-file-name to)))
580           errors result)
581       (setq to (file-truename to)
582             from (file-truename from))
583       ;; Set TO if have not already done so, and rename or copy
584       ;; the file FROM to TO if and as appropriate.
585       (cond
586        ((file-exists-p to)
587         ;; The crash box exists already.
588         t)
589        ((not (file-exists-p from))
590         ;; There is no inbox.
591         (setq to nil))
592        ((zerop (nth 7 (file-attributes from)))
593         ;; Empty file.
594         (setq to nil))
595        (t
596         ;; If getting from mail spool directory, use movemail to move
597         ;; rather than just renaming, so as to interlock with the
598         ;; mailer.
599         (unwind-protect
600             (save-excursion
601               (setq errors (generate-new-buffer " *mail source loss*"))
602               (let ((default-directory "/"))
603                 (setq result
604                       (apply
605                        'call-process
606                        (append
607                         (list
608                          (or mail-source-movemail-program
609                              (expand-file-name "movemail" exec-directory))
610                          nil errors nil from to)))))
611               (when (file-exists-p to)
612                 (set-file-modes to mail-source-default-file-modes))
613               (if (and (or (not (buffer-modified-p errors))
614                            (zerop (buffer-size errors)))
615                        (and (numberp result)
616                             (zerop result)))
617                   ;; No output => movemail won.
618                   t
619                 (set-buffer errors)
620                 ;; There may be a warning about older revisions.  We
621                 ;; ignore that.
622                 (goto-char (point-min))
623                 (if (search-forward "older revision" nil t)
624                     t
625                   ;; Probably a real error.
626                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
627                   (goto-char (point-max))
628                   (skip-chars-backward " \t")
629                   (delete-region (point) (point-max))
630                   (goto-char (point-min))
631                   (when (looking-at "movemail: ")
632                     (delete-region (point-min) (match-end 0)))
633                   ;; Result may be a signal description string.
634                   (unless (yes-or-no-p
635                            (format "movemail: %s (%s return).  Continue? "
636                                    (buffer-string) result))
637                     (error "%s" (buffer-string)))
638                   (setq to nil)))))))
639       (when (and errors
640                  (buffer-name errors))
641         (kill-buffer errors))
642       ;; Return whether we moved successfully or not.
643       to)))
644
645 (defun mail-source-movemail-and-remove (from to)
646   "Move FROM to TO using movemail, then remove FROM if empty."
647   (or (not (mail-source-movemail from to))
648       (not (zerop (nth 7 (file-attributes from))))
649       (delete-file from)))
650
651 (defun mail-source-fetch-with-program (program)
652   (eq 0 (call-process shell-file-name nil nil nil
653                       shell-command-switch program)))
654
655 (defun mail-source-run-script (script spec &optional delay)
656   (when script
657     (if (functionp script)
658         (funcall script)
659       (mail-source-call-script
660        (format-spec script spec))))
661   (when delay
662     (sleep-for delay)))
663
664 (defun mail-source-call-script (script)
665   (let ((background nil))
666     (when (string-match "& *$" script)
667       (setq script (substring script 0 (match-beginning 0))
668             background 0))
669     (call-process shell-file-name nil background nil
670                   shell-command-switch script)))
671
672 ;;;
673 ;;; Different fetchers
674 ;;;
675
676 (defun mail-source-fetch-file (source callback)
677   "Fetcher for single-file sources."
678   (mail-source-bind (file source)
679     (mail-source-run-script
680      prescript (format-spec-make ?t mail-source-crash-box)
681      prescript-delay)
682     (let ((mail-source-string (format "file:%s" path)))
683       (if (mail-source-movemail path mail-source-crash-box)
684           (prog1
685               (mail-source-callback callback path)
686             (mail-source-run-script
687              postscript (format-spec-make ?t mail-source-crash-box))
688             (mail-source-delete-crash-box))
689         0))))
690
691 (defun mail-source-fetch-directory (source callback)
692   "Fetcher for directory sources."
693   (mail-source-bind (directory source)
694     (mail-source-run-script
695      prescript (format-spec-make ?t path) prescript-delay)
696     (let ((found 0)
697           (mail-source-string (format "directory:%s" path)))
698       (dolist (file (directory-files
699                      path t (concat (regexp-quote suffix) "$")))
700         (when (and (file-regular-p file)
701                    (funcall predicate file)
702                    (mail-source-movemail file mail-source-crash-box))
703           (incf found (mail-source-callback callback file))
704           (mail-source-run-script postscript (format-spec-make ?t path))
705           (mail-source-delete-crash-box)))
706       found)))
707
708 (defun mail-source-fetch-pop (source callback)
709   "Fetcher for single-file sources."
710   (mail-source-bind (pop source)
711     (mail-source-run-script
712      prescript
713      (format-spec-make ?p password ?t mail-source-crash-box
714                        ?s server ?P port ?u user)
715      prescript-delay)
716     (let ((from (format "%s:%s:%s" server user port))
717           (mail-source-string (format "pop:%s@%s" user server))
718           result)
719       (when (eq authentication 'password)
720         (setq password
721               (or password
722                   (cdr (assoc from mail-source-password-cache))
723                   (read-passwd
724                    (format "Password for %s at %s: " user server)))))
725       (when server
726         (setenv "MAILHOST" server))
727       (setq result
728             (cond
729              (program
730               (mail-source-fetch-with-program
731                (format-spec
732                 program
733                 (format-spec-make ?p password ?t mail-source-crash-box
734                                   ?s server ?P port ?u user))))
735              (function
736               (funcall function mail-source-crash-box))
737              ;; The default is to use pop3.el.
738              (t
739               (let ((pop3-password password)
740                     (pop3-maildrop user)
741                     (pop3-mailhost server)
742                     (pop3-port port)
743                     (pop3-authentication-scheme
744                      (if (eq authentication 'apop) 'apop 'pass)))
745                 (if (or debug-on-quit debug-on-error)
746                     (save-excursion (pop3-movemail mail-source-crash-box))
747                   (condition-case err
748                       (save-excursion (pop3-movemail mail-source-crash-box))
749                     (error
750                      ;; We nix out the password in case the error
751                      ;; was because of a wrong password being given.
752                      (setq mail-source-password-cache
753                            (delq (assoc from mail-source-password-cache)
754                                  mail-source-password-cache))
755                      (signal (car err) (cdr err)))))))))
756       (if result
757           (progn
758             (when (eq authentication 'password)
759               (unless (assoc from mail-source-password-cache)
760                 (push (cons from password) mail-source-password-cache)))
761             (prog1
762                 (mail-source-callback callback server)
763               ;; Update display-time's mail flag, if relevant.
764               (if (equal source mail-source-primary-source)
765                   (setq mail-source-new-mail-available nil))
766               (mail-source-run-script
767                postscript
768                (format-spec-make ?p password ?t mail-source-crash-box
769                                  ?s server ?P port ?u user))
770               (mail-source-delete-crash-box)))
771         ;; We nix out the password in case the error
772         ;; was because of a wrong password being given.
773         (setq mail-source-password-cache
774               (delq (assoc from mail-source-password-cache)
775                     mail-source-password-cache))
776         0))))
777
778 (defun mail-source-check-pop (source)
779   "Check whether there is new mail."
780   (mail-source-bind (pop source)
781     (let ((from (format "%s:%s:%s" server user port))
782           (mail-source-string (format "pop:%s@%s" user server))
783           result)
784       (when (eq authentication 'password)
785         (setq password
786               (or password
787                   (cdr (assoc from mail-source-password-cache))
788                   (read-passwd
789                    (format "Password for %s at %s: " user server))))
790         (unless (assoc from mail-source-password-cache)
791           (push (cons from password) mail-source-password-cache)))
792       (when server
793         (setenv "MAILHOST" server))
794       (setq result
795             (cond
796              ;; No easy way to check whether mail is waiting for these.
797              (program)
798              (function)
799              ;; The default is to use pop3.el.
800              (t
801               (let ((pop3-password password)
802                     (pop3-maildrop user)
803                     (pop3-mailhost server)
804                     (pop3-port port)
805                     (pop3-authentication-scheme
806                      (if (eq authentication 'apop) 'apop 'pass)))
807                 (if (or debug-on-quit debug-on-error)
808                     (save-excursion (pop3-get-message-count))
809                   (condition-case err
810                       (save-excursion (pop3-get-message-count))
811                     (error
812                      ;; We nix out the password in case the error
813                      ;; was because of a wrong password being given.
814                      (setq mail-source-password-cache
815                            (delq (assoc from mail-source-password-cache)
816                                  mail-source-password-cache))
817                      (signal (car err) (cdr err)))))))))
818       (if result
819           ;; Inform display-time that we have new mail.
820           (setq mail-source-new-mail-available (> result 0))
821         ;; We nix out the password in case the error
822         ;; was because of a wrong password being given.
823         (setq mail-source-password-cache
824               (delq (assoc from mail-source-password-cache)
825                     mail-source-password-cache)))
826       result)))
827
828 (defun mail-source-touch-pop ()
829   "Open and close a POP connection shortly.
830 POP server should be defined in `mail-source-primary-source' (which is
831 preferred) or `mail-sources'.  You may use it for the POP-before-SMTP
832 authentication.  To do that, you need to set the
833 `message-send-mail-function' variable as `message-smtpmail-send-it'
834 and put the following line in your ~/.gnus.el file:
835
836 \(add-hook 'message-send-mail-hook 'mail-source-touch-pop)
837
838 See the Gnus manual for details."
839   (let ((sources (if mail-source-primary-source
840                      (list mail-source-primary-source)
841                    mail-sources)))
842     (while sources
843       (if (eq 'pop (car (car sources)))
844           (mail-source-check-pop (car sources)))
845       (setq sources (cdr sources)))))
846
847 (defun mail-source-new-mail-p ()
848   "Handler for `display-time' to indicate when new mail is available."
849   ;; Flash (ie. ring the visible bell) if mail is available.
850   (if (and mail-source-flash mail-source-new-mail-available)
851       (let ((visible-bell t))
852         (ding)))
853   ;; Only report flag setting; flag is updated on a different schedule.
854   mail-source-new-mail-available)
855
856
857 (defvar mail-source-report-new-mail nil)
858 (defvar mail-source-report-new-mail-timer nil)
859 (defvar mail-source-report-new-mail-idle-timer nil)
860
861 (eval-when-compile
862   (if (featurep 'xemacs)
863       (require 'itimer)
864     (require 'timer)))
865
866 (defun mail-source-start-idle-timer ()
867   ;; Start our idle timer if necessary, so we delay the check until the
868   ;; user isn't typing.
869   (unless mail-source-report-new-mail-idle-timer
870     (setq mail-source-report-new-mail-idle-timer
871           (run-with-idle-timer
872            mail-source-idle-time-delay
873            nil
874            (lambda ()
875              (unwind-protect
876                  (mail-source-check-pop mail-source-primary-source)
877                (setq mail-source-report-new-mail-idle-timer nil)))))
878     ;; Since idle timers created when Emacs is already in the idle
879     ;; state don't get activated until Emacs _next_ becomes idle, we
880     ;; need to force our timer to be considered active now.  We do
881     ;; this by being naughty and poking the timer internals directly
882     ;; (element 0 of the vector is nil if the timer is active).
883     (aset mail-source-report-new-mail-idle-timer 0 nil)))
884
885 (defun mail-source-report-new-mail (arg)
886   "Toggle whether to report when new mail is available.
887 This only works when `display-time' is enabled."
888   (interactive "P")
889   (if (not mail-source-primary-source)
890       (error "Need to set `mail-source-primary-source' to check for new mail"))
891   (let ((on (if (null arg)
892                 (not mail-source-report-new-mail)
893               (> (prefix-numeric-value arg) 0))))
894     (setq mail-source-report-new-mail on)
895     (and mail-source-report-new-mail-timer
896          (nnheader-cancel-timer mail-source-report-new-mail-timer))
897     (and mail-source-report-new-mail-idle-timer
898          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
899     (setq mail-source-report-new-mail-timer nil)
900     (setq mail-source-report-new-mail-idle-timer nil)
901     (if on
902         (progn
903           (require 'time)
904           ;; display-time-mail-function is an Emacs 21 feature.
905           (setq display-time-mail-function #'mail-source-new-mail-p)
906           ;; Set up the main timer.
907           (setq mail-source-report-new-mail-timer
908                 (run-at-time
909                  (* 60 mail-source-report-new-mail-interval)
910                  (* 60 mail-source-report-new-mail-interval)
911                  #'mail-source-start-idle-timer))
912           ;; When you get new mail, clear "Mail" from the mode line.
913           (add-hook 'nnmail-post-get-new-mail-hook
914                     'display-time-event-handler)
915           (message "Mail check enabled"))
916       (setq display-time-mail-function nil)
917       (remove-hook 'nnmail-post-get-new-mail-hook
918                    'display-time-event-handler)
919       (message "Mail check disabled"))))
920
921 (defun mail-source-fetch-maildir (source callback)
922   "Fetcher for maildir sources."
923   (mail-source-bind (maildir source)
924     (let ((found 0)
925           mail-source-string)
926       (unless (string-match "/$" path)
927         (setq path (concat path "/")))
928       (dolist (subdir subdirs)
929         (when (file-directory-p (concat path subdir))
930           (setq mail-source-string (format "maildir:%s%s" path subdir))
931           (dolist (file (directory-files (concat path subdir) t))
932             (when (and (not (file-directory-p file))
933                        (not (if function
934                                 (funcall function file mail-source-crash-box)
935                               (let ((coding-system-for-write
936                                      mm-text-coding-system)
937                                     (coding-system-for-read
938                                      mm-text-coding-system))
939                                 (with-temp-file mail-source-crash-box
940                                   (insert-file-contents file)
941                                   (goto-char (point-min))
942 ;;;                               ;; Unix mail format
943 ;;;                               (unless (looking-at "\n*From ")
944 ;;;                                 (insert "From maildir "
945 ;;;                                         (current-time-string) "\n"))
946 ;;;                               (while (re-search-forward "^From " nil t)
947 ;;;                                 (replace-match ">From "))
948 ;;;                               (goto-char (point-max))
949 ;;;                               (insert "\n\n")
950                                   ;; MMDF mail format
951                                   (insert "\001\001\001\001\n"))
952                                 (delete-file file)))))
953               (incf found (mail-source-callback callback file))
954               (mail-source-delete-crash-box)))))
955       found)))
956
957 (eval-and-compile
958   (autoload 'imap-open "imap")
959   (autoload 'imap-authenticate "imap")
960   (autoload 'imap-mailbox-select "imap")
961   (autoload 'imap-mailbox-unselect "imap")
962   (autoload 'imap-mailbox-close "imap")
963   (autoload 'imap-search "imap")
964   (autoload 'imap-fetch "imap")
965   (autoload 'imap-close "imap")
966   (autoload 'imap-error-text "imap")
967   (autoload 'imap-message-flags-add "imap")
968   (autoload 'imap-list-to-message-set "imap")
969   (autoload 'imap-range-to-message-set "imap")
970   (autoload 'nnheader-ms-strip-cr "nnheader"))
971
972 (defvar mail-source-imap-file-coding-system 'binary
973   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
974
975 (defun mail-source-fetch-imap (source callback)
976   "Fetcher for imap sources."
977   (mail-source-bind (imap source)
978     (mail-source-run-script
979      prescript (format-spec-make ?p password ?t mail-source-crash-box
980                                  ?s server ?P port ?u user)
981      prescript-delay)
982     (let ((from (format "%s:%s:%s" server user port))
983           (found 0)
984           (buf (generate-new-buffer " *imap source*"))
985           (mail-source-string (format "imap:%s:%s" server mailbox))
986           (imap-shell-program (or (list program) imap-shell-program))
987           remove)
988       (if (and (imap-open server port stream authentication buf)
989                (imap-authenticate
990                 user (or (cdr (assoc from mail-source-password-cache))
991                          password) buf)
992                (imap-mailbox-select mailbox nil buf))
993           (let ((coding-system-for-write mail-source-imap-file-coding-system)
994                 str)
995             (with-temp-file mail-source-crash-box
996               ;; Avoid converting 8-bit chars from inserted strings to
997               ;; multibyte.
998               (mm-disable-multibyte)
999               ;; remember password
1000               (with-current-buffer buf
1001                 (when (and imap-password
1002                            (not (assoc from mail-source-password-cache)))
1003                   (push (cons from imap-password) mail-source-password-cache)))
1004               ;; if predicate is nil, use all uids
1005               (dolist (uid (imap-search (or predicate "1:*") buf))
1006                 (when (setq str
1007                             (if (imap-capability 'IMAP4rev1 buf)
1008                                 (caddar (imap-fetch uid "BODY.PEEK[]"
1009                                                     'BODYDETAIL nil buf))
1010                               (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf)))
1011                   (push uid remove)
1012                   (insert "From imap " (current-time-string) "\n")
1013                   (save-excursion
1014                     (insert str "\n\n"))
1015                   (while (re-search-forward "^From " nil t)
1016                     (replace-match ">From "))
1017                   (goto-char (point-max))))
1018               (nnheader-ms-strip-cr))
1019             (incf found (mail-source-callback callback server))
1020             (mail-source-delete-crash-box)
1021             (when (and remove fetchflag)
1022               (setq remove (nreverse remove))
1023               (imap-message-flags-add
1024                (imap-range-to-message-set (gnus-compress-sequence remove))
1025                fetchflag nil buf))
1026             (if dontexpunge
1027                 (imap-mailbox-unselect buf)
1028               (imap-mailbox-close nil buf))
1029             (imap-close buf))
1030         (imap-close buf)
1031         ;; We nix out the password in case the error
1032         ;; was because of a wrong password being given.
1033         (setq mail-source-password-cache
1034               (delq (assoc from mail-source-password-cache)
1035                     mail-source-password-cache))
1036         (error "IMAP error: %s" (imap-error-text buf)))
1037       (kill-buffer buf)
1038       (mail-source-run-script
1039        postscript
1040        (format-spec-make ?p password ?t mail-source-crash-box
1041                          ?s server ?P port ?u user))
1042       found)))
1043
1044 (eval-and-compile
1045   (autoload 'webmail-fetch "webmail"))
1046
1047 (defun mail-source-fetch-webmail (source callback)
1048   "Fetch for webmail source."
1049   (mail-source-bind (webmail source)
1050     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
1051           (webmail-newmail-only dontexpunge)
1052           (webmail-move-to-trash-can (not dontexpunge)))
1053       (when (eq authentication 'password)
1054         (setq password
1055               (or password
1056                   (cdr (assoc (format "webmail:%s:%s" subtype user)
1057                               mail-source-password-cache))
1058                   (read-passwd
1059                    (format "Password for %s at %s: " user subtype))))
1060         (when (and password
1061                    (not (assoc (format "webmail:%s:%s" subtype user)
1062                                mail-source-password-cache)))
1063           (push (cons (format "webmail:%s:%s" subtype user) password)
1064                 mail-source-password-cache)))
1065       (webmail-fetch mail-source-crash-box subtype user password)
1066       (mail-source-callback callback (symbol-name subtype))
1067       (mail-source-delete-crash-box))))
1068
1069 (provide 'mail-source)
1070
1071 ;;; arch-tag: 72948025-1d17-4d6c-bb12-ef1aa2c490fd
1072 ;;; mail-source.el ends here