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