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