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