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