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