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