Importing Oort Gnus v0.04.
[elisp/gnus.git-] / lisp / nnimap.el
1 ;;; nnimap.el --- imap backend for Gnus
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Simon Josefsson <jas@pdc.kth.se>
5 ;;         Jim Radford <radford@robby.caltech.edu>
6 ;; Keywords: 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 ;; Todo, major things:
28 ;;
29 ;;   o Fix Gnus to view correct number of unread/total articles in group buffer
30 ;;   o Fix Gnus to handle leading '.' in group names (fixed?)
31 ;;   o Finish disconnected mode (moving articles between mailboxes unplugged)
32 ;;   o Sieve
33 ;;   o MIME (partial article fetches)
34 ;;   o Split to other backends, different split rules for different
35 ;;     servers/inboxes
36 ;;
37 ;; Todo, minor things:
38 ;;
39 ;;   o Don't require half of Gnus -- backends should be standalone
40 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
41 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
42 ;;   o Split up big fetches (1,* header especially) in smaller chunks
43 ;;   o What do I do with gnus-newsgroup-*?
44 ;;   o Tell Gnus about new groups (how can we tell?)
45 ;;   o Respooling (fix Gnus?) (unnecessery?)
46 ;;   o Add support for the following: (if applicable)
47 ;;       request-list-newsgroups, request-regenerate
48 ;;       list-active-group,
49 ;;       request-associate-buffer, request-restore-buffer,
50 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
51 ;;   o Support RFC2221 (Login referrals)
52 ;;   o IMAP2BIS compatibility? (RFC2061)
53 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
54 ;;     .newsrc.eld)
55 ;;   o What about Gnus's article editing, can we support it?  NO!
56 ;;   o Use \Draft to support the draft group??
57 ;;   o Duplicate suppression
58
59 ;;; Code:
60
61 (require 'imap)
62 (require 'nnoo)
63 (require 'nnmail)
64 (require 'nnheader)
65 (require 'mm-util)
66 (require 'gnus)
67 (require 'gnus-range)
68 (require 'gnus-start)
69 (require 'gnus-int)
70
71 (nnoo-declare nnimap)
72
73 (defconst nnimap-version "nnimap 1.0")
74
75 (defgroup nnimap nil
76   "Reading IMAP mail with Gnus."
77   :group 'gnus)
78
79 (defvoo nnimap-address nil
80   "Address of physical IMAP server.  If nil, use the virtual server's name.")
81
82 (defvoo nnimap-server-port nil
83   "Port number on physical IMAP server.
84 If nil, defaults to 993 for SSL connections and 143 otherwise.")
85
86 ;; Splitting variables
87
88 (defcustom nnimap-split-crosspost t
89   "If non-nil, do crossposting if several split methods match the mail.
90 If nil, the first match found will be used."
91   :group 'nnimap
92   :type 'boolean)
93
94 (defcustom nnimap-split-inbox nil
95   "Name of mailbox to split mail from.
96
97 Mail is read from this mailbox and split according to rules in
98 `nnimap-split-rule'.
99
100 This can be a string or a list of strings."
101   :group 'nnimap
102   :type '(choice (string)
103                  (repeat string)))
104
105 (define-widget 'nnimap-strict-function 'function
106   "This widget only matches values that are functionp.
107
108 Warning: This means that a value that is the symbol of a not yet
109 loaded function will not match.  Use with care."
110   :match 'nnimap-strict-function-match)
111
112 (defun nnimap-strict-function-match (widget value)
113   "Ignoring WIDGET, match if VALUE is a function."
114   (functionp value))
115
116 (defcustom nnimap-split-rule nil
117   "Mail will be split according to theese rules.
118
119 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
120
121 If you'd like, for instance, one mail group for mail from the
122 \"gnus-imap\" mailing list, one group for junk mail and leave
123 everything else in the incoming mailbox, you could do something like
124 this:
125
126 \(setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
127                           (\"INBOX.junk\"        \"Subject:.*buy\")))
128
129 As you can see, `nnimap-split-rule' is a list of lists, where the first
130 element in each \"rule\" is the name of the IMAP mailbox, and the
131 second is a regexp that nnimap will try to match on the header to find
132 a fit.
133
134 The second element can also be a function.  In that case, it will be
135 called narrowed to the headers with the first element of the rule as
136 the argument.  It should return a non-nil value if it thinks that the
137 mail belongs in that group.
138
139 This variable can also have a function as its value, the function will
140 be called with the headers narrowed and should return a group where it
141 thinks the article should be splitted to.  See `nnimap-split-fancy'.
142
143 To allow for different split rules on different virtual servers, and
144 even different split rules in different inboxes on the same server,
145 the syntax of this variable have been extended along the lines of:
146
147 \(setq nnimap-split-rule
148       '((\"my1server\"    (\".*\"    ((\"ding\"    \"ding@gnus.org\")
149                                   (\"junk\"    \"From:.*Simon\")))
150         (\"my2server\"    (\"INBOX\" nnimap-split-fancy))
151         (\"my[34]server\" (\".*\"    ((\"private\" \"To:.*Simon\")
152                                   (\"junk\"    my-junk-func)))))
153
154 The virtual server name is in fact a regexp, so that the same rules
155 may apply to several servers.  In the example, the servers
156 \"my3server\" and \"my4server\" both use the same rules.  Similarly,
157 the inbox string is also a regexp.  The actual splitting rules are as
158 before, either a function, or a list with group/regexp or
159 group/function elements."
160   :group 'nnimap
161   :type '(choice :tag "Rule type"
162                  (repeat :menu-tag "Single-server"
163                          :tag "Single-server list"
164                          (list (string :tag "Mailbox")
165                                (choice :tag "Predicate"
166                                        (regexp :tag "A regexp")
167                                        (nnimap-strict-function :tag "A function"))))
168                  (choice :menu-tag "A function"
169                          :tag "A function"
170                          (function-item nnimap-split-fancy)
171                          (function-item nnmail-split-fancy)
172                          (nnimap-strict-function :tag "User-defined function"))
173                  (repeat :menu-tag "Multi-server (extended)"
174                          :tag "Multi-server list"
175                          (list (regexp :tag "Server regexp") 
176                                (list (regexp :tag "Incoming Mailbox regexp")
177                                      (repeat :tag "Rules for matching server(s) and mailbox(es)"
178                                              (list (string :tag "Destination mailbox")
179                                                    (choice :tag "Predicate"
180                                                            (regexp :tag "A Regexp")
181                                                            (nnimap-strict-function :tag "A Function")))))))))
182
183 (defcustom nnimap-split-predicate "UNSEEN UNDELETED"
184   "The predicate used to find articles to split.
185 If you use another IMAP client to peek on articles but always would
186 like nnimap to split them once it's started, you could change this to
187 \"UNDELETED\". Other available predicates are available in
188 RFC2060 section 6.4.4."
189   :group 'nnimap
190   :type 'string)
191
192 (defcustom nnimap-split-fancy nil
193   "Like `nnmail-split-fancy', which see."
194   :group 'nnimap
195   :type 'sexp)
196
197 (defcustom nnimap-close-asynchronous nil
198   "Close mailboxes asynchronously in `nnimap-close-group'.
199 This means that errors cought by nnimap when closing the mailbox will
200 not prevent Gnus from updating the group status, which may be harmful.
201 However, it increases speed."
202   :type 'boolean
203   :group 'nnimap)
204
205 ;; Authorization / Privacy variables
206
207 (defvoo nnimap-auth-method nil
208   "Obsolete.")
209
210 (defvoo nnimap-stream nil
211   "How nnimap will connect to the server.
212
213 The default, nil, will try to use the \"best\" method the server can
214 handle.
215
216 Change this if
217
218 1) you want to connect with SSL.  The SSL integration with IMAP is
219    brain-dead so you'll have to tell it specifically.
220
221 2) your server is more capable than your environment -- i.e. your
222    server accept Kerberos login's but you haven't installed the
223    `imtest' program or your machine isn't configured for Kerberos.
224
225 Possible choices: kerberos4, ssl, network")
226
227 (defvoo nnimap-authenticator nil
228   "How nnimap authenticate itself to the server.
229
230 The default, nil, will try to use the \"best\" method the server can
231 handle.
232
233 There is only one reason for fiddling with this variable, and that is
234 if your server is more capable than your environment -- i.e. you
235 connect to a server that accept Kerberos login's but you haven't
236 installed the `imtest' program or your machine isn't configured for
237 Kerberos.
238
239 Possible choices: kerberos4, cram-md5, login, anonymous.")
240
241 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
242   "Directory to keep NOV cache files for nnimap groups.
243 See also `nnimap-nov-file-name'.")
244
245 (defvoo nnimap-nov-file-name "nnimap."
246   "NOV cache base filename.
247 The group name and `nnimap-nov-file-name-suffix' will be appended.  A
248 typical complete file name would be
249 ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
250 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
251 `nnmail-use-long-file-names' is nil")
252
253 (defvoo nnimap-nov-file-name-suffix ".novcache"
254   "Suffix for NOV cache base filename.")
255
256 (defvoo nnimap-nov-is-evil nil
257   "If non-nil, nnimap will never generate or use a local nov database for this backend.
258 Using nov databases will speed up header fetching considerably.
259 Unlike other backends, you do not need to take special care if you
260 flip this variable.")
261
262 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
263   "Whether to expunge a group when it is closed.
264 When a IMAP group with articles marked for deletion is closed, this
265 variable determine if nnimap should actually remove the articles or
266 not.
267
268 If always, nnimap always perform a expunge when closing the group.
269 If never, nnimap never expunges articles marked for deletion.
270 If ask, nnimap will ask you if you wish to expunge marked articles.
271
272 When setting this variable to `never', you can only expunge articles
273 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
274
275 (defvoo nnimap-list-pattern "*"
276   "A string LIMIT or list of strings with mailbox wildcards used to limit available groups.
277 See below for available wildcards.
278
279 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
280 REFERENCE will be passed as the first parameter to LIST/LSUB.  The
281 semantics of this are server specific, on the University of Washington
282 server you can specify a directory.
283
284 Example:
285  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
286
287 There are two wildcards * and %. * matches everything, % matches
288 everything in the current hierarchy.")
289
290 (defvoo nnimap-news-groups nil
291   "IMAP support a news-like mode, also known as bulletin board mode,
292 where replies is sent via IMAP instead of SMTP.
293
294 This variable should contain a regexp matching groups where you wish
295 replies to be stored to the mailbox directly.
296
297 Example:
298   '(\"^[^I][^N][^B][^O][^X].*$\")
299
300 This will match all groups not beginning with \"INBOX\".
301
302 Note that there is nothing technically different between mail-like and
303 news-like mailboxes.  If you wish to have a group with todo items or
304 similar which you wouldn't want to set up a mailing list for, you can
305 use this to make replies go directly to the group.")
306
307 (defvoo nnimap-expunge-search-string "UID %s NOT SINCE %s"
308   "IMAP search command to use for articles that are to be expired.
309 The first %s is replaced by a UID set of articles to search on,
310 and the second %s is replaced by a date criterium.
311
312 One useful (and perhaps the only useful) value to change this to would
313 be `UID %s NOT SENTSINCE %s' to make nnimap use the Date: header
314 instead of the internal date of messages.  See section 6.4.4 of RFC
315 2060 for more information on valid strings.")
316
317 (defvoo nnimap-importantize-dormant t
318   "If non-nil, mark \"dormant\" articles as \"ticked\" for other IMAP clients.
319 Note that within Gnus, dormant articles will still (only) be
320 marked as ticked.  This is to make \"dormant\" articles stand out,
321 just like \"ticked\" articles, in other IMAP clients.")
322
323 (defvoo nnimap-server-address nil
324   "Obsolete.  Use `nnimap-address'.")
325
326 (defcustom nnimap-authinfo-file "~/.authinfo"
327   "Authorization information for IMAP servers.  In .netrc format."
328   :type
329   '(choice file
330            (repeat :tag "Entries"
331                    :menu-tag "Inline"
332                    (list :format "%v"
333                          :value ("" ("login" . "") ("password" . ""))
334                          (string :tag "Host")
335                          (checklist :inline t
336                                     (cons :format "%v"
337                                           (const :format "" "login")
338                                           (string :format "Login: %v"))
339                                     (cons :format "%v"
340                                           (const :format "" "password")
341                                           (string :format "Password: %v")))))))
342
343 (defcustom nnimap-prune-cache t
344   "If non-nil, nnimap check whether articles still exist on server before using data stored in NOV cache."
345   :type 'boolean)
346
347 (defvar nnimap-request-list-method 'imap-mailbox-list
348   "Method to use to request a list of all folders from the server.
349 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
350 restrict visible folders.")
351
352 ;; Internal variables:
353
354 (defvar nnimap-debug nil
355   "Name of buffer to record debugging info.
356 For example: (setq nnimap-debug \"*nnimap-debug*\")")
357 (defvar nnimap-current-move-server nil)
358 (defvar nnimap-current-move-group nil)
359 (defvar nnimap-current-move-article nil)
360 (defvar nnimap-length)
361 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
362 (defvar nnimap-progress-how-often 20)
363 (defvar nnimap-counter)
364 (defvar nnimap-callback-callback-function nil
365   "Gnus callback the nnimap asynchronous callback should call.")
366 (defvar nnimap-callback-buffer nil
367   "Which buffer the asynchronous article prefetch callback should work in.")
368 (defvar nnimap-server-buffer-alist nil) ;; Map server name to buffers.
369 (defvar nnimap-current-server nil) ;; Current server
370 (defvar nnimap-server-buffer nil) ;; Current servers' buffer
371
372 \f
373
374 (nnoo-define-basics nnimap)
375
376 ;; Utility functions:
377
378 (defsubst nnimap-get-server-buffer (server)
379   "Return buffer for SERVER, if nil use current server."
380   (cadr (assoc (or server nnimap-current-server) nnimap-server-buffer-alist)))
381
382 (defun nnimap-possibly-change-server (server)
383   "Return buffer for SERVER, changing the current server as a side-effect.
384 If SERVER is nil, uses the current server."
385   (setq nnimap-current-server (or server nnimap-current-server)
386         nnimap-server-buffer (nnimap-get-server-buffer nnimap-current-server)))
387
388 (defun nnimap-verify-uidvalidity (group server)
389   "Verify stored uidvalidity match current one in GROUP on SERVER."
390   (let* ((gnusgroup (gnus-group-prefixed-name
391                      group (gnus-server-to-method
392                             (format "nnimap:%s" server))))
393          (new-uidvalidity (imap-mailbox-get 'uidvalidity))
394          (old-uidvalidity (gnus-group-get-parameter gnusgroup 'uidvalidity))
395          (dir (file-name-as-directory (expand-file-name nnimap-directory)))
396          (nameuid (nnheader-translate-file-chars
397                    (concat nnimap-nov-file-name
398                            (if (equal server "")
399                                "unnamed"
400                              server) "." group "." old-uidvalidity
401                            nnimap-nov-file-name-suffix) t))
402          (file (if (or nnmail-use-long-file-names
403                        (file-exists-p (expand-file-name nameuid dir)))
404                    (expand-file-name nameuid dir)
405                  (expand-file-name
406                   (mm-encode-coding-string
407                    (nnheader-replace-chars-in-string nameuid ?. ?/)
408                    nnmail-pathname-coding-system)
409                   dir))))
410     (if old-uidvalidity
411         (if (not (equal old-uidvalidity new-uidvalidity))
412             ;; uidvalidity clash
413             (gnus-delete-file file)
414           (gnus-group-set-parameter gnusgroup 'uidvalidity new-uidvalidity)
415           t)
416       (gnus-group-add-parameter gnusgroup (cons 'uidvalidity new-uidvalidity))
417       t)))
418
419 (defun nnimap-before-find-minmax-bugworkaround ()
420   "Function called before iterating through mailboxes with
421 `nnimap-find-minmax-uid'."
422   ;; XXX this is for UoW imapd problem, it doesn't notice new mail in
423   ;; currently selected mailbox without a re-select/examine.
424   (or (null (imap-current-mailbox nnimap-server-buffer))
425       (imap-mailbox-unselect nnimap-server-buffer)))
426
427 (defun nnimap-find-minmax-uid (group &optional examine)
428   "Find lowest and highest active article nummber in GROUP.
429 If EXAMINE is non-nil the group is selected read-only."
430   (with-current-buffer nnimap-server-buffer
431     (when (imap-mailbox-select group examine)
432       (let (minuid maxuid)
433         (when (> (imap-mailbox-get 'exists) 0)
434           (imap-fetch "1,*" "UID" nil 'nouidfetch)
435           (imap-message-map (lambda (uid Uid)
436                               (setq minuid (if minuid (min minuid uid) uid)
437                                     maxuid (if maxuid (max maxuid uid) uid)))
438                             'UID))
439         (list (imap-mailbox-get 'exists) minuid maxuid)))))
440
441 (defun nnimap-possibly-change-group (group &optional server)
442   "Make GROUP the current group, and SERVER the current server."
443   (when (nnimap-possibly-change-server server)
444     (with-current-buffer nnimap-server-buffer
445       (if (or (null group) (imap-current-mailbox-p group))
446           imap-current-mailbox
447         (if (imap-mailbox-select group)
448             (if (or (nnimap-verify-uidvalidity
449                      group (or server nnimap-current-server))
450                     (zerop (imap-mailbox-get 'exists group))
451                     t ;; for OGnus to see if ignoring uidvalidity
452                     ;; changes has any bad effects.
453                     (yes-or-no-p
454                      (format
455                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
456                 imap-current-mailbox
457               (imap-mailbox-unselect)
458               (error "nnimap: Group %s is not uid-valid" group))
459           (nnheader-report 'nnimap (imap-error-text)))))))
460
461 (defun nnimap-replace-whitespace (string)
462   "Return STRING with all whitespace replaced with space."
463   (when string
464     (while (string-match "[\r\n\t]+" string)
465       (setq string (replace-match " " t t string)))
466     string))
467
468 ;; Required backend functions
469
470 (defun nnimap-retrieve-headers-progress ()
471   "Hook to insert NOV line for current article into `nntp-server-buffer'."
472   (and (numberp nnmail-large-newsgroup)
473        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
474        (> nnimap-length nnmail-large-newsgroup)
475        (nnheader-message 6 "nnimap: Retrieving headers... %c"
476                          (nth (/ (% nnimap-counter
477                                     (* (length nnimap-progress-chars)
478                                        nnimap-progress-how-often))
479                                  nnimap-progress-how-often)
480                               nnimap-progress-chars)))
481   (with-current-buffer nntp-server-buffer
482     (let (headers lines chars uid mbx)
483       (with-current-buffer nnimap-server-buffer
484         (setq uid imap-current-message
485               mbx imap-current-mailbox
486               headers (nnimap-demule
487                        (if (imap-capability 'IMAP4rev1)
488                            ;; xxx don't just use car? alist doesn't contain
489                            ;; anything else now, but it might...
490                            (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
491                          (imap-message-get uid 'RFC822.HEADER)))
492               lines (imap-body-lines (imap-message-body imap-current-message))
493               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
494       (nnheader-insert-nov
495        (with-temp-buffer
496          (buffer-disable-undo)
497          (insert headers)
498          (nnheader-ms-strip-cr)
499          (nnheader-fold-continuation-lines)
500          (subst-char-in-region (point-min) (point-max) ?\t ? )
501          (let ((head (nnheader-parse-head 'naked)))
502            (mail-header-set-number head uid)
503            (mail-header-set-chars head chars)
504            (mail-header-set-lines head lines)
505            (mail-header-set-xref
506             head (format "%s %s:%d" (system-name) mbx uid))
507            head))))))
508
509 (defun nnimap-retrieve-which-headers (articles fetch-old)
510   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
511   (with-current-buffer nnimap-server-buffer
512     (if (numberp (car-safe articles))
513         (imap-search
514          (concat "UID "
515                  (imap-range-to-message-set
516                   (gnus-compress-sequence
517                    (append (gnus-uncompress-sequence
518                             (and fetch-old
519                                  (cons (if (numberp fetch-old)
520                                            (max 1 (- (car articles) fetch-old))
521                                          1)
522                                        (1- (car articles)))))
523                            articles)))))
524       (mapcar (lambda (msgid)
525                 (imap-search
526                  (format "HEADER Message-Id \"%s\"" msgid)))
527               articles))))
528
529 (defun nnimap-group-overview-filename (group server)
530   "Make pathname for GROUP on SERVER."
531   (let* ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
532          (uidvalidity (gnus-group-get-parameter
533                        (gnus-group-prefixed-name
534                         group (gnus-server-to-method
535                                (format "nnimap:%s" server)))
536                        'uidvalidity))
537          (name (nnheader-translate-file-chars
538                 (concat nnimap-nov-file-name
539                         (if (equal server "")
540                             "unnamed"
541                           server) "." group nnimap-nov-file-name-suffix) t))
542          (nameuid (nnheader-translate-file-chars
543                    (concat nnimap-nov-file-name
544                            (if (equal server "")
545                                "unnamed"
546                              server) "." group "." uidvalidity
547                            nnimap-nov-file-name-suffix) t))
548          (oldfile (if (or nnmail-use-long-file-names
549                           (file-exists-p (expand-file-name name dir)))
550                       (expand-file-name name dir)
551                     (expand-file-name
552                      (mm-encode-coding-string
553                       (nnheader-replace-chars-in-string name ?. ?/)
554                       nnmail-pathname-coding-system)
555                      dir)))
556          (newfile (if (or nnmail-use-long-file-names
557                           (file-exists-p (expand-file-name nameuid dir)))
558                       (expand-file-name nameuid dir)
559                     (expand-file-name
560                      (mm-encode-coding-string
561                       (nnheader-replace-chars-in-string nameuid ?. ?/)
562                       nnmail-pathname-coding-system)
563                      dir))))
564     (when (and (file-exists-p oldfile) (not (file-exists-p newfile)))
565       (message "nnimap: Upgrading novcache filename...")
566       (sit-for 1)
567       (gnus-make-directory (file-name-directory newfile))
568       (unless (ignore-errors (rename-file oldfile newfile) t)
569         (if (ignore-errors (copy-file oldfile newfile) t)
570             (delete-file oldfile)
571           (error "Can't rename `%s' to `%s'" oldfile newfile))))
572     newfile))
573
574 (defun nnimap-retrieve-headers-from-file (group server)
575   (with-current-buffer nntp-server-buffer
576     (let ((nov (nnimap-group-overview-filename group server)))
577       (when (file-exists-p nov)
578         (mm-insert-file-contents nov)
579         (set-buffer-modified-p nil)
580         (let ((min (ignore-errors (goto-char (point-min))
581                                   (read (current-buffer))))
582               (max (ignore-errors (goto-char (point-max))
583                                   (forward-line -1)
584                                   (read (current-buffer)))))
585           (if (and (numberp min) (numberp max))
586               (cons min max)
587             ;; junk, remove it, it's saved later
588             (erase-buffer)
589             nil))))))
590
591 (defun nnimap-retrieve-headers-from-server (articles group server)
592   (with-current-buffer nnimap-server-buffer
593     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
594           (nnimap-length (gnus-range-length articles))
595           (nnimap-counter 0))
596       (imap-fetch (imap-range-to-message-set articles)
597                   (concat "(UID RFC822.SIZE BODY "
598                           (let ((headers
599                                  (append '(Subject From Date Message-Id
600                                                    References In-Reply-To Xref)
601                                          (copy-sequence
602                                           nnmail-extra-headers))))
603                             (if (imap-capability 'IMAP4rev1)
604                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
605                               (format "RFC822.HEADER.LINES %s)" headers)))))
606       (and (numberp nnmail-large-newsgroup)
607            (> nnimap-length nnmail-large-newsgroup)
608            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
609
610 (defun nnimap-dont-use-nov-p (group server)
611   (or gnus-nov-is-evil nnimap-nov-is-evil
612       (unless (and (gnus-make-directory
613                     (file-name-directory
614                      (nnimap-group-overview-filename group server)))
615                    (file-writable-p
616                     (nnimap-group-overview-filename group server)))
617         (message "nnimap: Nov cache not writable, %s"
618                  (nnimap-group-overview-filename group server)))))
619
620 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
621   (when (nnimap-possibly-change-group group server)
622     (with-current-buffer nntp-server-buffer
623       (erase-buffer)
624       (if (nnimap-dont-use-nov-p group server)
625           (nnimap-retrieve-headers-from-server
626            (gnus-compress-sequence articles) group server)
627         (let (uids cached low high)
628           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
629                       low (car uids)
630                       high (car (last uids)))
631             (if (setq cached (nnimap-retrieve-headers-from-file group server))
632                 (progn
633                   ;; fetch articles with uids before cache block
634                   (when (< low (car cached))
635                     (goto-char (point-min))
636                     (nnimap-retrieve-headers-from-server
637                      (cons low (1- (car cached))) group server))
638                   ;; fetch articles with uids after cache block
639                   (when (> high (cdr cached))
640                     (goto-char (point-max))
641                     (nnimap-retrieve-headers-from-server
642                      (cons (1+ (cdr cached)) high) group server))
643                   (when nnimap-prune-cache
644               ;; remove nov's for articles which has expired on server
645                     (goto-char (point-min))
646                     (dolist (uid (gnus-set-difference articles uids))
647                       (when (re-search-forward (format "^%d\t" uid) nil t)
648                         (gnus-delete-line)))))
649               ;; nothing cached, fetch whole range from server
650               (nnimap-retrieve-headers-from-server
651                (cons low high) group server))
652             (when (buffer-modified-p)
653               (nnmail-write-region
654                1 (point-max) (nnimap-group-overview-filename group server)
655                nil 'nomesg))
656             (nnheader-nov-delete-outside-range low high))))
657       'nov)))
658
659 (defun nnimap-open-connection (server)
660   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
661                       nnimap-authenticator nnimap-server-buffer))
662       (nnheader-report 'nnimap "Can't open connection to server %s" server)
663     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
664                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
665       (imap-close nnimap-server-buffer)
666       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
667     (let* ((list (gnus-parse-netrc nnimap-authinfo-file))
668            (port (if nnimap-server-port
669                      (int-to-string nnimap-server-port)
670                    "imap"))
671            (alist (gnus-netrc-machine list (or nnimap-server-address
672                                                nnimap-address server)
673                                       port "imap"))
674            (user (gnus-netrc-get alist "login"))
675            (passwd (gnus-netrc-get alist "password")))
676       (if (imap-authenticate user passwd nnimap-server-buffer)
677           (prog1
678               (push (list server nnimap-server-buffer)
679                     nnimap-server-buffer-alist)
680             (nnimap-possibly-change-server server))
681         (imap-close nnimap-server-buffer)
682         (kill-buffer nnimap-server-buffer)
683         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
684
685 (deffoo nnimap-open-server (server &optional defs)
686   (nnheader-init-server-buffer)
687   (if (nnimap-server-opened server)
688       t
689     (unless (assq 'nnimap-server-buffer defs)
690       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
691     ;; translate `nnimap-server-address' to `nnimap-address' in defs
692     ;; for people that configured nnimap with a very old version
693     (unless (assq 'nnimap-address defs)
694       (if (assq 'nnimap-server-address defs)
695           (push (list 'nnimap-address
696                       (cadr (assq 'nnimap-server-address defs))) defs)
697         (push (list 'nnimap-address server) defs)))
698     (nnoo-change-server 'nnimap server defs)
699     (or nnimap-server-buffer
700         (setq nnimap-server-buffer (cadr (assq 'nnimap-server-buffer defs))))
701     (with-current-buffer (get-buffer-create nnimap-server-buffer)
702       (nnoo-change-server 'nnimap server defs))
703     (or (and nnimap-server-buffer
704              (imap-opened nnimap-server-buffer))
705         (nnimap-open-connection server))))
706
707 (deffoo nnimap-server-opened (&optional server)
708   "Whether SERVER is opened.
709 If SERVER is the current virtual server, and the connection to the
710 physical server is alive, this function return a non-nil value.  If
711 SERVER is nil, it is treated as the current server."
712   ;; clean up autologouts??
713   (and (or server nnimap-current-server)
714        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
715        (imap-opened (nnimap-get-server-buffer server))))
716
717 (deffoo nnimap-close-server (&optional server)
718   "Close connection to server and free all resources connected to it.
719 Return nil if the server couldn't be closed for some reason."
720   (let ((server (or server nnimap-current-server)))
721     (when (or (nnimap-server-opened server)
722               (imap-opened (nnimap-get-server-buffer server)))
723       (imap-close (nnimap-get-server-buffer server))
724       (kill-buffer (nnimap-get-server-buffer server))
725       (setq nnimap-server-buffer nil
726             nnimap-current-server nil
727             nnimap-server-buffer-alist
728             (delq server nnimap-server-buffer-alist)))
729     (nnoo-close-server 'nnimap server)))
730
731 (deffoo nnimap-request-close ()
732   "Close connection to all servers and free all resources that the backend have reserved.
733 All buffers that have been created by that
734 backend should be killed.  (Not the nntp-server-buffer, though.) This
735 function is generally only called when Gnus is shutting down."
736   (mapcar (lambda (server) (nnimap-close-server (car server)))
737           nnimap-server-buffer-alist)
738   (setq nnimap-server-buffer-alist nil))
739
740 (deffoo nnimap-status-message (&optional server)
741   "This function returns the last error message from server."
742   (when (nnimap-possibly-change-server server)
743     (nnoo-status-message 'nnimap server)))
744
745 (defun nnimap-demule (string)
746   (funcall (if (and (fboundp 'string-as-multibyte)
747                     (subrp (symbol-function 'string-as-multibyte)))
748                'string-as-multibyte
749              'identity)
750            (or string "")))
751
752 (defun nnimap-callback ()
753   (remove-hook 'imap-fetch-data-hook 'nnimap-callback)
754   (with-current-buffer nnimap-callback-buffer
755     (insert
756      (with-current-buffer nnimap-server-buffer
757        (nnimap-demule
758         (if (imap-capability 'IMAP4rev1)
759             ;; xxx don't just use car? alist doesn't contain
760             ;; anything else now, but it might...
761             (nth 2 (car (imap-message-get (imap-current-message) 'BODYDETAIL)))
762           (imap-message-get (imap-current-message) 'RFC822)))))
763     (nnheader-ms-strip-cr)
764     (funcall nnimap-callback-callback-function t)))
765
766 (defun nnimap-request-article-part (article part prop &optional
767                                             group server to-buffer detail)
768   (when (nnimap-possibly-change-group group server)
769     (let ((article (if (stringp article)
770                        (car-safe (imap-search
771                                   (format "HEADER Message-Id \"%s\"" article)
772                                   nnimap-server-buffer))
773                      article)))
774       (when article
775         (gnus-message 10 "nnimap: Fetching (part of) article %d..." article)
776         (if (not nnheader-callback-function)
777             (with-current-buffer (or to-buffer nntp-server-buffer)
778               (erase-buffer)
779               (let ((data (imap-fetch article part prop nil
780                                       nnimap-server-buffer)))
781                 (insert (nnimap-demule (if detail
782                                            (nth 2 (car data))
783                                          data))))
784               (nnheader-ms-strip-cr)
785               (gnus-message 10 "nnimap: Fetching (part of) article %d...done"
786                             article)
787               (if (bobp)
788                   (nnheader-report 'nnimap "No such article: %s"
789                                    (imap-error-text nnimap-server-buffer))
790                 (cons group article)))
791           (add-hook 'imap-fetch-data-hook 'nnimap-callback)
792           (setq nnimap-callback-callback-function nnheader-callback-function
793                 nnimap-callback-buffer nntp-server-buffer)
794           (imap-fetch-asynch article part nil nnimap-server-buffer)
795           (cons group article))))))
796
797 (deffoo nnimap-asynchronous-p ()
798   t)
799
800 (deffoo nnimap-request-article (article &optional group server to-buffer)
801   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
802       (nnimap-request-article-part
803        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
804     (nnimap-request-article-part
805      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
806
807 (deffoo nnimap-request-head (article &optional group server to-buffer)
808   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
809       (nnimap-request-article-part
810        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
811     (nnimap-request-article-part
812      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
813
814 (deffoo nnimap-request-body (article &optional group server to-buffer)
815   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
816       (nnimap-request-article-part
817        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
818     (nnimap-request-article-part
819      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
820
821 (deffoo nnimap-request-group (group &optional server fast)
822   (nnimap-request-update-info-internal
823    group
824    (gnus-get-info (gnus-group-prefixed-name
825                    group (gnus-server-to-method (format "nnimap:%s" server))))
826    server)
827   (when (nnimap-possibly-change-group group server)
828     (nnimap-before-find-minmax-bugworkaround)
829     (let (info)
830       (cond (fast group)
831             ((null (setq info (nnimap-find-minmax-uid group t)))
832              (nnheader-report 'nnimap "Could not get active info for %s"
833                               group))
834             (t
835              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
836                               (max 1 (or (nth 1 info) 1))
837                               (or (nth 2 info) 0) group)
838              (nnheader-report 'nnimap "Group %s selected" group)
839              t)))))
840
841 (defun nnimap-close-group (group &optional server)
842   (with-current-buffer nnimap-server-buffer
843     (when (and (imap-opened)
844                (nnimap-possibly-change-group group server))
845       (case nnimap-expunge-on-close
846         (always (imap-mailbox-expunge nnimap-close-asynchronous)
847                  (imap-mailbox-close nnimap-close-asynchronous))
848         (ask (if (and (imap-search "DELETED")
849                        (gnus-y-or-n-p (format
850                                        "Expunge articles in group `%s'? "
851                                        imap-current-mailbox)))
852                   (progn (imap-mailbox-expunge nnimap-close-asynchronous)
853                          (imap-mailbox-close nnimap-close-asynchronous))
854                 (imap-mailbox-unselect)))
855         (t (imap-mailbox-unselect)))
856       (not imap-current-mailbox))))
857
858 (defun nnimap-pattern-to-list-arguments (pattern)
859   (mapcar (lambda (p)
860             (cons (car-safe p) (or (cdr-safe p) p)))
861           (if (and (listp pattern)
862                    (listp (cdr pattern)))
863               pattern
864             (list pattern))))
865
866 (deffoo nnimap-request-list (&optional server)
867   (when (nnimap-possibly-change-server server)
868     (with-current-buffer nntp-server-buffer
869       (erase-buffer))
870     (gnus-message 5 "nnimap: Generating active list%s..."
871                   (if (> (length server) 0) (concat " for " server) ""))
872     (nnimap-before-find-minmax-bugworkaround)
873     (with-current-buffer nnimap-server-buffer
874       (dolist (pattern (nnimap-pattern-to-list-arguments nnimap-list-pattern))
875         (dolist (mbx (funcall nnimap-request-list-method
876                               (cdr pattern) (car pattern)))
877           (or (member "\\NoSelect" (imap-mailbox-get 'list-flags mbx))
878               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
879                 (when info
880                   (with-current-buffer nntp-server-buffer
881                     (insert (format "\"%s\" %d %d y\n"
882                                     mbx (or (nth 2 info) 0)
883                                     (max 1 (or (nth 1 info) 1)))))))))))
884     (gnus-message 5 "nnimap: Generating active list%s...done"
885                   (if (> (length server) 0) (concat " for " server) ""))
886     t))
887
888 (deffoo nnimap-request-post (&optional server)
889   (let ((success t))
890     (dolist (mbx (message-unquote-tokens
891                   (message-tokenize-header
892                    (message-fetch-field "Newsgroups") ", ")) success)
893       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
894         (or (gnus-active to-newsgroup)
895             (gnus-activate-group to-newsgroup)
896             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
897                                        to-newsgroup))
898                 (or (and (gnus-request-create-group
899                           to-newsgroup gnus-command-method)
900                          (gnus-activate-group to-newsgroup nil nil
901                                               gnus-command-method))
902                     (error "Couldn't create group %s" to-newsgroup)))
903             (error "No such group: %s" to-newsgroup))
904         (unless (nnimap-request-accept-article mbx (nth 1 gnus-command-method))
905           (setq success nil))))))
906
907 ;; Optional backend functions
908
909 (deffoo nnimap-retrieve-groups (groups &optional server)
910   (when (nnimap-possibly-change-server server)
911     (gnus-message 5 "nnimap: Checking mailboxes...")
912     (with-current-buffer nntp-server-buffer
913       (erase-buffer)
914       (nnimap-before-find-minmax-bugworkaround)
915       (dolist (group groups)
916         (gnus-message 7 "nnimap: Checking mailbox %s" group)
917         (or (member "\\NoSelect"
918                     (imap-mailbox-get 'list-flags group nnimap-server-buffer))
919             (let ((info (nnimap-find-minmax-uid group 'examine)))
920               (when (> (or (imap-mailbox-get 'recent group 
921                                              nnimap-server-buffer) 0)
922                        0)
923                 (push (list (cons group 0)) nnmail-split-history))
924               (insert (format "\"%s\" %d %d y\n" group
925                               (or (nth 2 info) 0)
926                               (max 1 (or (nth 1 info) 1))))))))
927     (gnus-message 5 "nnimap: Checking mailboxes...done")
928     'active))
929
930 (deffoo nnimap-request-update-info-internal (group info &optional server)
931   (when (nnimap-possibly-change-group group server)
932     (when info ;; xxx what does this mean? should we create a info?
933       (with-current-buffer nnimap-server-buffer
934         (gnus-message 5 "nnimap: Updating info for %s..."
935                       (gnus-info-group info))
936
937         (when (nnimap-mark-permanent-p 'read)
938           (let (seen unseen)
939             ;; read info could contain articles marked unread by other
940             ;; imap clients!  we correct this
941             (setq seen (gnus-uncompress-range (gnus-info-read info))
942                   unseen (imap-search "UNSEEN UNDELETED")
943                   seen (gnus-set-difference seen unseen)
944                   ;; seen might lack articles marked as read by other
945                   ;; imap clients! we correct this
946                   seen (append seen (imap-search "SEEN"))
947                   ;; remove dupes
948                   seen (sort seen '<)
949                   seen (gnus-compress-sequence seen t)
950                   ;; we can't return '(1) since this isn't a "list of ranges",
951                   ;; and we can't return '((1)) since g-list-of-unread-articles
952                   ;; is buggy so we return '((1 . 1)).
953                   seen (if (and (integerp (car seen))
954                                 (null (cdr seen)))
955                            (list (cons (car seen) (car seen)))
956                          seen))
957             (gnus-info-set-read info seen)))
958
959         (mapcar (lambda (pred)
960                   (when (or (eq (cdr pred) 'recent)
961                             (and (nnimap-mark-permanent-p (cdr pred))
962                                  (member (nnimap-mark-to-flag (cdr pred))
963                                          (imap-mailbox-get 'flags))))
964                     (gnus-info-set-marks
965                      info
966                      (gnus-update-alist-soft
967                       (cdr pred)
968                       (gnus-compress-sequence
969                        (imap-search (nnimap-mark-to-predicate (cdr pred))))
970                       (gnus-info-marks info))
971                      t)))
972                 gnus-article-mark-lists)
973
974         (when nnimap-importantize-dormant
975       ;; nnimap mark dormant article as ticked too (for other clients)
976           ;; so we remove that mark for gnus since we support dormant
977           (gnus-info-set-marks
978            info
979            (gnus-update-alist-soft
980             'tick
981             (gnus-remove-from-range
982              (cdr-safe (assoc 'tick (gnus-info-marks info)))
983              (cdr-safe (assoc 'dormant (gnus-info-marks info))))
984             (gnus-info-marks info))
985            t))
986
987         (gnus-message 5 "nnimap: Updating info for %s...done"
988                       (gnus-info-group info))
989
990         info))))
991
992 (deffoo nnimap-request-type (group &optional article)
993   (if (and nnimap-news-groups (string-match nnimap-news-groups group))
994       'news
995     'mail))
996
997 (deffoo nnimap-request-set-mark (group actions &optional server)
998   (when (nnimap-possibly-change-group group server)
999     (with-current-buffer nnimap-server-buffer
1000       (let (action)
1001         (gnus-message 7 "nnimap: Setting marks in %s..." group)
1002         (while (setq action (pop actions))
1003           (let ((range (nth 0 action))
1004                 (what  (nth 1 action))
1005                 (cmdmarks (nth 2 action))
1006                 marks)
1007             ;; bookmark can't be stored (not list/range
1008             (setq cmdmarks (delq 'bookmark cmdmarks))
1009             ;; killed can't be stored (not list/range
1010             (setq cmdmarks (delq 'killed cmdmarks))
1011             ;; unsent are for nndraft groups only
1012             (setq cmdmarks (delq 'unsent cmdmarks))
1013             ;; cache flags are pointless on the server
1014             (setq cmdmarks (delq 'cache cmdmarks))
1015             ;; seen flags are local to each gnus
1016             (setq cmdmarks (delq 'seen cmdmarks))
1017             ;; recent marks can't be set
1018             (setq cmdmarks (delq 'recent cmdmarks))
1019             (when nnimap-importantize-dormant
1020               ;; flag dormant articles as ticked
1021               (if (memq 'dormant cmdmarks)
1022                   (setq cmdmarks (cons 'tick cmdmarks))))
1023             ;; remove stuff we are forbidden to store
1024             (mapcar (lambda (mark)
1025                       (if (imap-message-flag-permanent-p
1026                            (nnimap-mark-to-flag mark))
1027                           (setq marks (cons mark marks))))
1028                     cmdmarks)
1029             (when (and range marks)
1030               (cond ((eq what 'del)
1031                      (imap-message-flags-del
1032                       (imap-range-to-message-set range)
1033                       (nnimap-mark-to-flag marks nil t)))
1034                     ((eq what 'add)
1035                      (imap-message-flags-add
1036                       (imap-range-to-message-set range)
1037                       (nnimap-mark-to-flag marks nil t)))
1038                     ((eq what 'set)
1039                      (imap-message-flags-set
1040                       (imap-range-to-message-set range)
1041                       (nnimap-mark-to-flag marks nil t)))))))
1042         (gnus-message 7 "nnimap: Setting marks in %s...done" group))))
1043   nil)
1044
1045 (defun nnimap-split-fancy ()
1046   "Like nnmail-split-fancy, but uses nnimap-split-fancy."
1047   (let ((nnmail-split-fancy nnimap-split-fancy))
1048     (nnmail-split-fancy)))
1049
1050 (defun nnimap-split-to-groups (rules)
1051   ;; tries to match all rules in nnimap-split-rule against content of
1052   ;; nntp-server-buffer, returns a list of groups that matched.
1053   (with-current-buffer nntp-server-buffer
1054     ;; Fold continuation lines.
1055     (goto-char (point-min))
1056     (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1057       (replace-match " " t t))
1058     (if (functionp rules)
1059         (funcall rules)
1060       (let (to-groups regrepp)
1061         (catch 'split-done
1062           (dolist (rule rules to-groups)
1063             (let ((group (car rule))
1064                   (regexp (cadr rule)))
1065               (goto-char (point-min))
1066               (when (and (if (stringp regexp)
1067                              (progn
1068                                (setq regrepp (string-match "\\\\[0-9&]" group))
1069                                (re-search-forward regexp nil t))
1070                            (funcall regexp group))
1071                  ;; Don't enter the article into the same group twice.
1072                          (not (assoc group to-groups)))
1073                 (push (if regrepp
1074                           (nnmail-expand-newtext group)
1075                         group)
1076                       to-groups)
1077                 (or nnimap-split-crosspost
1078                     (throw 'split-done to-groups))))))))))
1079
1080 (defun nnimap-assoc-match (key alist)
1081   (let (element)
1082     (while (and alist (not element))
1083       (if (string-match (car (car alist)) key)
1084           (setq element (car alist)))
1085       (setq alist (cdr alist)))
1086     element))
1087
1088 (defun nnimap-split-find-rule (server inbox)
1089   (if (and (listp nnimap-split-rule) (listp (car nnimap-split-rule))
1090            (list (cdar nnimap-split-rule)) (listp (cadar nnimap-split-rule)))
1091       ;; extended format
1092       (cadr (nnimap-assoc-match inbox (cdr (nnimap-assoc-match
1093                                             server nnimap-split-rule))))
1094     nnimap-split-rule))
1095
1096 (defun nnimap-split-find-inbox (server)
1097   (if (listp nnimap-split-inbox)
1098       nnimap-split-inbox
1099     (list nnimap-split-inbox)))
1100
1101 (defun nnimap-split-articles (&optional group server)
1102   (when (nnimap-possibly-change-server server)
1103     (with-current-buffer nnimap-server-buffer
1104       (let (rule inbox removeorig (inboxes (nnimap-split-find-inbox server)))
1105         ;; iterate over inboxes
1106         (while (and (setq inbox (pop inboxes))
1107                     (nnimap-possibly-change-group inbox)) ;; SELECT
1108           ;; find split rule for this server / inbox
1109           (when (setq rule (nnimap-split-find-rule server inbox))
1110             ;; iterate over articles
1111             (dolist (article (imap-search nnimap-split-predicate))
1112               (when (nnimap-request-head article)
1113                 ;; copy article to right group(s)
1114                 (setq removeorig nil)
1115                 (dolist (to-group (nnimap-split-to-groups rule))
1116                   (cond ((eq to-group 'junk)
1117                          (message "IMAP split removed %s:%s:%d" server inbox
1118                                   article)
1119                          (setq removeorig t))
1120                         ((imap-message-copy (number-to-string article)
1121                                             to-group nil 'nocopyuid)
1122                          (message "IMAP split moved %s:%s:%d to %s" server
1123                                   inbox article to-group)
1124                          (setq removeorig t)
1125                          ;; Add the group-art list to the history list.
1126                          (push (list (cons to-group 0)) nnmail-split-history))
1127                         (t
1128                          (message "IMAP split failed to move %s:%s:%d to %s"
1129                                   server inbox article to-group))))
1130                 ;; remove article if it was successfully copied somewhere
1131                 (and removeorig
1132                      (imap-message-flags-add (format "%d" article)
1133                                              "\\Seen \\Deleted")))))
1134           (when (imap-mailbox-select inbox) ;; just in case
1135             ;; todo: UID EXPUNGE (if available) to remove splitted articles
1136             (imap-mailbox-expunge)
1137             (imap-mailbox-close)))
1138         t))))
1139
1140 (deffoo nnimap-request-scan (&optional group server)
1141   (nnimap-split-articles group server))
1142
1143 (deffoo nnimap-request-newgroups (date &optional server)
1144   (when (nnimap-possibly-change-server server)
1145     (with-current-buffer nntp-server-buffer
1146       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s..."
1147                     (if (> (length server) 0) " on " "") server)
1148       (erase-buffer)
1149       (nnimap-before-find-minmax-bugworkaround)
1150       (dolist (pattern (nnimap-pattern-to-list-arguments
1151                         nnimap-list-pattern))
1152         (dolist (mbx (imap-mailbox-lsub "*" (car pattern) nil
1153                                         nnimap-server-buffer))
1154           (or (catch 'found
1155                 (dolist (mailbox (imap-mailbox-get 'list-flags mbx
1156                                                    nnimap-server-buffer))
1157                   (if (string= (downcase mailbox) "\\noselect")
1158                       (throw 'found t)))
1159                 nil)
1160               (let ((info (nnimap-find-minmax-uid mbx 'examine)))
1161                 (when info
1162                   (insert (format "\"%s\" %d %d y\n"
1163                                   mbx (or (nth 2 info) 0)
1164                                   (max 1 (or (nth 1 info) 1)))))))))
1165       (gnus-message 5 "nnimap: Listing subscribed mailboxes%s%s...done"
1166                     (if (> (length server) 0) " on " "") server))
1167     t))
1168
1169 (deffoo nnimap-request-create-group (group &optional server args)
1170   (when (nnimap-possibly-change-server server)
1171     (or (imap-mailbox-status group 'uidvalidity nnimap-server-buffer)
1172         (imap-mailbox-create group nnimap-server-buffer))))
1173
1174 (defun nnimap-time-substract (time1 time2)
1175   "Return TIME for TIME1 - TIME2."
1176   (let* ((ms (- (car time1) (car time2)))
1177          (ls (- (nth 1 time1) (nth 1 time2))))
1178     (if (< ls 0)
1179         (list (- ms 1) (+ (expt 2 16) ls))
1180       (list ms ls))))
1181
1182 (defun nnimap-date-days-ago (daysago)
1183   "Return date, in format \"3-Aug-1998\", for DAYSAGO days ago."
1184   (let* ((time (nnimap-time-substract (current-time) (days-to-time daysago)))
1185          (date (format-time-string
1186                 (format "%%d-%s-%%Y"
1187                         (capitalize (car (rassoc (nth 4 (decode-time time))
1188                                                  parse-time-months))))
1189                 time)))
1190     (if (eq ?0 (string-to-char date))
1191         (substring date 1)
1192       date)))
1193
1194 (defun nnimap-request-expire-articles-progress ()
1195   (gnus-message 5 "nnimap: Marking article %d for deletion..."
1196                 imap-current-message))
1197
1198
1199 (defun nnimap-expiry-target (arts group server)
1200   (unless (eq nnmail-expiry-target 'delete)
1201     (with-temp-buffer
1202       (dolist (art (gnus-uncompress-sequence arts))
1203         (nnimap-request-article art group server  (current-buffer))
1204         ;; hints for optimization in `nnimap-request-accept-article'
1205         (let ((nnimap-current-move-article art)
1206               (nnimap-current-move-group group)
1207               (nnimap-current-move-server server))
1208           (nnmail-expiry-target-group nnmail-expiry-target group))))
1209     ;; It is not clear if `nnmail-expiry-target' somehow cause the
1210     ;; current group to be changed or not, so we make sure here.
1211     (nnimap-possibly-change-group group server)))
1212
1213 ;; Notice that we don't actually delete anything, we just mark them deleted.
1214 (deffoo nnimap-request-expire-articles (articles group &optional server force)
1215   (let ((artseq (gnus-compress-sequence articles)))
1216     (when (and artseq (nnimap-possibly-change-group group server))
1217       (with-current-buffer nnimap-server-buffer
1218         (if force
1219             (progn
1220               (nnimap-expiry-target artseq group server)
1221               (when (imap-message-flags-add (imap-range-to-message-set artseq)
1222                                             "\\Deleted")
1223                 (setq articles nil)))
1224           (let ((days (or (and nnmail-expiry-wait-function
1225                                (funcall nnmail-expiry-wait-function group))
1226                           nnmail-expiry-wait)))
1227             (cond ((eq days 'immediate)
1228                    (nnimap-expiry-target artseq group server)
1229                    (when (imap-message-flags-add
1230                           (imap-range-to-message-set artseq) "\\Deleted")
1231                      (setq articles nil)))
1232                   ((numberp days)
1233                    (let ((oldarts (imap-search
1234                                    (format nnimap-expunge-search-string
1235                                            (imap-range-to-message-set artseq)
1236                                            (nnimap-date-days-ago days))))
1237                          (imap-fetch-data-hook
1238                           '(nnimap-request-expire-articles-progress)))
1239                      (nnimap-expiry-target oldarts group server)
1240                      (and oldarts
1241                           (imap-message-flags-add
1242                            (imap-range-to-message-set
1243                             (gnus-compress-sequence oldarts))
1244                            "\\Deleted")
1245                           (setq articles (gnus-set-difference
1246                                           articles oldarts)))))))))))
1247   ;; return articles not deleted
1248   articles)
1249
1250 (deffoo nnimap-request-move-article (article group server
1251                                              accept-form &optional last)
1252   (when (nnimap-possibly-change-server server)
1253     (save-excursion
1254       (let ((buf (get-buffer-create " *nnimap move*"))
1255             (nnimap-current-move-article article)
1256             (nnimap-current-move-group group)
1257             (nnimap-current-move-server nnimap-current-server)
1258             result)
1259         (and (nnimap-request-article article group server)
1260              (save-excursion
1261                (set-buffer buf)
1262                (buffer-disable-undo (current-buffer))
1263                (insert-buffer-substring nntp-server-buffer)
1264                (setq result (eval accept-form))
1265                (kill-buffer buf)
1266                result)
1267              (imap-message-flags-add
1268               (imap-range-to-message-set (list article))
1269               "\\Deleted" 'silent nnimap-server-buffer))
1270         result))))
1271
1272 (deffoo nnimap-request-accept-article (group &optional server last)
1273   (when (nnimap-possibly-change-server server)
1274     (let (uid)
1275       (if (setq uid
1276                 (if (string= nnimap-current-server nnimap-current-move-server)
1277                   ;; moving article within same server, speed it up...
1278                     (and (nnimap-possibly-change-group
1279                           nnimap-current-move-group)
1280                          (imap-message-copy (number-to-string
1281                                              nnimap-current-move-article)
1282                                             group 'dontcreate nil
1283                                             nnimap-server-buffer))
1284                   (with-current-buffer (current-buffer)
1285                     (goto-char (point-min))
1286                   ;; remove any 'From blabla' lines, some IMAP servers
1287                     ;; reject the entire message otherwise.
1288                     (when (looking-at "^From[^:]")
1289                       (kill-region (point) (progn (forward-line) (point))))
1290                     ;; turn into rfc822 format (\r\n eol's)
1291                     (while (search-forward "\n" nil t)
1292                       (replace-match "\r\n")))
1293                   ;; this 'or' is for Cyrus server bug
1294                   (or (null (imap-current-mailbox nnimap-server-buffer))
1295                       (imap-mailbox-unselect nnimap-server-buffer))
1296                   (imap-message-append group (current-buffer) nil nil
1297                                        nnimap-server-buffer)))
1298           (cons group (nth 1 uid))
1299         (nnheader-report 'nnimap (imap-error-text nnimap-server-buffer))))))
1300
1301 (deffoo nnimap-request-delete-group (group force &optional server)
1302   (when (nnimap-possibly-change-server server)
1303     (with-current-buffer nnimap-server-buffer
1304       (if force
1305           (or (null (imap-mailbox-status group 'uidvalidity))
1306               (imap-mailbox-delete group))
1307         ;; UNSUBSCRIBE?
1308         t))))
1309
1310 (deffoo nnimap-request-rename-group (group new-name &optional server)
1311   (when (nnimap-possibly-change-server server)
1312     (imap-mailbox-rename group new-name nnimap-server-buffer)))
1313
1314 (defun nnimap-expunge (mailbox server)
1315   (when (nnimap-possibly-change-group mailbox server)
1316     (imap-mailbox-expunge nil nnimap-server-buffer)))
1317
1318 (defun nnimap-acl-get (mailbox server)
1319   (when (nnimap-possibly-change-server server)
1320     (and (imap-capability 'ACL nnimap-server-buffer)
1321          (imap-mailbox-acl-get mailbox nnimap-server-buffer))))
1322
1323 (defun nnimap-acl-edit (mailbox method old-acls new-acls)
1324   (when (nnimap-possibly-change-server (cadr method))
1325     (unless (imap-capability 'ACL nnimap-server-buffer)
1326       (error "Your server does not support ACL editing"))
1327     (with-current-buffer nnimap-server-buffer
1328       ;; delete all removed identifiers
1329       (mapcar (lambda (old-acl)
1330                 (unless (assoc (car old-acl) new-acls)
1331                   (or (imap-mailbox-acl-delete (car old-acl) mailbox)
1332                       (error "Can't delete ACL for %s" (car old-acl)))))
1333               old-acls)
1334       ;; set all changed acl's
1335       (mapcar (lambda (new-acl)
1336                 (let ((new-rights (cdr new-acl))
1337                       (old-rights (cdr (assoc (car new-acl) old-acls))))
1338                   (unless (and old-rights new-rights
1339                                (string= old-rights new-rights))
1340                     (or (imap-mailbox-acl-set (car new-acl) new-rights mailbox)
1341                         (error "Can't set ACL for %s to %s" (car new-acl)
1342                                new-rights)))))
1343               new-acls)
1344       t)))
1345
1346 \f
1347 ;;; Internal functions
1348
1349 ;;
1350 ;; This is confusing.
1351 ;;
1352 ;; mark      => read, tick, draft, reply etc
1353 ;; flag      => "\\Seen", "\\Flagged", "\\Draft", "gnus-expire" etc
1354 ;; predicate => "SEEN", "FLAGGED", "DRAFT", "KEYWORD gnus-expire" etc
1355 ;;
1356 ;; Mark should not really contain 'read since it's not a "mark" in the Gnus
1357 ;; world, but we cheat.  Mark == gnus-article-mark-lists + '(read . read).
1358 ;;
1359
1360 (defconst nnimap-mark-to-predicate-alist
1361   (mapcar
1362    (lambda (pair)                       ; cdr is the mark
1363      (or (assoc (cdr pair)
1364                 '((read . "SEEN")
1365                   (tick . "FLAGGED")
1366                   (draft . "DRAFT")
1367                   (recent . "RECENT")
1368                   (reply . "ANSWERED")))
1369          (cons (cdr pair)
1370                (format "KEYWORD gnus-%s" (symbol-name (cdr pair))))))
1371    (cons '(read . read) gnus-article-mark-lists)))
1372
1373 (defun nnimap-mark-to-predicate (pred)
1374   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP predicate.
1375 This is a string such as \"SEEN\", \"FLAGGED\", \"KEYWORD gnus-expire\",
1376 to be used within a IMAP SEARCH query."
1377   (cdr (assq pred nnimap-mark-to-predicate-alist)))
1378
1379 (defconst nnimap-mark-to-flag-alist
1380   (mapcar
1381    (lambda (pair)
1382      (or (assoc (cdr pair)
1383                 '((read . "\\Seen")
1384                   (tick . "\\Flagged")
1385                   (draft . "\\Draft")
1386                   (recent . "\\Recent")
1387                   (reply . "\\Answered")))
1388          (cons (cdr pair)
1389                (format "gnus-%s" (symbol-name (cdr pair))))))
1390    (cons '(read . read) gnus-article-mark-lists)))
1391
1392 (defun nnimap-mark-to-flag-1 (preds)
1393   (if (and (not (null preds)) (listp preds))
1394       (cons (nnimap-mark-to-flag (car preds))
1395             (nnimap-mark-to-flag (cdr preds)))
1396     (cdr (assoc preds nnimap-mark-to-flag-alist))))
1397
1398 (defun nnimap-mark-to-flag (preds &optional always-list make-string)
1399   "Convert a Gnus mark (a symbol such as read, tick, expire) to a IMAP flag.
1400 This is a string such as \"\\Seen\", \"\\Flagged\", \"gnus-expire\", to
1401 be used in a STORE FLAGS command."
1402   (let ((result (nnimap-mark-to-flag-1 preds)))
1403     (setq result (if (and (or make-string always-list)
1404                           (not (listp result)))
1405                      (list result)
1406                    result))
1407     (if make-string
1408         (mapconcat (lambda (flag)
1409                      (if (listp flag)
1410                          (mapconcat 'identity flag " ")
1411                        flag))
1412                    result " ")
1413       result)))
1414
1415 (defun nnimap-mark-permanent-p (mark &optional group)
1416   "Return t iff MARK can be permanently (between IMAP sessions) saved on articles, in GROUP."
1417   (imap-message-flag-permanent-p (nnimap-mark-to-flag mark)))
1418
1419 (when nnimap-debug
1420   (require 'trace)
1421   (buffer-disable-undo (get-buffer-create nnimap-debug))
1422   (mapcar (lambda (f) (trace-function-background f nnimap-debug))
1423           '(
1424             nnimap-possibly-change-server
1425             nnimap-verify-uidvalidity
1426             nnimap-find-minmax-uid
1427             nnimap-before-find-minmax-bugworkaround
1428             nnimap-possibly-change-group
1429             ;;nnimap-replace-whitespace
1430             nnimap-retrieve-headers-progress
1431             nnimap-retrieve-which-headers
1432             nnimap-group-overview-filename
1433             nnimap-retrieve-headers-from-file
1434             nnimap-retrieve-headers-from-server
1435             nnimap-retrieve-headers
1436             nnimap-open-connection
1437             nnimap-open-server
1438             nnimap-server-opened
1439             nnimap-close-server
1440             nnimap-request-close
1441             nnimap-status-message
1442             ;;nnimap-demule
1443             nnimap-request-article-part
1444             nnimap-request-article
1445             nnimap-request-head
1446             nnimap-request-body
1447             nnimap-request-group
1448             nnimap-close-group
1449             nnimap-pattern-to-list-arguments
1450             nnimap-request-list
1451             nnimap-request-post
1452             nnimap-retrieve-groups
1453             nnimap-request-update-info-internal
1454             nnimap-request-type
1455             nnimap-request-set-mark
1456             nnimap-split-to-groups
1457             nnimap-split-find-rule
1458             nnimap-split-find-inbox
1459             nnimap-split-articles
1460             nnimap-request-scan
1461             nnimap-request-newgroups
1462             nnimap-request-create-group
1463             nnimap-time-substract
1464             nnimap-date-days-ago
1465             nnimap-request-expire-articles-progress
1466             nnimap-request-expire-articles
1467             nnimap-request-move-article
1468             nnimap-request-accept-article
1469             nnimap-request-delete-group
1470             nnimap-request-rename-group
1471             gnus-group-nnimap-expunge
1472             gnus-group-nnimap-edit-acl
1473             gnus-group-nnimap-edit-acl-done
1474             nnimap-group-mode-hook
1475             nnimap-mark-to-predicate
1476             nnimap-mark-to-flag-1
1477             nnimap-mark-to-flag
1478             nnimap-mark-permanent-p
1479             )))
1480
1481 (provide 'nnimap)
1482
1483 ;;; nnimap.el ends here