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