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