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