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