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